我认为这可行,但是在使它想更好理解之前,我遇到了一些问题,因此是一个问题。看起来其他人也可以通过多种方式查看堆栈溢出时的其他答案。我要避免的是,在创建新的搜索配置文件时,用户必须从下拉菜单中选择用户名。搜索配置文件模型为:
class Search_Profile(models.Model):
author_of_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True)
keyword_string = models.CharField(max_length=200)
other_stuff = models.CharField(max_length=200)
我最终得到的表格是:
class Search_Profile_Form(ModelForm):
class Meta:
model = Search_Profile
fields = [ 'keyword_string', 'other_stuff']
我故意遗漏了“ author_of_profile”,因此不会显示或需要对其进行验证。我尝试隐藏它,但是由于未输入字段,因此表单无法保存到模型中。如果我还好通过下拉菜单,我想我可能会把它留在里面。
在测试完整性时,我对HTML没有任何问题:
<form action="" method="POST">
{% csrf_token %}
{{ form.author_of_profile}}
{{ form.keyword_string }}
{{ form.other_stuff }}
<input type="submit" value="Save and Return to Home Page">
</form>
我最终在View处对待表单,然后分离模型,先保存表单,然后更新模型,这是我认为人们可能会采用的其他方法。
def New_Profile(request):
if request.method=='POST':
form = Search_Profile_Form(request.POST)
if form.is_valid():
post=form.save(commit=False)
# here is where I thought I could update the author of profile field somehow with USER
# but If I include the author_of_profile field in the form it seems I can't.
post.save()
#So instead I tried to update the author_of profile directly in the model
current_profile=Search_Profile.objects.last()
current_profile.author_of_profile=request.user
current_profile.save()
return(redirect('home'))
else:
form=Search_Profile_Form()
return render(request, 'mainapp/New_Profile.html', {'form': form})
有几个问题: 对于author_of_profile字段中的外键,最好使用blank = True或null = True 我最终使用了request.user而不是从django.contrib.auth.models import导入。User有什么区别? 我真正的问题是,上述方法是否是获取表单数据并使用该数据和用户更新数据库的合理方法?还是我错过了更多内置的其他方式?
try something like this. save the form to db then change the author again.
save(commit=False)
will not save the date to db immediately.