django 在get()中传递变量

w8f9ii69  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(636)

使用CreateView,我显示了一个在管理面板中设置了标题的表单。我不知道如何做到这一点了,因为在上下文中设置的变量是不可见的html模板。否则,变量可见,但不显示表单域。
html文件:

<div class="navbar">
        <div class="image">
            <img src="{% static 'images/logo.png' %}">
        </div>
        <div class="text">
            <h1>{{name}}</h1>
        </div>
    </div>

    <div class="card">
        <form method="POST" action="">
            {% csrf_token %}
            {{ form.as_p }}
            <input class="button" type="submit" value="Submit">
        </form>
</div>

在这种情况下,整个表单都正确显示,但不显示标题(内容为空)。views.py:

class ItemCreate(CreateView):
    template_name = 'form/additem.html'
    model = Parts
    fields = ['number', 'item']
    success_url = reverse_lazy('parts_list')

    def form_valid(self, form):
        username = self.request.user.get_full_name()
        form.instance.user = username
        form.instance.desc = getDescFromDB(form.cleaned_data['number'])
        return super(ItemCreate, self).form_valid(form)

    def get(self, request):
        match checkUserGroup(self.request.user):
            case "Service":
                return redirect("/")
            case "Shop":
                context = {
                    'name': getHeader('PartsForm')
                }
                return super().get(request, context)

在这种情况下,页眉会正确显示,但表单不会显示(没有表单字段可见)。views.py:

class ItemCreate(CreateView):
    template_name = 'form/additem.html'
    model = Parts
    fields = ['number', 'item']
    success_url = reverse_lazy('parts_list')

    def form_valid(self, form):
        username = self.request.user.get_full_name()
        form.instance.user = username
        form.instance.desc = getDescFromDB(form.cleaned_data['number'])
        return super(ItemCreate, self).form_valid(form)

    def get(self, request):
        match checkUserGroup(self.request.user):
            case "Service":
                return redirect("/")
            case "Shop":
                context = {
                    'name': getHeader('PartsForm')
                }
                return render(request, self.template_name, context)

getHeader和checkUserGroup函数(正常工作):

def getHeader(form):
    title = Header.objects.get(name=form)
    return title.title

def checkUserGroup(user):
    if (user.groups.filter(name='Service').exists()):
        return "Service"
    elif (user.groups.filter(name='Shop').exists()):
        return "Shop"
    else:
        raise PermissionDenied()

我知道我的代码一定有很多bug,但我才刚开始玩django,还没有完全理解。

t40tm48m

t40tm48m1#

您需要覆盖dispatch方法来检查用户组,并覆盖get_context_data方法来将头添加到上下文。
你的代码应该看起来像这样(我还没有测试过):

class ItemCreate(CreateView):
    template_name = 'form/additem.html'
    model = Parts
    fields = ['number', 'item']
    success_url = reverse_lazy('parts_list')

    def form_valid(self, form):
        username = self.request.user.get_full_name()
        form.instance.user = username
        form.instance.desc = getDescFromDB(form.cleaned_data['number'])
        return super(ItemCreate, self).form_valid(form)
    
    def dispatch(self, request, *args, **kwargs):
        match checkUserGroup(self.request.user):
            case "Service":
                return redirect("/")
            case "Shop":
                return super().dispatch(request, *args, **kwargs)
                
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["name"] = getHeader('PartsForm')
        return context

在这里找到更多关于dispatch方法的信息,以及关于添加额外的上下文数据here的信息。

相关问题