我创建了一个模型以及相应的ModelForm,视图和模板,但是即使使用.save()函数,ModelForm也不会将数据保存到模型中。 我曾尝试查看表单和视图,但不知道出了什么问题。我在问题中张贴了相应的模型,表单,视图和模板。
models.py:
class Centre(models.Model):
Location = (
('rashmi_heights', 'Rashmi Heights Centre'),
('Levana', 'Levana Centre')
)
name= models.CharField(max_length=50, blank=False, choices=Location, unique=True)
address = models.CharField(max_length =250)
contact = models.CharField(max_length=100, blank=False)
phone = PhoneField(blank=True, help_text='Contact phone number')
def __str__(self):
return self.name
forms.py:
class CentreForm(forms.ModelForm):
class Meta():
model = Centre
fields = '__all__'
views.py:
def centre(request):
forms = CentreForm()
if request.method == 'POST':
forms = CentreForm(request.POST)
if forms.is_valid():
centre = forms.save(request.POST)
centre.save()
else:
forms = CentreForm()
return render(request,'NewApp/centreinfo.html',{'forms':forms})
模板:
<!DOCTYPE html>
{% extends 'NewApp/base.html' %}
{% load staticfiles %}
{% block body_block %}
<div class="jumbotron">
<h2>Fill details about your centre.</h2><br>
<h3> </h3>
<form method="post" enctype="multipart/form-data">
{{forms.as_p}}
{% csrf_token %}
<a class="btn btn-primary" href="{% url 'NewApp:centreinfo' %}">Submit</a>
</form>
</div>
{% endblock %}
答案 0 :(得分:1)
forms.py:
class CentreForm(forms.ModelForm):
class Meta: -> change here
model = Centre
fields = '__all__'
def centre(request):
forms = CentreForm()
if request.method == 'POST':
forms = CentreForm(request.POST)
if forms.is_valid():
forms.save(request.POST)
else:
forms = CentreForm()
return render(request,'NewApp/centreinfo.html',{'forms':forms})
html
<form method="post" enctype="multipart/form-data">
{{forms.as_p}}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>