我有一个django表单,该表单从视图中获取了一个参数,以便根据用户实例初始化MultipleChoiceField。
加载模板时,表单工作正常。 当我提交表单时,表单中的 init 方法会引发错误。
我的模型 models.py
from django.db import models
from django.contrib.auth.models import User
class Group(models.Model):
group_name = models.CharField('Group name', max_length=50)
def __str__(self):
return self.group_name
class GroupMembers(models.Model):
group_name = models.ManyToManyField(Group)
members = models.ForeignKey(User, on_delete=models.CASCADE)
class Transactions(models.Model):
bill_type = models.CharField('Bill type',max_length=200)
added_by = models.ForeignKey(GroupMembers, on_delete=models.CASCADE)
added_to = models.ForeignKey(Group, on_delete=models.CASCADE)
purchase_date = models.DateField(auto_now=True)
share_with = models.CharField('Share among',max_length=250)
amount = models.IntegerField(default=0)
def __str__(self):
return self.bill_type
表格表格.py
from django import forms
from .models import Transactions, GroupMembers
class Bill_CreateForm(forms.ModelForm):
def __init__(self, user_list, *args, **kwargs):
super(Bill_CreateForm, self).__init__(*args, **kwargs)
self.fields['share_with'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([(name, name.members) for name in user_list]))
class Meta:
model = Transactions
fields = (
'bill_type',
'amount',
'added_by',
'added_to',
'share_with',
)
**通过@Alasdair帮助解决了我的问题”
编辑后的解决方案
观看次数 views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Transactions, Group, GroupMembers
from .forms import Bill_CreateForm
from django.http import HttpResponse, HttpResponseRedirect
def add_bills_home(request, id=None):
user = User.objects.get(pk=id)
grpname = Group.objects.filter(groupmembers__members=user)
gm = GroupMembers.objects.filter(group_name__group_name=grpname[0])
users_list = [i for i in gm]
if request.method == 'POST':
form = Bill_CreateForm(users_list, request.POST)
if form.is_valid():
print(form.cleaned_data['share_with'])
form.save()
form = Bill_CreateForm(users_list)
return render(request, 'bills/create_bill.html', {'form':form})
else:
form = Bill_CreateForm(users_list)
return render(request, 'bills/create_bill.html', {'form':form})
错误是
提交带有数据的表格后 request.POST方法返回 下方数据
我不知道request.POST方法是否用填充的数据重新初始化表单并将其传递给form.py中的init方法。
请帮助我