Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将django多对多字段设置为接受null_Python_Django - Fatal编程技术网

Python 如何将django多对多字段设置为接受null

Python 如何将django多对多字段设置为接受null,python,django,Python,Django,我正在开发python/django应用程序。在我的应用程序中,有两个具有多对多关系的表Store和Ad Class Store: ads = models.ManyToManyField(Ad, null=True, blank=True) Class Store: ads = models.ManyToManyField(Ad) 我已经用上面给出的两种实现对其进行了测试,但当我保存我的商店而不选择广告时,会出现错误: ads:此字段为必填字段 我如何在这里设置可选广告 视

我正在开发python/django应用程序。在我的应用程序中,有两个具有多对多关系的表Store和Ad

Class Store:
    ads = models.ManyToManyField(Ad, null=True, blank=True)

Class Store:
    ads = models.ManyToManyField(Ad)
我已经用上面给出的两种实现对其进行了测试,但当我保存我的商店而不选择广告时,会出现错误:

ads:此字段为必填字段

我如何在这里设置可选广告

视图:

表格:


在表单的定义
ads
字段中添加
required=False
。重写模型表单中的字段时,不会从模型继承任何属性。您必须向其添加所有约束,如
max_length
required
等。

显示您的表单,查看代码。@Rohan我也添加了视图和源代码…您可能希望在表单中的定义
ads
字段中添加
required=False
。非常感谢Rohan!这就是问题所在,现在正在发挥作用。请将您的评论张贴在答案部分,以便我将其标记为答案。。。
class StoreView(FormView):
form_class = StoreForm
success_url = "/"
template_name = 'store.html'

def __init__(self):
    super(StoreView, self).__init__()
    self.store = None

def get_form_kwargs(self):
    kwargs = super(StoreView, self).get_form_kwargs()
    kwargs['current_user'] = self.request.user
    if 'store_id' in self.kwargs:
        self.store = Store.objects.get(id=self.kwargs['store_id'])
        kwargs['instance'] = self.store
    kwargs['request'] = self.request
    return kwargs

def get_context_data(self, **kwargs):
    context = super(StoreView, self).get_context_data(**kwargs)
    context['store_info'] = self.store
    return context

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
    return super(StoreView, self).dispatch(*args, **kwargs)

def form_invalid(self, form):
    return super(StoreView, self).form_invalid(form)

def form_valid(self, form):
    self.object = form.save()
    return super(StoreView, self).form_valid(form)
class StoreForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
    self.fields['ads'] = forms.ModelMultipleChoiceField(
        queryset=Ad.objects.filter(type=13),
        widget=forms.CheckboxSelectMultiple,
        label='Ads associated with this store'
    )

def save(self, commit=False):
    store = super(StoreForm, self).save(commit=True)
    return store

class Meta:
    model = Store