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
111 views
in Technique[技术] by (71.8m points)

python - How to pass form_class data into model objects create in Django?

I want to create article form in Django. The code below getting Error FileModel.post" must be a "Article" instance. because i want to create multiple file related article instances which is coming from forgnekey. i need to pass example post=form.instances when i submit form data but i don't understand how can i pass FileModel.objects.create(post=self.form_class, file=f)? I would be grateful for any help.

views.py

class CreateView(CreateView):
    form_class = FileForm
    template_name = 'create.html'
    success_url = '/'
    success_message = "New story has been created successfully"

    def form_valid(self, form):
        form.instance.author = self.request.user
        for f in self.request.FILES.getlist('file'):
            FileModel.objects.create(post=self.form_class, file=f) # Error is here!
        return super().form_valid(form)
question from:https://stackoverflow.com/questions/65909922/how-to-pass-form-class-data-into-model-objects-create-in-django

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

1 Answer

0 votes
by (71.8m points)

You need to pass the instance created by the form, rather than just the form class. For example:

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

Update: As the Article hasn't been saved yet, when you try to attach it to the FileModel object, it won't let you.

Try something like this:

def form_valid(self, form):
    post = form.save(commit=False)
    post.author = self.request.user
    post.save()
    for f in self.request.FILES.getlist('file'):
        FileModel.objects.create(post=post, file=f)
    return redirect('/')

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

...