J2015
J2015

Reputation: 330

Django form does not save new post using based view function

I have a model as follow:

class Post(models.Model):
    title = models.CharField(max_length=150)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    date_posted = models.DateTimeField(default=timezone.now)
    imagefile = models.FileField(null=True, blank=True, upload_to='images', default='default.jpg')

There is a bug in the view file that, when I use class base view I can post the new post but whenever I use it as a function it does not save the form.

This one works(saves post in database):

class PostCreateView(LoginRequiredMixin, AjaxFormMixin, CreateView):
    model = Post
    template_name = "app/postform.html"
    success_url = '/posts'
    form_class = postform

But this one does not(does not save post in database):

@login_required
def PostCreateView(request):
    if request.method == 'POST':
        mform = postform(request.POST or None, request.FILES or None, instance=request.user)
        if mform.is_valid():
            mform.save() # when I print something here, Ill see something
            messages.success(request, f'Yes!')
            return redirect('posts')
    else:
        mform = postform()
    return render(request, 'myapplication/postform.html', {'form': mform})

and in postform.html:

 <form method="POST" action="" enctype="multipart/form-data">
     <fieldset class="form-group">
           {% csrf_token %}
           <div class="content-section">
               <!-- {{ form|crispy }} -->
           </div>
     </fieldset>
 </form>

and form.py:

class postform(forms.ModelForm):
    class Meta:
        model = Post
        fields = ("__all__")
        exclude = ['date_posted']

Upvotes: 0

Views: 35

Answers (1)

Pruthvi Barot
Pruthvi Barot

Reputation: 2018

I think the problem is that you form's model is post and you're assigning object of user as instance.

So try this way:

@login_required
def PostCreateView(request):
    if request.method == 'POST':
        mform = postform(request.POST or None, request.FILES or None)
        if mform.is_valid():
            post = mform.save(commit=False)
            post.author = request.user
            post.save()
            messages.success(request, f'Yes!')
            return redirect('posts')
    else:
        mform = postform()
    return render(request, 'myapplication/postform.html', {'form': mform})

Upvotes: 1

Related Questions