简体   繁体   English

Django,无法使删除按钮正常工作

[英]Django, Can't get delete button to work

I have a section of my site where an admin can add a widget. 我在网站的一部分中,管理员可以添加小部件。 However the delete button to delete any current widgets is not working. 但是,用于删除任何当前小部件的删除按钮不起作用。 I have this code implemented else where on my site and it is working. 我已经在我的网站上的其他地方实现了此代码,并且可以正常工作。

I copied the same code from the other section of my site where this is being used. 我从网站的其他部分复制了相同的代码。 The other section of my site which uses this code is a little different in that a post can only be deleted be the user who created it, and the widgets can be delete by any user with the "access_level" field is equal to "admin". 我网站的其他部分使用该代码的地方有些不同,因为只有创建该帖子的用户才能删除该帖子,并且任何用户都可以删除该小部件,并且“ access_level”字段等于“ admin” 。 However, I am the only admin so it should still work. 但是,我是唯一的管理员,因此它仍然可以正常工作。 The page that the widget stuff is displayed on is only accessible if your "access_level" is equal to admin so I don't need to validate whether or not they have the permission before deleting. 仅当您的“ access_level”等于admin时,才可以访问显示小部件材料的页面,因此在删除之前,我不需要验证它们是否具有权限。 Please help. 请帮忙。

widget_list.html: 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: Adminpanel应用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: 项目URL间谍:

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: Adminpanel应用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'),
]

EDIT: Here is the error I'm getting I forgot to add it. 编辑:这是我得到我忘记添加它的错误。

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

and the traceback points to this: 追溯指向:

/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 (widget model): Adminpanel应用程序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

As your error is saying: 正如您的错误所言:

Cannot resolve keyword 'user_id' into field.

And it points to this line: 它指向这一行:

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

It's that your queryset model does not have a user_id field. 这是因为您的queryset模型没有user_id字段。 In your DeleteWidget view you have specified model = Widget and as you see in your Widget model, you have the following fields: body, id, name, widget_order . DeleteWidget视图中,您指定了model = Widget并且在Widget模型中看到,您具有以下字段: body, id, name, widget_order There is no user_id field. 没有user_id字段。


You need to change your filtering logic. 您需要更改过滤逻辑。 If you want to have a related User model, you should use ForeignKey relation and then you can filter by the User 's id . 如果要具有相关的User模型,则应使用ForeignKey关系,然后可以按Userid进行过滤。

In your models.py : 在您的models.py

from django.contrib.auth.models import User


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

And then in your DeleteWidget 's get_queryset , you can do the following: 然后在DeleteWidgetget_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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM