【问题标题】:CreateView Model Objects to a templateCreateView 模型对象到模板
【发布时间】:2020-05-03 21:48:25
【问题描述】:

所以我试图将对象列表传递到我的模板中。我希望我的 profile.html 反映模型中的信息。我在 ListView 上找到了一些文档,但在 CreateView 上没有找到。 唯一传递给模板的是 {{ user.username }}。任何建议将不胜感激。

profile.html

{% extends 'base.html' %}
{% block title %}User Profile{% endblock %}
{% block content %}
{% if user.is_authenticated %}
<p>User: {{ user.username }} logged in.</p>
<p><a href="{% url 'homepage' %}">homepage</a></p>
<p><a href="{% url 'logout' %}">logout</a></p>
{% else %}
<a href="{% url 'login' %}">login</a> |
<a href="{% url 'signup' %}">signup</a>
{% endif %}
{% endblock %}

models.py

class Volunteer(CustomUser):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True)
    about_me = models.TextField(default='')    

    class Meta:
         db_table = "volunteer"

forms.py

class VolunteerSignUpForm(UserCreationForm):

class Meta(UserCreationForm.Meta):
    model = Volunteer
    fields = ("username", "email", "first_name", "last_name",)
@transaction.atomic
def save(self):
    user = super(VolunteerSignUpForm, self).save(commit=False)
    user.is_volunteer = True
    user.save()
    return user

views.py

class VolunteerSignUp(CreateView):
form_class = VolunteerSignUpForm
success_url = reverse_lazy('login')
template_name = 'volunteer_signup.html'
#added code from answer
def get_context_data(self, **kwargs):
    context = super(VolunteerSignUp, self).get_context_data(**kwargs)
    context['profile_list'] = Volunteer.objects.all()
    return context

profile.html 以下是一些 iv 试图获取信息但没有成功的事情。

<ul>
    {% for volunteer in object_list %}
    <li>{{ volunteer.about_me }}</li>
    {% endfor %}
</ul>

<ul>
    {% for volunteer in profile_list %}
    <li>{{ volunteer.about_me }}</li>
    {% endfor %}
</ul>

{% if profile_list %}

{% else %}
  <p>There is no info.</p>
{% endif %}

【问题讨论】:

  • 您希望在模板中反映哪些信息?
  • 我希望将每个字段添加到单独的段落中。我尝试用 {% if profile_list %} 迭代它,但它不起作用,所以我尝试用 {% for志愿者 in object_list %}
  • {{ 志愿者.about_me }}
  • {% endfor %} 添加它这也没有用。

标签: django django-models django-templates django-views


【解决方案1】:

你可以在你的类中使用 get_context_data() 方法。

class VolunteerSignUp(CreateView):
    form_class = VolunteerSignUpForm
    success_url = reverse_lazy('login')
    template_name = 'volunteer_signup.html'

    def get_context_data(self, **kwargs):
        data = super(VolunteerSignUp, self).get_context_data(**kwargs)
        data['profile_list'] = 'your queryset goes here'
        return data

【讨论】:

  • 我的 HTML 模板应该是什么来传递信息?
      {% 为 profile_list 中的志愿者%} {{ 志愿者.about_me }} {% endfor %}
    没有像我想象的那样工作。
  • 用 context = super(VolunteerSignUp, self).get_context_data(**kwargs) 替换这个 context = super(VolunteerListView, self).get_context_data(**kwargs)
猜你喜欢
相关资源
最近更新 更多
热门标签