简体   繁体   English

Django - 如何通过用户先前选择的选项在表单中填充 manytomany 字段

[英]Django - How to populate manytomany field in forms by previously selected options by users

How can I populate manytomany form field with previous user selected subs.如何使用以前用户选择的子项填充 manytomany 表单字段。

In this code forms render choices with empty checkboxes.在此代码表单中,呈现带有空复选框的选项。 I want checkboxes to show which subscriptions user subscribed to.我希望复选框显示用户订阅了哪些订阅。

models.py模型.py

class Subscription(models.Model):
    SUBSCRIPTION_TYPES = (
        ('SUB1', _('sub 1')),
        ('SUB2', _('sub 2')),
    )

    subscription_type = models.CharField(choices=SUBSCRIPTION_TYPES, max_length=30, unique=True)
    description = models.CharField(max_length=255, blank=True)

class UserSubscription(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    subscriptions = models.ManyToManyField(Subscription, related_name='subscriptions',
                                           related_query_name='subscriptions')

forms.py表格.py

class SubscriptionForm(forms.ModelForm):
    class Meta:
        model = UserSubscription
        fields = ('subscriptions',)
        widgets = {
            'subscriptions': forms.CheckboxSelectMultiple(),
        }

views.py视图.py

class SubscriptionFormView(FormView):
    template_name = 'profile/subscription.html'
    form_class = SubscriptionForm

Please do not create a UserSubscription , now you defined two junction tables.不要创建UserSubscription ,现在你定义了两个结表。 This will result in duplicate data, and will make queries less efficient, and more error-prone logic.这将导致重复数据,并使查询效率降低,并且更容易出错的逻辑。

What you need is a ManyToManyField from the Subscription to the User , so:您需要的是从SubscriptionUserManyToManyField ,因此:

class Subscription(models.Model):
    # …
    subscribers = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='subscriptions'
    )

Then we can define a form to select the Subscription s:然后我们可以定义一个表单来选择Subscription

from django import forms

class SubscribingForm(forms.Form):
    subscriptions = forms.ModelMultipleChoiceField(
        queryset=Subscription.objects.all(),
        widget=forms.CheckboxSelectMultiple()
    )

Then in the view we can handle the form and subscribe the logged in user to all the subscriptions that have been selected:然后在视图中我们可以处理表单并为登录用户订阅所有已选择的订阅:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect

class SubscriptionFormView(LoginRequiredMixin, FormView):
    template_name = 'profile/subscription.html'
    form_class = SubscribingForm
    
    def get_initial(self):
        initial = super().get_initial()
        initial['subscriptions'] = self.request.user.subscriptions.all()
        return initial
    
    def form_valid(self, form):
        subs = form.cleaned_data['subscriptions']
        self.request.suer.subscriptions.add(*subs)
        return redirect('name-of-some-view')

Note : You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc] .注意:您可以使用LoginRequiredMixin mixin [Django-doc]将基于类的视图的视图限制为经过身份验证的用户。


Note : In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki] .注意:如果 POST 请求成功,您应该进行redirect [Django-doc]以实现Post/Redirect/Get模式 [wiki] This avoids that you make the same POST request when the user refreshes the browser.这可以避免您在用户刷新浏览器时发出相同的 POST 请求。

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

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