我正在尝试解决一个小项目,django的新项目。
以下是我的网址:
url(r'^createreceivable/$',views.createreceivables,name = 'createreceivable'),
我的views.py
@login_required
def createreceivables(request):
if request.method == 'POST':
rec_form = Receivablesforms(data=request.POST)
if rec_form.is_valid():
rec_form.save()
return render(request,'account/dashboard.html')
else:
rec_form = Receivablesforms()
return render(request,'account/addreceivable.html',{'rec_form':rec_form})
我的model.py
class Receivables(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
receivable_name = models.CharField(max_length=250)
receivable_address = models.CharField(max_length=250,blank=True)
receivable_email = models.CharField(max_length=250,blank=True)
receivable_telephone = models.CharField(max_length=250,blank=True)
receivable_VAT = models.CharField(max_length=250,blank=True)
receivable_Service_Tax = models.CharField(max_length=250,blank=True)
receivable_PAN = models.CharField(max_length=250,blank=True)
forms.py
class Receivablesforms(forms.ModelForm):
class Meta:
model = Receivables
exclude = ('user',)
一切都很完美,除了数据没有保存在数据库中。请指导。
instance=request.user is not working
模板
<form action="." method="post">
{{ rec_form }}
{% csrf_token %}
<p><input type="submit" value="Save Changes"</p>
</form>
答案 0 :(得分:2)
由于您排除了用户,因此您需要以某种方式将其取回,否则您的rec_form.save()
会出现异常,因为您的模型需要填写user
字段。
诀窍是使用save(commit=False)
。它会在内存中创建一个对象,但它不会保存它。您只需将user
分配给内存中对象并再次保存:
if rec_form.is_valid():
new_rec = rec_form.save(commit=False)
new_rec.user = request.user
new_rec.save()
检查django doc commit=False
in save()
method。