0
長時間的聽衆,第一次張貼海報。希望得到我的模型問題的一些幫助。Django - 多對多模型返回無
我遇到了我的多對多關係問題。當我提交表單時,我想讓我的用戶信息與他們創建的帖子相關聯。我使用的是多對多,因爲我會在其他用戶可以在同一行中加入其他功能。
目前,我的Trip表的數據創建正常,但我的用戶沒有鏈接到旅行ID,所以我無法在模板上渲染出他們的名字。
以下是我的代碼。感謝任何幫助! 乾杯
這裏是我的models.py:
class User(models.Model):
name = models.CharField(max_length=45)
username = models.CharField(max_length=255)
password = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
class Trip(models.Model):
destination = models.CharField(max_length=45)
description = models.CharField(max_length=255)
datefrom = models.CharField(max_length=255)
dateend = models.CharField(max_length=255)
user = models.ManyToManyField(User)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
這裏是我的views.py:
def travels(request):
user = User.objects.get(id=request.session['logged_user'])
all_trips = Trip.objects.all().order_by('-id')
user_trips = Trip.objects.filter(user=request.session['logged_user'])
context = {
"user_trips": user_trips,
"all_trips": all_trips,
"user": user,
}
return render(request, 'belt_exam/travels.html', context)
def addtrip(request):
user_id = request.session['logged_user']
createdtrip = Trip.objects.create(destination=request.POST['destination'], description=request.POST['description'], datefrom=request.POST['datefrom'], dateend=request.POST['dateend'])
createdtrip.user.add(User.objects.get(id=user_id))
return redirect('/travels')
這裏是我的模板:
{% for alltrip in all_trips.all %}
<tr>
<td>{{alltrip.name}}</td>
<td><a href="travels/destination/{{alltrip.id}}">{{alltrip.destination}}</a></td>
<td>{{alltrip.datefrom}}</td>
<td>{{alltrip.dateend}}</td>
<td>
<form class="" action="travels/destination/{{alltrip.id}}" method="POST">
{% csrf_token %}
<input type="submit" value="Join">
</form>
</td>
</tr>
{% endfor %}
感謝克勞斯!儘管如此,我仍然有點困惑。我的「models.ManyToManyField(用戶)」位於Trip表格中。我試圖將兩張表連接在一起,以便我可以將海報的用戶ID添加到Trip ID中。你能幫忙解釋一下嗎?對不起,我是編程新手,感謝您的耐心等待! – justinchanman
也許這會幫助你理解https://docs.djangoproject.com/en/1.10/topics/db/queries/#following-relationships-backward –