我正在尝试将django管理员中名为Listing
的模型中的用户信息显示到名为myaccount.html
的HTML模板中,但没有成功。
我当前的代码在做什么错了?
我们非常感谢您的帮助。干杯。
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
{% extends 'base.html' %}
{% load static %}
<p>{{ Listing.name }}</p>
<p>{{ Listing.address }}</p>
{% block content %}
{% endblock content %}
答案 0 :(得分:1)
您的Listing
对象列表在您的上下文中称为user_profile
。所以:
{% for profile in user_profile %}
{{ profile.name }}
{{ profile.address }}
{% endfor %}
将向您显示所有Listings
。
请注意一个错误:应该是user_profile = Listing.objects.all()
,并带有括号。而且我建议您使用复数user_profiles
,因为您要获取多个。使您的代码更容易理解。
答案 1 :(得分:0)
将您的html更改为
<p>{{ form.name }}</p>
<p>{{ form.address }}</p>