Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.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 导致关键字参数无效的多个字段_Python_Django_Django Models_Django Forms_Django Views - Fatal编程技术网

Python 导致关键字参数无效的多个字段

Python 导致关键字参数无效的多个字段,python,django,django-models,django-forms,django-views,Python,Django,Django Models,Django Forms,Django Views,不知是否有人能帮助我。我正在尝试编写一个表单和视图,将新的用户配置文件添加到我的数据库中。用户模型有一个多个字段,指向一个名为“兴趣”的表,这允许用户选择他们的兴趣 型号 class Interest(models.Model): title = models.TextField() class User(models.Model): first_name = models.CharField(max_length=30) last_name = models.Ch

不知是否有人能帮助我。我正在尝试编写一个表单和视图,将新的用户配置文件添加到我的数据库中。用户模型有一个多个字段,指向一个名为“兴趣”的表,这允许用户选择他们的兴趣

型号

class Interest(models.Model):
    title = models.TextField()



class User(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    date_of_birth = models.DateField()
    email = models.EmailField()
    password = models.CharField(max_length=32)
    course = models.ForeignKey(Course)
    location = models.ForeignKey(Location)
    interests = models.ManyToManyField(Interest)
    bio = models.TextField(blank=True)
查看

def add_user(request):
if request.method == 'POST':
    form = AddUserForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        submission = User(
            first_name=cd['first_name'],
            last_name=cd['last_name'],
            date_of_birth=cd['date_of_birth'],
            email=cd['email'],
            password=cd['password'],
            course=cd['course'],
            location=cd['location'],
            interests=cd['interests'], #Line that is causing errors
            bio=cd['bio']
        )
        submission.save()
        return HttpResponseRedirect('/add-user/')
else:
    form = AddUserForm()
return render(request, 'adduser.html', {'form': form})
表格

class AddUserForm(forms.ModelForm):
class Meta:
    model = User
    fields = [
        'first_name',
        'last_name',
        'date_of_birth',
        'email',
        'password',
        'course',
        'location',
        'interests',
        'bio',
        ]
    widgets = {
        'password': forms.PasswordInput(),
    }
有没有人有办法让它正常工作并允许我创建新用户


非常感谢

正如错误所说,在实例化模型时,多对多字段作为关键字参数无效,因为它们实际上引用了一个单独的链接表,并且它们所关联的实例必须已经保存

但是,您不需要手动执行这些操作。使用ModelForm的要点之一是它有一个
save
方法,该方法负责设置所有字段,必要时包括m2m

if form.is_valid():
    submission = form.save()
    return HttpResponseRedirect('/add-user/')
然而,你必须再次永远不要使用你在这里所做的一切。您将密码存储为纯文本,这是一个严重的安全漏洞。也没有理由这么做:Django包含一个身份验证框架,它负责为您散列密码,并且易于扩展。用它来代替