Django,无法获取删除按钮工作

时间:2017-09-03 15:37:23

标签: python django

我的网站中有一部分管理员可以添加小部件。但是删除任何当前窗口小部件的删除按钮不起作用。我已经在我的网站上实现了这个代码,并且它正在运行。

我从我网站的其他部分复制了相同的代码。我的网站的另一部分使用此代码有点不同,因为帖子只能由创建它的用户删除,并且任何用户都可以删除小部件,其中“access_level”字段等于“admin” 。但是,我是唯一的管理员,所以它仍然应该工作。显示窗口小部件内容的页面只有在“access_level”等于admin时才可访问,因此我不需要在删除之前验证他们是否具有该权限。请帮忙。

widget_list.html:

{% extends "base.html" %}

{% block content %}

<div class="container">
    <div class="content">
        <div class="widgets-list">
        {% for widget in widget_list %}
            <h3>{{ widget.name }}</h3>
            <h3>{{ widget.widget_order }}</h3>
            <div>
                <p>{{ widget.body }}</p>
            </div>
            {% if user.is_authenticated %}
                <a class="auth-user-options" href="{% url 'adminpanel:delete-widget' pk=widget.pk %}">Delete</a>
            {% endif %}
        {% endfor %}
        </div>
    </div>
</div>

{% endblock %}

Adminpanel app views.py:

from django.shortcuts import render
from adminpanel.forms import WidgetForm
from adminpanel.models import Widget
from django.utils import timezone

from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse,reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin
from django.views.generic import (TemplateView,ListView,
                                    DetailView,CreateView,
                                    UpdateView,DeleteView)

# Create your views here.
class CreateWidgetView(LoginRequiredMixin,CreateView):
    login_url = '/login/'
    redirect_field_name = 'index.html'
    form_class = WidgetForm
    model = Widget

    def form_valid(self,form):
        self.object = form.save(commit=False)
        self.object.save()
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('adminpanel:widgets')

class SettingsListView(ListView):
    model = Widget
    ordering = ['widget_order']

class DeleteWidget(LoginRequiredMixin,SelectRelatedMixin,DeleteView):
    model = Widget
    select_related = ('Widget',)
    success_url = reverse_lazy('adminpanel:widget')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user_id=self.request.user.id)

    def delete(self,*args,**kwargs):
        return super().delete(*args,**kwargs)

Project url spy:

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from accounts import views
from colorsets import views
from colors import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$',views.home,name='index'),
    url(r'^accounts/',include('accounts.urls',namespace='accounts')),
    url(r'^colorsets/',include('colorsets.urls',namespace='colorsets')),
    url(r'^adminpanel/',include('adminpanel.urls',namespace='adminpanel')),
]

Adminpanel app urls.py:

from django.conf.urls import url
from adminpanel import views

app_name = 'adminpanel'

urlpatterns = [
    url(r'^widgets/',views.SettingsListView.as_view(),name='widgets'),
    url(r'^new/$',views.CreateWidgetView.as_view(),name='create-widget'),
    url(r'^delete/(?P<pk>\d+)/$',views.DeleteWidget.as_view(),name='delete-widget'),
]

编辑:以下是我收到的错误,我忘了添加它。

FieldError at /adminpanel/delete/10/
Cannot resolve keyword 'user_id' into field. Choices are: body, id, name, widget_order

并且追溯指向:

/Users/garrettlove/Desktop/colors/adminpanel/views.py in get_queryset
        return queryset.filter(user_id=self.request.user.id) ...
▶ Local vars

Adminpanel app models.py(小部件模型):

from django.db import models
from adminpanel.choices import *

# Create your models here.
class Widget(models.Model):
    name = models.CharField(max_length=50)
    widget_order = models.IntegerField(blank=False,unique=True)
    display_name = models.IntegerField(choices=WIDGET_NAME_CHOICES,default=1)
    body = models.TextField(max_length=500)

    def __str__(self):
        return self.name

1 个答案:

答案 0 :(得分:0)

正如你的错误所说:

Cannot resolve keyword 'user_id' into field.

它指向这一行:

return queryset.filter(user_id=self.request.user.id)

您的queryset模型没有user_id字段。在DeleteWidget视图中,您已指定model = Widget 正如您在Widget模型中看到的那样,您有以下字段:body, id, name, widget_order。没有user_id字段。

您需要更改过滤逻辑。如果您想拥有相关的User模型,则应使用ForeignKey关系,然后您可以按User&#39; s id进行过滤。

models.py

from django.contrib.auth.models import User


class Widget(models.Model):
    # ...
    user = models.ForeignKey(User, on_delete=models.CASCADE)

然后在DeleteWidget get_queryset中,您可以执行以下操作:

return queryset.filter(user__id=self.request.user.id)
# __________________________^
# Note that there is a double underscore here!
# This is because Django uses double underscore for accessing related models in queries.