Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

python - How to pass get object pk_ to inside of form valid function

I want to update an Article. when i try to submit the form i'm getting this error FileModel.post" must be a "Article" instance because i need to pass the article(primary key) inside FileModel(post=pk_) for create new files which is related with Article but i don't understand how can i pass the primary key from get_object function? I would be grateful for any help.

VIEWS

class UpdateViews(UpdateView):
    form_class = FileForm
    template_name = 'update.html'
    success_url = '/'

    def get_object(self):
        pk_ = self.kwargs.get('pk')
        FileModel.objects.filter(post=pk_).delete()
        return get_object_or_404(Article, pk=pk_)

    def form_valid(self, form):
        form.instance.author = self.request.user
        for f in self.request.FILES.getlist('file'):
            FileModel.objects.create(post=self.get_object.pk_, file=f) # error
        return super().form_valid(form)
question from:https://stackoverflow.com/questions/65908750/how-to-pass-get-object-pk-to-inside-of-form-valid-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to use post_id=form.instance.pk or post=form.instance

So:

FileModel.objects.create(post_id=form.instance.pk, file=f)

or

FileModel.objects.create(post=form.instance, file=f)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...