0

I am new to django, I created a form to save Data into my database but it not working corectly, I got no error but data is not sent in database. Thanks for helping!

views.py

@login_required()
def data(request):
    if request.POST == "POST":
        form = CreatePost(request.POST)
        if form.is_valid():
            form.instance.author = request.user
            form.save()
            return redirect(data)
    else:
        form = CreatePost()
    context = {
        "form": form
    }
    return render(request, "sms/data.html", context)

forms.py

class CreatePost(forms.ModelForm):

    class Meta:
        model = Post
        fields = ["title", "content"]

models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)


    def __str__(self):
        return self.title

data.html

<form method="POST">
    {% csrf_token %}
    {{ form|crispy }}
      <pre></pre>
    <button class="btn btn-outline-info" type="submit" value="Submit">Data</button>
</form>
6
  • Are you sure your form is valid? Are you displaying {{form.errors}} in your template so you see if there are errors?
    – dirkgroten
    Commented Mar 4, 2020 at 16:22
  • Ah: if request.POST == "POST" is always false. It's probably this simple typo you made which causes your issue.
    – dirkgroten
    Commented Mar 4, 2020 at 16:23
  • If i write {{form.errors}} in template, my form is not shown on my page, I updated my post with my template Commented Mar 4, 2020 at 16:28
  • did you change the line if request.POST?????
    – dirkgroten
    Commented Mar 4, 2020 at 16:30
  • Florin's answer was first and correct. He already mentioned to fix request.POST to request.method. You should mark his answer correct, not the other one.
    – dirkgroten
    Commented Mar 4, 2020 at 16:39

2 Answers 2

1

try like this

@login_required()
def data(self, request):
 if request.method == "POST": #this line
    form = CreatePost(request.POST)
    if form.is_valid():
        post = form.save(commit=False) #new line
        post.author = self.request.user #this line
        post.save() #this line
        return redirect(data)
else:
    form = CreatePost()
context = {
    "form": form
}
return render(request, "sms/data.html", context)
0
0
if request.POST == "POST":

Should instead be:

if request.method == 'POST':

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.