user6210879
user6210879

Reputation: 51

Django CreateView: automatically set two foreign key fields in a form

I have a model called "Booking" where events are booked between a user and an expert. I'm trying to set the booking CreateView to automatically know the current user and the expert who's profile the user was visiting so that these two users do not need to be selected from dropdown menus in the booking form. I am able to do this successfully for the current user by overriding the form_valid method, but not sure how to do this for the expert.

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)

I've tried setting "form.instance.expert" to the form_valid method, but it didn't work. Thanks.

Upvotes: 0

Views: 833

Answers (1)

user6210879
user6210879

Reputation: 51

Answered my question with the help of the comment above. Answer is in 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)

Upvotes: 1

Related Questions