你好,这是我在这里的第一篇文章。我是python
和django
的新手,我想进一步了解两者,因此我正在与他们合作以获取更多经验。
我正在尝试让metros
的所有user(x)
都说1
。我希望能够将user 1
作为id
,并获取与此metros
相关的所有user
。
模型
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Metro(models.Model):
class Meta():
verbose_name_plural = "MetroCards"
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Creator")
metro_name = models.CharField( max_length=30)
created = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.metro_name} by: {self.owner}"
观看次数
from django.shortcuts import render, redirect, Http404
from .models import User, Metro
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
def user(request, user_id):
try:
user = User.objects.get(pk=user_id)
metro = Metro.owner.get(pk=user_id)
except User.DoesNotExist:
raise Http404("User Does Not Exist")
context = {
"user": user,
"metro": metro
}
return render(request, "metrocard/user.html", context)
网址
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('register/', views.register, name='register'),
path("user/<str:user_id>", views.user, name="userid"),
path('map/', views.map, name='map'),
]
HTML
<h1>User Id: {{ user.id}} </h1>
<ul>
<li>Username: {{ user.username }} </li>
<li>Email: {{ user.email }} </li>
{% for met in metro %}
<li>Metro Name: {{ met.metro_name }}</li>
{% endfor %}
</ul>
我遇到的错误是:
'ForwardManyToOneDescriptor' object has no attribute 'get'
使用控制台回溯进行编辑:
Traceback (most recent call last):
File "/home/bryant/Desktop/metro/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/bryant/Desktop/metro/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/bryant/Desktop/metro/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/bryant/Desktop/metro/vMetro/metrocard/views.py", line 16, in user
metro = Metro.owner.get(pk=user_id)
AttributeError: 'ForwardManyToOneDescriptor' object has no attribute 'get'
答案 0 :(得分:0)
我认为您应该更改:
metro = Metro.owner.get(pk=user_id)
到
metro = user.metro_set.all()
答案 1 :(得分:0)
models.py
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(blank=True)
price = models.TextField()
views.py
def dynamic_lookup_view(request,my_id):
object = Product.objects.get(id=my_id)
context = {
'product':object
}
return render(request,'products/product_detail.html',context)
urls.py
path('products/<int:my_id>/',dynamic_lookup_view)
HTML
{{ product.title }}
{{ product.description }}