Linked Questions

Popular Questions

form is valid but not able to save to the backend

Asked by At

I built two apps, app blog for the normal blog, and app twit for asynchronous messaging, both using the homepage. Form is confirmed as post and also valid, but database not updated.

My first guess was that the user and content are not associated, and tried many ways in vain, hope get some help from you guys, thanks

Here are the codes:

homepage:

<form method="POST" id="twit" action={% url 'twit:create' %}>
    {% csrf_token %}
    {{form|crispy}}
    <div class="form-group">
        <button type="submit">Post</button>
    </div>
</form>

blog/views:

def home_view(request):
    form = TwitForm()
    post_list = Post.objects.all()
    context = {
        'form': form,
        'post_list':post_list,
    }
    return render(request, 'blog/blog_list.html', context)

twit/views:

def twit_create(request):
    if request.method == 'POST':
        form = TwitForm(request.POST or None, instance=request.user)
        print('inside post')
        if form.is_valid():
            print('inside valid')
            form.save()
            return redirect('blog:home')
    else:
        print('inside else')
        form = TwitForm(instance=request.user)
    post_list = Post.objects.all()
    context = {
        'post_list': post_list,
        'form': form,
    }
    return render(request, 'blog/blog_list.html', context)

from django import forms
from .models import Twit

class TwitForm(forms.ModelForm):
    class Meta:
        model = Twit
        fields = ['message']

twit/models

from django.db import models
from django.contrib.auth.models import User 

class Twit(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    message = models.TextField(max_length=100)
    published = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = 'twits'
        ordering = ['-published']
        verbose_name = 'twit'

    def __str__(self):
        return self.message[:10]

twit/forms

from django import forms
from .models import Twit

class TwitForm(forms.ModelForm):
    class Meta:
        model = Twit
        fields = ['message']

terminal:

inside post
inside valid
[07/Feb/2019 21:23:21] "POST /twit/create/ HTTP/1.1" 302 0
[07/Feb/2019 21:23:21] "GET / HTTP/1.1" 200 10548
[07/Feb/2019 21:37:33] "GET / HTTP/1.1" 200 10722

Related Questions