- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对 django 和 python 都很陌生,在我的应用程序中我有两个模型,一个是 MyProfile
一个是 MyPost
,用户将有一个配置文件和用户可以创建帖子,一切正常,但我想在用户的个人资料中显示用户创建的帖子。为此,我尝试在我的通用 Detailview
中创建一个 get_context_data
。但它给了我这个错误 Cannot query "ahmy": Must be "MyProfile"instance
。 ahmy 是我的登录用户名。
我的模型
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
from django.core.validators import MinValueValidator, RegexValidator
# Create your models here.
class MyProfile(models.Model):
name = models.CharField(max_length = 500)
user = models.OneToOneField(to=User, on_delete=CASCADE)
address = models.TextField(null=True, blank=True)
gender = models.CharField(max_length=20, default="Male", choices=(("Male", 'Male'), ("Female", "Female"), ("LGBTQ", "LGBTQ")))
phone_no = models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")], max_length=15, null=True, blank=True)
description = models.CharField(max_length = 240, null=True, blank=True)
pic = models.ImageField(upload_to = "image\\", null=True)
def __str__(self):
return "%s" % self.user
class MyPost(models.Model):
main_pic = models.ImageField(upload_to = "image\\", null=True)
amount_spend = models.IntegerField(null=True, blank=True)
total_donars = models.IntegerField(null=True, blank=True)
title = models.CharField(max_length = 200)
body = models.TextField(null=False, blank=False)
cr_date = models.DateTimeField(auto_now_add=True)
uploaded_by = models.ForeignKey(to=MyProfile, on_delete=CASCADE, null=True, blank=True)
def __str__(self):
return "%s" % self.title
我的观点@method_decorator(login_required, name="dispatch")
class MyProfileDetailView(DetailView):
model = MyProfile
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the user posts
user_posts = MyPost.objects.filter(uploaded_by=self.request.user).order_by('-cr_date')
context['user_posts'] = user_posts
context['user'] = self.request.user
return context
我的 Html 文件
{% extends 'base.html' %}
{% block content %}
<div class="p-5">
<img src="/media/{{myprofile.pic}}" />
<h1 class="myhead2">{{myprofile.name}}</h1>
<p><strong>Address: {{myprofile.address}}</strong></p>
<p><strong>Phone Number: {{myprofile.phone_no}}</strong></p>
<p><strong>Email: {{myprofile.user.email}}</strong></p>
<p><strong>About:</strong> {{myprofile.purpose}}</p>
<p><strong> Total Donation Recived: {{myprofile.donation_recived}}</strong></p>
<hr>
<table class="table my-3">
<thead class="thead-dark">
<tr>
<th>Title</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
{% for MyPost in user_posts %}
<tr>
<td>{{MyPost.title}}</td>
<td>{{MyPost.cr_date | date:"d/m/y"}}</td>
<td>
<a class="btn btn-dark btn-sm" href='/covid/mypost/{{n1.id}}'>Read More</a>
<a class="btn btn-dark btn-sm" href='/covid/mypost/delete/{{n1.id}}'>Delete</a>
</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
网址
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from covid import views
from django.views.generic.base import RedirectView
urlpatterns = [
# Normal pages
path('home/', views.HomeView.as_view()),
path('tips/', views.TipsViews.as_view()),
path('info/', views.InfoView.as_view()),
path('dashboard', views.DashboardView.as_view()),
# Choose State URL
path('chose_state', views.chose_state, name='chose_state'),
# Orginisations Profiles
path('profile/edit/<int:pk>', views.MyProfileUpdateView.as_view(success_url="/covid/home")),
path('myprofile/', views.MyProfileListView.as_view()),
path('myprofile/<int:pk>', views.MyProfileDetailView.as_view()),
# Post URL
path('mypost/create/', views.MyPostCreate.as_view(success_url="/covid/mypost")),
path('mypost/delete/<int:pk>', views.MyPostDeleteView.as_view(success_url="/covid/mypost")),
path('mypost/', views.MyPostListView.as_view()),
path('mypost/<int:pk>', views.MyPostDetailView.as_view()),
path('profile/edit/<int:pk>', views.MyProfileUpdateView.as_view(success_url="/covid/home")),
# Root URL
path('', RedirectView.as_view(url="home/")),
]
最佳答案
uploaded_by
字段指的是 MyProfile
模型,而不是 User
模型。您可以将查询更改为:
user_posts = MyPost.objects.filter(
<b>uploaded_by__user=self.request.user</b>
).order_by('-cr_date')
因此,通过使用双下划线 (__
),我们“看穿”了一个关系,因此我们寻找 MyPost
对象,其中 uploaded_by
是一个 MyProfile
,作为 user
是对 request.user
对象的引用。
如果要显示路径中带有pk
的用户的内容:
path('myprofile/<int:pk>', views.MyProfileDetailView.as_view()),
您可以将其替换为:
user_posts = MyPost.objects.filter(
<b>uploaded_by_id=self.kwargs['pk']</b>
).order_by('-cr_date')
给定 pk
是 profile id;或者:
user_posts = MyPost.objects.filter(
<b>uploaded_by__user_id=self.kwargs['pk']</b>
).order_by('-cr_date')
如果 pk
指的是 user id。
或者你可以使用self.object
:
user_posts = self.object<b>.mypost_set.order_by('-cr_date')</b>
关于django - 无法查询 "": Must be "" instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61428148/
我知道我的问题有点含糊,但我不知道如何描述它。我问过很多地方,但似乎没有人理解我为什么要这样做。但请耐心等待,我会解释为什么我想要这样的东西。 我使用 Liquid Templates 允许用户在我的
这个问题在这里已经有了答案: what is the difference between null != object and object!=null [duplicate] (2 个回答) 7年
当我在我的本地主机 Google App Engine 应用程序中将日志记录级别更改为 FINE 时,我开始在我的跟踪堆栈中看到这些: Apr 17, 2013 4:54:20 PM com.goog
Python 有内置函数 type : class type(object) With one argument, return the type of an object. The return v
我正在使用深度学习进行语义分割,我遇到了以下术语:语义分割、实例检测、对象检测 和对象分割. 它们有什么区别? 最佳答案 这些术语的某些用法对用户而言是主观的或依赖于上下文,但据我所知对这些术语的合理
我面临 -[NSConcreteMutableData release] 的问题:消息发送到已释放的实例,我也附上了我的示例代码。 - (IBAction)uploadImage { NSString
我试图显示模型中的单个实例(数据库行),其中多个实例共享多行的相同字段(列)值。为了澄清这一说法,我有以下情况: ID/Title/Slug/Modified 1 Car A 1s ag
我正在尝试使用mockito来模拟服务。然而,我没有找到一种方法来告诉mockito,给定一个类的实例返回给我相同的实例: 类似于: given(service.add(any(Individua
我知道如何从父类(super class)原型(prototype)创建子类原型(prototype)。但是,如果我已经有了父类(super class)对象的实例来创建子类对象怎么办? 在 JS 中
鉴于 Kotlin 1.1。对于某个类的 instance,instance::class.java 和 instance.javaClass 似乎几乎是等价的: val i = 0 println(
这个问题在这里已经有了答案: 8年前关闭。 Possible Duplicate: Find out the instance id from within an ec2 machine 我正在寻找从
为什么我的 Instantiate 函数没有创建 That 的“空白”实例? 我有以下最小类: classdef That < handle properties This = '' end
Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTra
考虑以下几点: public class A { public String name = "i am a A instance"; } public class B extends A {
我正在使用 Scalr 来扩展网站服务器。 在 Apache 服务器上,我安装了 Sakai,并为 Linux 机器创建了一个启动脚本。 问题是,如何确保MySQL实例在Apache服务器启动之前启动
Android Realm DB 允许使用 Realm.getInstance() 获取多个实例。这些中的最佳实践是什么? :1.创建单个实例(应用程序范围)并在任何地方使用它2. 在需要时获取一个新
我很难理解为什么修改实例 a 中的属性会修改实例 b 中的相同属性。 var A = function (){ }; A.prototype.data = { value : 0 }; var
我将 Weka 用作更长管道的一部分,因此,我无法承受将所有数据写入文件或数据库只是为了创建一个 Instances。目的。我可以即时做的是创建 Instance 的列表对象。 来自 this pag
class C: def func(self, a): print(a) c = C() print(c.__dict__) # {} c.func = c.func # c.func i
Angular Routing 文档提到了组件实例创建、组件实例激活和路由激活。 文档没有解释这些概念的区别,以及每次创建/激活发生的时间。 问题 实例创建和实例激活有什么区别? 实例激活和路由激活有
我是一名优秀的程序员,十分优秀!