Django CreateView:在表单中自动设置两个外键字段

时间:2018-12-05 16:22:24

标签: python django django-forms django-views

我有一个称为“预订”的模型,该模型在用户和专家之间预订事件。我正在尝试将预订CreateView设置为自动了解当前用户以及该用户正在访问的个人资料的专家,这样就无需从预订表单的下拉菜单中选择这两个用户。通过覆盖form_valid方法,我可以为当前用户成功完成此操作,但是不确定如何为专家执行此操作。

models.py:

class Booking(models.Model):
    user = models.ForeignKey(CustomUser, null=True, default='', on_delete=models.CASCADE)
    expert = models.ForeignKey(CustomUser, null=True, default='',on_delete=models.CASCADE, related_name='bookings')
    title = models.CharField(max_length=200, default='Video call with ..', null=True)
    start_time = models.DateTimeField('Start time', null=True)
    end_time = models.DateTimeField('End time', null=True)
    notes = models.TextField('Notes', help_text='Please provide some detail on what you would like to learn or discuss', blank=True, null=True)

views.py:

class BookingView(CreateView):
    model = Booking
    form_class = BookingForm
    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(BookingView, self).form_valid(form)

urls.py:

urlpatterns = [
    #path('', include('booking.urls')),
    path('signup/', views.SignUp.as_view(), name='signup'),
    path('login/', auth_views.LoginView.as_view(), {'authentication_form': LoginForm}, name='login'),
    path('profile/', views.view_profile, name='profile'),
    path('profile/<int:pk>/', views.view_profile, name='profile_with_pk'),
    path('profile/<int:pk>/booking/', BookingView.as_view(), name='user_booking_new'),
    path('profile/edit/', views.EditProfileView, name='edit_profile'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我尝试将“ form.instance.expert”设置为form_valid方法,但是没有用。谢谢。

1 个答案:

答案 0 :(得分:1)

借助以上评论回答了我的问题。答案在views.py中:

class BookingView(CreateView):
model = Booking
form_class = BookingForm
def form_valid(self, form):
    form.instance.user = self.request.user
    form.instance.expert = CustomUser.objects.get(id=self.kwargs.get('pk'))
    return super(BookingView, self).form_valid(form)