你好,这是我在这里的第一篇文章。我是新来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'
交互式爱情
繁星点点滴滴
相关分类