我刚开始使用Django,但遇到一个问题,当我在模型中添加字段(继承自models.Model的JobPost)并将其成功迁移时,我可以看到新的并与之交互字段,当我创建职位发布时,而不是当我查看职位发布时(该字段通过使用{{form | crispy}}标签的易碎表单显示。
我已在我的views.py
中将字段名称添加到我的字段= ['']中models.py
class JobPost(models.Model):
#constants
CLEARANCE_LEVELS=[(...),]
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
clearance_required = models.CharField(max_length=50, choices=CLEARANCE_LEVELS, default='None')
date_posted = models.DateTimeField(default=timezone.now)
views.py
class JobDetailView(DetailView):
model = JobPost
class JobCreateView(LoginRequiredMixin, CreateView):
model = JobPost
fields = ['title', 'content', 'clearance_required']
# form_valid checks if the user is logged in
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
jobpost_form.html
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %} <!--Used to prevent some XSS Attacks (Cross-site request forgery) -->
<fieldset class="form-group">
<legend class="border-bottom mb-4">Create Job Post</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Submit</button>
</div>
</form>
</div>
{% endblock content %}
jobpost_detail.html
{% block content %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="mb-2 article-metadata">
<a class="mr-1" href="{% url 'profile' %}">{{ object.author }}</a> <!-- BROKEN LINK: SIMPLY TAKES TO CURRENTLY LOGGED IN USER-->
<small class="text-muted">{{ object.date_posted|date:"F d, Y" }}</small>
{% if object.author != user %}
<a class="btn btn-secondary btn-sm float-right" href="{% url 'user-jobs' object.author.username %}">See all jobs the user applied to</a>
{% endif %}
<div>
{% if object.author == user %}
<a class="btn btn-secondary btn-sm mt-1 mb-1 float-right" href="{% url 'user-jobs' object.author.username %}">See all jobs the user applied to</a>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'job-update' object.id %}">Update Job Posting</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'job-delete' object.id %}">Delete</a>
{% endif %}
</div>
</div>
<div class="mt-1">
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content }}</p>
</div>
</div>
</article>
{% endblock content %}
因此,当我在浏览器中查看它时,在创建职位发布时会看到“ clearance_required”字段。但是,当我仅查看职位发布时,它仅显示标题和说明,而不显示新的clearance_required字段。我不知道如何显示它。
答案 0 :(得分:1)
由于我看不到,您实际上在object.clearance_required
的{{1}}中输出了吗?
顺便说一句,如果输出,则应使用jobpost_detail.html
,because it is a field with choices。