0
votes

My view: ''' from django.shortcuts import render from django.http import HttpResponse from .models import Post from .forms import createPostForm

def showPosts(request):
    if request.method == "POST":
        crf = createPostForm(request.POST)

        crf.author = request.user
        crf.save()


    else:
        crf = createPostForm()
    context = {
        'post' : Post.objects.all(),
        'crf' : crf

    }
    return render(request, 'Content/FeedsPage.html', context)

'''

My Model: '''

from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
    # image = models.ImageField(blank=True, null=True, upload_to='post_images/')
    # video = models.FileField(blank=True, null=True, upload_to='post_videos/')
    title = models.CharField(max_length=100)
    description = models.CharField(blank=True, max_length=1000)
    date_posted = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

'''

My Template:

'''

<form enctype="multipart/form-data" novalidate method="post">
                    {%csrf_token%}
                    <div class="fieldWrapper">
                        {{crf.title.errors}}
                        {{crf.title}}
                    </div>
                    <div class="fieldWrapper">
                        {{crf.description.errors}}
                        {{crf.description}}
                    </div>
                    <button class="primaryButton" type="submit">submit</button>
                </form>

''' My Form:

'''

from django import forms
from .models import Post
class createPostForm(forms.ModelForm):

    title = forms.CharField(
        widget = forms.TextInput(attrs={
        'placeholder': 'Give a sweet title',
        'autocomplete' :'off'
        })
    )
    description = forms.CharField(widget=forms.TextInput(attrs={
        'placeholder': 'Please elaborate a little',
        'autocomplete' :'off'
        }))

    class Meta:
        model = Post
        fields = '__all__'

'''

I removed the is_valid() function to see whats happening and apperently its showing 'The Post could not be created because the data didn't validate'

Please somebody help

1

1 Answers

0
votes

This save() method accepts an optional commit keyword argument, which accepts either True or False. If you call save() with commit=False, then it will return an object that hasn't yet been saved to the database. Which is neat for some post processing before actually saving it! So, you method should look something like this.

def showPosts(request):
if request.method == "POST":
    crf = createPostForm(request.POST)

    if crf.is_valid():

    form = crf.save(commit=False)
    form.author = request.user
    form.save()


else:
    crf = createPostForm()
context = {
    'post' : Post.objects.all(),
    'crf' : crf

}
return render(request, 'Content/FeedsPage.html', context)