我的保存按鈕不會將用戶輸入的數據以django形式保存到數據庫中,問題在哪裏?使用Django表單將數據保存到數據庫
models.py
class Cemetery(models.Model):
id = models.AutoField(primary_key=True)
name=models.CharField(verbose_name="Cemetery Name",max_length=100)
city=models.CharField(max_length=30)
zipcode=models.CharField(max_length=5)
date_created=models.DateTimeField(editable=False, auto_now_add=True)
date_modified= models.DateTimeField(editable=False, auto_now=True)
created_by=models.ForeignKey('auth.User')
def __str__(self):
return str(self.id) +'-' + self.name + ' - ' + self.city
forms.py
class CemeteryForm(forms.ModelForm):
class Meta:
model=Cemetery
fields=('name','city','zipcode',)
views.py
def cemetery_add(request):
if request.method=="POST":
form=CemeteryForm(request.POST)
if form.is_valid():
cemetery=form.save(commit=False)
cemetery.name=request.name
cemetery.city=request.city
cemetery.zipcode=request.zipcode
cemetery.created_by=request.user
cemetery.date_created=timezone.now()
cemetery.save()
return redirect('cemetery_list')
else:
form=CemeteryForm
return render(request,'heaven/edit_cemetery.html',{'form':form})
模板
{% extends 'heaven/base.html' %}
{% block content %}
<!-- Edit Cemetery -->
<h2>New Cemetery</h2>
<form method="POST" class="cemetery-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
當我按下保存按鈕,這是我收到的錯誤: AttributeError的AT/cemetery_add/ 'WSGIRequest' 對象有沒有屬性 '名'
非常感謝您的回答!我現在有點困惑,我嘗試了不同的場景,但都沒有工作。你的意思是忽略你提到的那4行或保留它們,並刪除其餘的?你會如何重寫views.py? – Ibo