Sunday, October 29, 2017

Django View classes and database selection

Hi all,

I've two databases connected in my setup.
One default (sqlite) for Djano and one postgressql (pgsql, NOT managed) for
my postfix.

In my AddDomainView(CreateView) I can access the pgsql database and
I can add Domains to the pgsql-database but in my DeleteDomain(DeleteView)
I can't because the view will always try to find the table in the sqlite3 Database where it
not is.

Here parts of my code:

view.py
-----%<-----
# -*- coding: utf-8 -*-
import socket

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponseRedirect, Http404
from django.urls.base import reverse
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from django.views.generic.edit import CreateView, DeleteView
from django.db.utils import IntegrityError
from vmail.domain.forms import CreateDomainForm
from vmail.main.models import Domains


class AddDomainView(CreateView):
    template_name = 'domain/add_domain.html'
    model = Domains
    form_class = CreateDomainForm

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(AddDomainView, self).dispatch(*args, **kwargs)

    def get_form(self, form_class=form_class):
        form = super(AddDomainView, self).get_form(form_class)
        form.fields['domain'].queryset = Domains.objects.using('pgsql').all()
        return form

    def form_valid(self, form):
        self.object = form.save(commit=False)
        try:
            socket.gethostbyname(self.object.domain)
        except socket.gaierror:
            success, level, msg = False, messages.ERROR, _('Base domain does not exist.')
        else:
            try:
                self.object.created_by = self.request.user
                self.object.save(using='pgsql')
                success, level, msg = True, messages.SUCCESS, _('Domain added.')
            except IntegrityError:
                success, level, msg = False, messages.WARNING, _('Domain already exists .')
        messages.add_message(self.request, level, msg)
        url = reverse('overview')
        return HttpResponseRedirect(url)

    def get_context_data(self, **kwargs):
        context = super(AddDomainView, self).get_context_data(**kwargs)
        context['nav_overview'] = True
        return context


class DeleteDomain(DeleteView):
    model = Domains
    template_name = 'domain/delete_domain.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(DeleteDomain, self).dispatch(*args, **kwargs)

    def get_object(self, *args, **kwargs):
        obj = super(DeleteDomain, self).get_object(*args, **kwargs)
        if obj.created_by != self.request.user :
            raise Http404
        return obj

    def get_success_url(self):
        return reverse('overview')

    def get_context_data(self, **kwargs):
        context = super(DeleteDomain, self).get_context_data(**kwargs)
        context['nav_overview'] = True
        return context
----->%-----

settings.py
-----%<-----
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'pgsql': {
        'ENGINE': 'django.db.backends.postgresql',
        'HOST': 'localhost',
        'PORT': '5432',
        'PASSWORD': 'xxxxx',
        'USER': 'vmailuser',
        'NAME': 'virtualmail',
        'OPTIONS': {
            'options': '-c search_path=public'
        },
    }
}
----->%-----

model.py:
-----%<-----
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator


class Domains(models.Model):
    id = models.AutoField(primary_key=True,
                          unique=True)
    domain = (
        models.CharField(max_length=255,
                         blank=False,
                         null=True,
                         validators=[RegexValidator(
                             regex=r"([a-zA-Z0-9-_]+\.)+[a-zA-Z0-9-_]
                                     {2,}",
                             message=_("Invalid domain name")
                         )],
                         help_text=_('Please enter the email Domain 
                                     here')    
                         )
    )
    created_by = (
        models.CharField(max_length=255)
    )

    class Meta:
        managed = False
        db_table = 'domains'

    def __unicode__(self):
        return self.domain
----->%-----

So how can I select the right database in the class-view?
And please remember, the pgsql is unmanaged in the model class. ;)

Kind regards,
Sören

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALFRwjhnuQGwOHw%3DOzCOrZpqZqOO9v4GmnLECstea9tzSUJogg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment