JenSeReal
JenSeReal

Reputation: 93

Django access PK/Object in URL

I have two classes - event and round. Round has a foreign key constraint to event, so a round is bound to an event.

Now to create a round I have the following route

<slug:slug_event>/new/

And to access a round

<slug:slug_event>/<int:pk_round>/

To save a round I need to declare a event. So in my round/views.py I have

fields = [..., 'event']

and I can select the event the round will be attached to. But I'd like to not have that event field, because the event is already given in the URL. So I'd like something like

class RoundCreateView(CreateView):
    model = Round
    pk_url_kwarg = 'pk_round'
    fields = [...]

    def form_valid(self, form):
        form.instance.event = self.request.event #obviously this dosn't work
        return super().form_valid(form)

so i don't need to specify the event "twice".

Upvotes: 1

Views: 108

Answers (1)

Alasdair
Alasdair

Reputation: 308949

You can fetch the event from the database using the slug from the URL:

def form_valid(self, form):
    event = get_object_or_404(Event, slug=self.kwargs['slug_event'])
    form.instance.event = event
    return super().form_valid(form)

Now you can remove `'event' from the form's fields.

Note that get_object_or_404 will display the 404 page if the event doesn't exist. You might want to do get_object_or_404 for GET requests as well, so that user's don't fill out the form for an invalid slug and then get a 404 error.

Upvotes: 1

Related Questions