嗨,我从昨天起就在努力。
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约束失败:events_kategorie.event_id
答案 0 :(得分:1)
在上下文中设置该值没有意义;你需要在表单实例中这样做。这是well documented:
def form_valid(self, form):
form.instance.event_id = self.kwargs['pk']
return super(KategorieCreate, self).form_valid(form)
注意,我实际上无法理解您要插入的值。使用类别PK作为事件的id是没有意义的。