尝试将表单添加到 DetailView
Posted
技术标签:
【中文标题】尝试将表单添加到 DetailView【英文标题】:Trying to add a form to a DetailView 【发布时间】:2021-04-12 21:57:18 【问题描述】:我正在编写一个详细视图 - 显示的表单是用户添加/更新到 CD 条目的特定轨道(它是一个 CD 库应用程序)。诀窍是我想在页面上查看有关 CD 的所有其他内容以及特定曲目的表格。无法弄清楚如何让表单成为我正在添加/更新的跟踪。
基本上,您可以在 CD 模型中输入 CD 标题、艺术家和 CD 总时间。然后将轨道存储在轨道模型中,它们的外键是它们所在的 CD。
在查看 CD 的详细视图时,用户可以通过按钮添加或更新特定曲目。我正在尝试使更新部分正常工作。 模型如下所示:
from django.db import models
from datetime import datetime, timedelta
class Cd(models.Model):
artist_name = models.CharField(max_length=155)
cd_title = models.CharField(max_length=155)
cd_total_time = models.TimeField(default="00:00:00")
cd_total_time_delta = models.DurationField(default=timedelta)
cd_run_time = models.TimeField(default="00:00:00",blank=True)
cd_run_time_delta = models.DurationField(default=timedelta)
cd_remaining_time = models.TimeField(default="00:00:00",blank=True)
cd_remaining_time_delta = models.DurationField(default=timedelta)
def save(self, *args, **kwargs):
super().save(*args,**kwargs)
def __str__(self):
return f"self.artist_name : self.cd_title"
class Track(models.Model):
cd_id = models.ForeignKey(Cd, on_delete=models.CASCADE,
related_name='cd_tracks',
)
track_title = models.CharField(max_length=50)
track_number = models.IntegerField()
trk_length_time = models.TimeField(null=True,default=None, blank=True)
trk_length_time_delta = models.DurationField(default=timedelta)
trk_run_time = models.TimeField(default="00:00:00",blank=True)
trk_run_time_delta = models.DurationField(default=timedelta)
trk_remaining_time = models.TimeField(default="00:00:00",blank=True)
trk_remaining_time_delta = models.DurationField(default=timedelta)
def save(self, *args, **kwargs):
super().save(*args,**kwargs)
self.cd_id.save()
def __str__(self):
return f"self.track_title"
views.py sn-p:
class Track_update(UpdateView):
model = Track
template_name = 'track_update.html'
fields = [ 'cd_id', 'track_title',
'track_number', 'trk_length_time'
]
success_url = "/"
class Cd_DetailView(DetailView):
model = Cd
template_name = 'cd_detail.html'
fields = ['artist_name','cd_title','cd_total_time',
'cd_run_time','cd_remaining_time'
]
class Cd_MixedView(FormMixin, DetailView):
model = Cd
template_name = 'cd_mixed_view.html'
form_class = TrackForm
def get_success_url(self):
return reverse('cd_detail id')
def get_context_data(self, **kwargs):
context = super(Cd_MixedView,self).get_context_data(**kwargs)
context['form'] = TrackForm(initial=
'cd_id':self.object
)
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self,form):
form.save()
return super(Cd_MixedView, self).form_valid(form)
urls.py 看起来像
from django.urls import path
from django.contrib import admin
from .views import (
HomePageView,
Cd_Create,
Cd_Update,
Cd_DetailView,
List_Cds,
Track_Create,
Cd_MixedView,
)
urlpatterns = [
path('', HomePageView.as_view(), name = 'home'),
path('admin/', admin.site.urls),
path('cd/add/', Cd_Create.as_view(), name='cd_new'),
path('cd/update/<int:pk>', Cd_Update.as_view(), name='cd_update'),
path('cd/detail/<int:pk>', Cd_DetailView.as_view(), name='cd_detail'),
path('track/add/', Track_Create.as_view(), name='track_new'),
path('track/add/<int:pk>', Cd_MixedView.as_view(), name='cd_mixed_view'),
path('list/', List_Cds.as_view(), name='list_cds'),
]
模板如下所示:
<!-- templates/cd_mixed_view.html -->
% extends 'base.html' %
% load static %
% block title % CD Details% endblock title %
% block content %
<h1>CD Update Track </h1>
<p>Artist Name: cd.artist_name
<p>Cd Title: cd.cd_title
<p>Cd Total Time: cd.cd_total_time|time:"H:i:s"
<p>Cd Run Time: cd.cd_run_time|time:"H:i:s"
<p>Cd Remaining Time:
% if cd.cd_run_time_delta > cd.cd_total_time_delta %
(- cd.cd_remaining_time|time:"H:i:s" )
% else %
cd.cd_remaining_time|time:"H:i:s"
% endif %
<TABLE BORDER="0" TABLE_LAYOUT="fixed" WIDTH="100%">
<TR BGCOLOR="#B0B0FF">
<TD></TD>
<TD ALIGN="Center"> Track #</TD>
<TD ALIGN="Center"> Cut Title</TD>
<TD ALIGN="Center">Track Length</TD>
<TD ALIGN="Center" BGCOLOR="#CC99CC">Run Time</TD>
<TD ALIGN="Center" BGCOLOR="#CC99CC">Time Remaining</TD>
</TR>
% for tracks in cd.cd_tracks.all %
*** This is the part I am having trouble with ***
% if tracks.id = track number that was clicked %
form_as_p
% else %
<TR>
<TD ALIGN="Center" rowspan="1" >
<TD ALIGN="Left" VALIGN="Top" WIDTH="10"> tracks.track_number </TD>
<TD ALIGN="Left" VALIGN="Top"> tracks.track_title </TD>
<TD ALIGN="Left" VALIGN="Top"> tracks.trk_length_time|time:"H:i:s" </TD>
<TD ALIGN="Left" VALIGN="Top"> tracks.trk_run_time|time:"H:i:s" </TD>
% if tracks.trk_run_time_delta > cd.cd_total_time_delta %
<TD BGCOLOR="#8DF1BF" ALIGN="Left"> (- tracks.trk_remaining_time|time:"H:i:s" )</TD>
% else %
<TD BGCOLOR="#8DF1BF" ALIGN="Left"> tracks.trk_remaining_time|time:"H:i:s" </TD>
% endif %
</TR>
% endfor %
</TABLE>
</table>
% endblock content %
那么,我如何将 Track ID 传递到模板中,以便我可以显示 THAT Track 的表单,否则 显示所有其他曲目的曲目信息。
任何有关如何解决此问题的信息将不胜感激。 下面是尝试更新轨道之前详细信息屏幕的图片。
谢谢
【问题讨论】:
【参考方案1】:您是否考虑过将跟踪 ID 添加为 slug,在视图中创建另一个函数来传递它?带有'a'标签,并传递一个href,如果轨道引用CD,则在其中包含外键。您可以在视图的上下文中传递值。
【讨论】:
以前从未使用过 slug,所以不确定它是什么样子(Django 新手)。但我也不知道我是否需要一个,因为从技术上讲,此时我已经知道 CD 主键和轨道 ID。如果创建它,那么我没有 Track ID,但可以调用创建函数而不是更新功能......?以上是关于尝试将表单添加到 DetailView的主要内容,如果未能解决你的问题,请参考以下文章