[英]Django: How to render model data into HTML template?
I'm trying to display user info from my model named Listing
that's in the django admin into my HTML template named myaccount.html
and I have not had any success. 我正在尝试将django管理员中名为
Listing
的模型中的用户信息显示到名为myaccount.html
HTML模板中,但没有成功。
What am I doing wrong with my current code? 我当前的代码在做什么错?
Any help is gladly appreciated. 任何帮助都将不胜感激。 Cheers.
干杯。
from django.contrib import auth
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
class Listing (models.Model):
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True)
rank = models.CharField(max_length=100, null=True)
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
zip_code = models.CharField(max_length=100)
mobile_number = models.CharField(max_length=100)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Listing.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=CustomUser)
from django.http import HttpResponse, HttpResponseRedirect
from django.http import HttpResponseNotFound
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.conf import settings
from .forms import HomeForm
from .models import Listing
from users.models import CustomUser
def change_view(request):
form = HomeForm(request.POST or None, request.FILES or None,)
user_profile = Listing.objects.all
user = request.user
if request.method == "POST":
if form.is_valid():
listing_instance = form.save(commit=False)
listing_instance.user = user
listing_instance.save()
return redirect("myaccount")
context = {
'form': form, 'user_profile': user_profile
}
return render(request, "myaccount.html", context)
HTML HTML
{% extends 'base.html' %}
{% load static %}
<p>{{ Listing.name }}</p>
<p>{{ Listing.address }}</p>
{% block content %}
{% endblock content %}
Your list of Listing
objects is called user_profile
in your context. 您的
Listing
对象列表在您的上下文中称为user_profile
。 So: 所以:
{% for profile in user_profile %}
{{ profile.name }}
{{ profile.address }}
{% endfor %}
will show you all the Listings
. 将向您显示所有
Listings
。
Note one mistake: It should be user_profile = Listing.objects.all()
with brackets. 注意一个错误:它应该是
user_profile = Listing.objects.all()
并带有方括号。 And I would advise you to use plural user_profiles
since you're fetching multiple. 而且我建议您使用多个
user_profiles
因为您要获取多个。 Makes it easier to understand your code. 使您更容易理解您的代码。
Change your html to 将您的html更改为
<p>{{ form.name }}</p>
<p>{{ form.address }}</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.