我有一个显示表单并保存相同表单的视图。显示视图没有问题但保存时出现以下错误:
int()参数必须是字符串,类字节对象或数字,而不是' QueryDict'
这是我的代码:
MODEL:
class Category(models.Model):
name = models.CharField(max_length=100, db_index=True, unique=True)
slug = models.SlugField(max_length=100, db_index=True, unique=True)
user = models.ForeignKey(User, related_name='categories')
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('wallet:category_details', args=[self.id])
查看:
@login_required
def category_create(request):
user = request.user
if request.method == 'POST':
category_create_form = CategoryCreateForm(request.POST)
if category_create_form.is_valid():
new_category = category_create_form.save(commit=False)
new_category.user = request.user
new_category.save()
return render(request, 'category/done.html')
else:
category_create_form = CategoryCreateForm()
return render(request, 'category/create.html', {'category_form': category_create_form})
形式:
class TransactionCreateForm(forms.ModelForm):
field_order = ['name', 'type', 'wallet', 'category', 'date', 'amount', 'notes', ]
class Meta:
model = Transaction
fields = ('name', 'type', 'wallet', 'category', 'date', 'amount', 'notes',)
def __init__(self, user, *args, **kwargs):
super(TransactionCreateForm, self).__init__(*args, **kwargs)
self.fields['wallet'] = forms.ChoiceField(
choices=[(wallet, str(wallet)) for wallet in Wallet.objects.filter(user=user)])
我该如何解决?
答案 0 :(得分:2)
您的表单的__init__
方法指定了user
参数,您在实例化时不会提供该参数。使用以下命令创建表单:
category_create_form = CategoryCreateForm(user)
或在POST
分支中
category_create_form = CategoryCreateForm(user, request.POST)
好吧,假设实际的类看起来像你发布的不同命名的表单类。基本上,请查看表单所需的参数。