Django:在通用视图中为排除的字段设置 kwargs 值
Django: Set kwargs value for excluded field in generic view
嗨,我从昨天开始就在尝试。
models.py
class Event(models.Model):
def get_absolute_url(self):
return reverse('events:event-detail', kwargs={'pk': self.pk})
class Kategorie(models.Model):
event = models.ForeignKey(Event)
sport = models.ForeignKey(Sport)
....
urls.py
url(r'^kategorie/(?P<pk>[0-9]+)/create/$', views.KategorieCreate.as_view(), name='kategorie-create'),
html
<a href="{% url 'events:kategorie-create' event.id %}">Neue Kategorie</a>
views.py
class KategorieCreate(generic.CreateView):
model = Kategorie
fields = ['sport',...] # 'event' is excluded
template_name_suffix = '_create_form'
def get_context_data(self, **kwargs):
context = super(KategorieCreate, self).get_context_data(**kwargs)
context['event'] = kwargs.get(self.pk)
return context
我收到了:
NOT NULL constraint failed: events_kategorie.event_id
在上下文中设置该值没有意义;您需要在表单实例中这样做。这是 well documented:
def form_valid(self, form):
form.instance.event_id = self.kwargs['pk']
return super(KategorieCreate, self).form_valid(form)
请注意,我实际上无法理解您要在此处插入的值。使用类别PK作为事件id是没有意义的。
嗨,我从昨天开始就在尝试。
models.py
class Event(models.Model):
def get_absolute_url(self):
return reverse('events:event-detail', kwargs={'pk': self.pk})
class Kategorie(models.Model):
event = models.ForeignKey(Event)
sport = models.ForeignKey(Sport)
....
urls.py
url(r'^kategorie/(?P<pk>[0-9]+)/create/$', views.KategorieCreate.as_view(), name='kategorie-create'),
html
<a href="{% url 'events:kategorie-create' event.id %}">Neue Kategorie</a>
views.py
class KategorieCreate(generic.CreateView):
model = Kategorie
fields = ['sport',...] # 'event' is excluded
template_name_suffix = '_create_form'
def get_context_data(self, **kwargs):
context = super(KategorieCreate, self).get_context_data(**kwargs)
context['event'] = kwargs.get(self.pk)
return context
我收到了:
NOT NULL constraint failed: events_kategorie.event_id
在上下文中设置该值没有意义;您需要在表单实例中这样做。这是 well documented:
def form_valid(self, form):
form.instance.event_id = self.kwargs['pk']
return super(KategorieCreate, self).form_valid(form)
请注意,我实际上无法理解您要在此处插入的值。使用类别PK作为事件id是没有意义的。