页面应该显示一个反馈表单链接和在管理面板中创建。创建模型:
from django.db import models
class ContactModel(models.Model):
# feedback form
name = models.CharField(max_length=50)
email = models.EmailField()
website = models.URLField()
message = models.TextField(max_length=5000)
create_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.name} - {self.email}'
class ContactLink(models.Model):
# links
icon = models.FileField(upload_to='icons/')
name = models.CharField(max_length=200)
def __str__(self):
return self.name
我将模型连接到管理面板:
from django.contrib import admin
from .models import ContactModel, ContactLink
@admin.register(ContactModel)
class ContactModelAdmin(admin.ModelAdmin):
list_display = ['id', 'name', 'email', 'create_at']
list_display_links = ('name',)
admin.site.register(ContactLink)
一切正常,你可以在管理面板创建链接。
views.py
以下:
from django.shortcuts import render
from django.views import View
from .models import ContactLink
class ContactView(View):
def get(self, request):
contacts = ContactLink.objects.all()
form = ContactForm()
return render(request, 'contact/contact.html', {'contact': contacts, 'form': form})
urls.py
:
from django.urls import path
from . import views
urlpatterns = [
path('contact/', views.ContactView.as_view(), name='contact'),
path('feedback/', views.CreateContact.as_view(), name='feedback'),
]
我通过for
循环通过代码返回链接从管理面板:
#links
<div class="contact__widget">
<ul>
{% for contact in contacts %}
<li>
<img src="{{ contact.icon.url }}">
<span>{{ contact.name }}</span>
</li>
{% endfor %}
</ul>
</div>
#feedback form
<form action="{% url 'feedback' %}" method="post">
{{ form }}
<button type="submit" class="site-btn">Submit</button>
</form>
反馈表格工作正常,但是链接都没有显示在页面上…错误可能在哪里?截图
视图必须引用正确的变量名。在
中使用contact
和s
return render(request, 'contact/contact.html', {'contacts': contacts, 'form': form})