lukos06
lukos06

Reputation: 312

Passing the pk from url to CreateView form_valid

I want to pass pk of other model from URL to my CreateView form. How to do that? Could you help me? When I'm passing specific id it works, but I want to get the pk automatycly, from url. My views.py:

class ScenarioDetailView(LoginRequiredMixin, DetailView):
    model = Scenario

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = [
        'commentText'
    ]

    def form_valid(self, form):
        form.instance.commentAuthor = self.request.user
        form.instance.commentDate = datetime.now()
        form.instance.commentScenario = Scenario.objects.get(pk=1) #there is my problem
        return super().form_valid(form)

My url.py:

path('scenario/<int:pk>/', ScenarioDetailView.as_view(), name='scenario-detail'),

Also my model:

class Comment(models.Model):
    commentText = models.CharField(max_length=256)
    commentScenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
    commentAuthor = models.ForeignKey(User, on_delete=models.CASCADE)
    commentDate = models.DateTimeField(default=timezone.now)

Any suggestions?

Edit// enter image description here

Upvotes: 0

Views: 1887

Answers (1)

ruddra
ruddra

Reputation: 51988

You can get the value from self.kwargs dictionary. For example:

# url
path('comment/<int:scenario_id>/', CommentCreateView.as_view(), name='comment-create'),

# view
class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = [
        'commentText'
    ]
    def form_valid(self, form):
            form.instance.commentAuthor = self.request.user
            form.instance.commentDate = datetime.now()
            form.instance.commentScenario = Scenario.objects.get(pk=self.kwargs.get('scenario_id')) #there is my problem
            return super().form_valid(form)

Upvotes: 2

Related Questions