[英]I can not display Django form
I am trying to make a contact form but it's html template does not see {{ form }} template.我正在尝试制作联系表格,但它的 html 模板没有看到 {{ form }} 模板。 What am I doing wrong?
我究竟做错了什么? Where is an error.
哪里出错了。
My code is attached above.我的代码附在上面。
models.py模型.py
class Contact(models.Model):
listing = models.CharField(max_length=200)
listing_id = models.IntegerField()
name = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=100)
message = models.TextField(blank=True)
file = models.FileField(upload_to='files/%Y/%m/%d/', blank=True)
contact_date = models.DateTimeField(default=datetime.now, blank=True)
user_id = models.IntegerField(blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('listings', kwargs={'pk': self.pk})
In views.py file在views.py 文件中
class ContactCreate(CreateView):
model = Contact
form_class = ContactForm
template_name = 'listing.html'
urls.py网址.py
from django.urls import path
from . import views
urlpatterns = [
path('listings/<int:pk>/', views.ContactCreate.as_view(), name='contact-create')
]
html html
<form action="{% url 'contact-create' pk=listing.pk %}" method="post">
{{ form }}
{% csrf_token %}
<input type="submit" value="Send" class="btn btn-block btn-secondary">
</form>
forms.py forms.py
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['name','email','phone','file']
Could you help me out, please你能帮我吗,拜托
If you provide a form_class
with ContactForm
, Django is expecting a form to be provided so you have two options:如果您使用
ContactForm
提供form_class
,则 Django 期望提供一个表单,因此您有两种选择:
Create a form.py and add the following:创建一个 form.py 并添加以下内容:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
message = forms.CharField(widget=forms.Textarea)
Don't forget to add that to your view:不要忘记将其添加到您的视图中:
from myapp.forms import ContactForm
If you want your custom form to be display you have to specify the form_class
in your create view:如果要显示自定义表单,则必须在创建视图中指定
form_class
:
form_class = ContactForm
If you are using a custom template to display your form add the following to your create view:如果您使用自定义模板来显示您的表单,请将以下内容添加到您的创建视图中:
template_name = 'listing.html' # or the path to your template
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.