具有通用UpdateView的RadioSelect小部件

时间:2019-05-12 10:10:26

标签: django

,由UpdateView更新。我想为此添加单选。我找到的所有解决方案都是forms.py,但是由于我使用UpdateView,因此我不会在表单中使用widget。有什么想法吗?

views.py

class AddPersonView(LoginRequiredMixin, UserPassesTestMixin, UpdateView)
    model = Trip
    template_name = 'tripplanner/add_new_member.html'
    fields = ["members"]
    success_url = '/'


    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        detailView = self.get_object()
        if self.request.user in detailView.members.all() or self.request.user in detailView.owners.all():
            return True
        return False

.html

{% extends "tripplanner/base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block content %}
    <div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">{% trans "New member" %}</legend>
                {{ form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">{% trans "Add" %}</button>
            </div>
        </form>
    </div>
{% endblock content %}

1 个答案:

答案 0 :(得分:1)

  

我找到的所有解决方案都是NA,但是由于我使用forms.py,所以我不会在表单中使用小部件。

一个完全不排除另一个。实际上,在UpdateViewCreateView中指定表单类是很常见的。即使您自己没有指定UpdateView,在幕后您的Form也会使用默认元素为您构造一个UpdateView。实际上,在ModelFormMixin class [GitHub]中,我们看到:

class ModelFormMixin(FormMixin, SingleObjectMixin):

    # ...

    def get_form_class(self):
        # ...
        return model_forms.modelform_factory(model, fields=self.fields)

因此,在幕后,它使用modelform_factory和您提供的ModelForm为您构造一个fields。但是,没有什么阻止您指定自己的表单并使用该表单。

因此,在forms.py中,您可以在AddPersonForm中指定要使用RadioSelect [Django-doc],尽管由于members可能是多对多关系, CheckboxSelectMultiple [Django-doc]更合适:

# app/forms.py

from app.models import Trip
from django import forms, RadioSelect

class AddPersonForm(forms.ModelForm):

    class Meta:
        model = Trip
        fields = ['members']
        widgets = {
            'members': RadioSelect()
        }

然后,您可以使用AddPersonForm

# app/views.py

from django.views.generic.edit import UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from app.models import Trip
from app.forms import AddPersonForm

class AddPersonView(LoginRequiredMixin, UserPassesTestMixin, UpdateView)
    model = Trip
    template_name = 'tripplanner/add_new_member.html'
    form_class = AddPersonForm
    success_url = '/'

    # ...

    def test_func(self):
        detailView = self.get_object()
        user = self.request.user
        return user in detailView.members.all() or user in detailView.owners.all()