Django DeleteView选择要使用的数据库

时间:2017-10-28 16:52:08

标签: python django django-views

我将从第二个非托管数据库(pgsql)中删除一个对象。

view.py

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'
        },
    }
}

models.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

urls.py:     # - - 编码:utf-8 - -

from django.conf.urls import url
from .views import AddDomainView, DeleteDomain


urlpatterns = [
    url(r'add', AddDomainView.as_view(), name='add_domain'),
    url(r'(?P<pk>\d+)/delete/$', DeleteDomain.as_view(), 
           name='delete_domain'),

如果我尝试访问https://localhost:8080/1/delete

我明白了:

Exception Value:    
no such table: domains

在我的Consolelog中:

Internal Server Error: /domain/12/delete/
Traceback (most recent call last):
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: domains

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/utils/decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/utils/decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/home/smindorf/PycharmProjects/django/vmailpostfix/vmail/domain/views.py", line 59, in dispatch
    return super(DeleteDomain, self).dispatch(*args, **kwargs)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/views/generic/detail.py", line 115, in get
    self.object = self.get_object()
  File "/home/smindorf/PycharmProjects/django/vmailpostfix/vmail/domain/views.py", line 62, in get_object
    obj = super(DeleteDomain, self).get_object(*args, **kwargs)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/views/generic/detail.py", line 53, in get_object
    obj = queryset.get()
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/models/query.py", line 374, in get
    num = len(clone)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/models/query.py", line 232, in __len__
    self._fetch_all()
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/models/query.py", line 1118, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 894, in execute_sql
    raise original_exception
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 884, in execute_sql
    cursor.execute(sql, params)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/smindorf/PycharmProjects/venv/django/vmailpostfix/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: domains

如何在视图中选择我的pgsql-Database? 我不知道如何在我看来访问我的数据库。

由于

更新1:

在此视图中,我可以访问:

  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)

更新2:

我的数据库架构:

CREATE TABLE domains (
    id integer NOT NULL,
    domain character varying(255) NOT NULL,
    created_by character varying
);

1 个答案:

答案 0 :(得分:0)

你可以交叉检查一次名字吗?您似乎拥有用户Domains而不是domain