1

A Django beginner here, having a lot of trouble getting forms working. I've tried different ways, but I can't save the user in the database. I get this error:

"IntegrityError at /n_post/ NOT NULL constraint failed: learning_logs_post.owner_id"

views.py:

def nuovo_post(request):
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = PostForm()
    else:
        # POST data submitted; process data.
        form = PostForm(request.POST)
        if form.is_valid():
            n_post = form.save(commit=False)
            n_post.owner = request.user
            n_post.save()
            return HttpResponseRedirect(reverse('learning_logs:posts'))
    context = {'form': form}
    return render(request, 'learning_logs/nuovo_post.html', context)

models.py:

class Post(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    image = models.ImageField(blank=True)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User)

forms.py:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'description', 'image']
        labels = {'title': "Title", 'description': "Description"}
        widgets = {'description': forms.Textarea(attrs={'cols': 80})}

urls.py:

urlpatterns = [
# Home Page [[ ^$ = stringa vuota ]]
url(r"^$", views.index, name="index"),
url(r"^servizi/$", views.servizi, name="servizi"),


url(r"^catering/$", views.catering, name="catering"),
url(r"^eventi_degustazioni/$", views.eventi_degustazioni, name="eventi_degustazioni"),
url(r"^academy/$", views.academy, name="academy"),

url(r"^corsi/$", views.corsi, name="corsi"),
url(r'^corsi/(?P<corso_id>\d+)/$', views.corso, name='corso'),


url(r"^shop/$", views.shop, name="shop"),
url(r"^chi_siamo/$", views.chi_siamo, name="chi_siamo"),
url(r"^lavora_con_noi/$", views.lavora_con_noi, name="lavora_con_noi"),


url(r"^spazio_utenti/$", views.spazio_utenti, name="spazio_utenti"),
url(r'^posts/$', views.post, name="posts"),
url(r'^posts/(?P<post_id>\d+)/$', views.post, name='post'),
url(r'^nuovo_post/$', views.nuovo_post, name="nuovo_post"),
url(r'^modifica_post/(?P<post_id>\d+)/$', views.modifica_post, name='modifica_post'),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
bouteillebleu
  • 2,456
  • 23
  • 32
ilbose
  • 747
  • 13
  • 21

1 Answers1

1

When the user has not logged into your site. request.user is an instance of AnonymousUser. This instance does not have an id. Therefore the owner_id field in your model becomes null which is not allowed by the database constraint. Try something like this:

def nuovo_post(request):

    if request.user.is_authenticated():
        if request.method != 'POST':
            # No data submitted; create a blank form.
            form = PostForm()
        else:
            # POST data submitted; process data.
            form = PostForm(request.POST)
            if form.is_valid():
                n_post = form.save(commit=False)
                n_post.owner = request.user
                n_post.save()
                return HttpResponseRedirect(reverse('learning_logs:posts'))
        context = {'form': form}
        return render(request, 'learning_logs/nuovo_post.html', context)
    else :
        return HttpResponseRedirect('/login/')

taking care to redirect to the appropriate login url

IntegrityError at /n_post/ NOT NULL constraint failed: learning_logs_post.owner_id

This answer is essentially correct for the question you have asked. But your update shows that your error has nothing to do with the code you have posted. (this code would produce the same error, but the error you are seeing is for similar code elsewhere).

The following line shows the the nuovu_post does not map to the url in your error.

url(r'^nuovo_post/$', views.nuovo_post, name="nuovo_post"),
e4c5
  • 52,766
  • 11
  • 101
  • 134
  • I've just tried, and now I got a new error. "TypeError at /posts/ post() missing 1 required positional argument: 'post_id'" – ilbose Jan 31 '17 at 10:06
  • And if I remove commit=False it keeps getting me: "IntegrityError at /n_post/ NOT NULL constraint failed: learning_logs_post.owner_id" – ilbose Jan 31 '17 at 10:20
  • neither of those errors have anything to do with my answer. – e4c5 Jan 31 '17 at 10:54
  • Please do post your urls.py and also confirm that you added the is_authenticated part of the code suggested in my answer – e4c5 Jan 31 '17 at 10:54
  • Yep, I confirm that I've added the is_authenticated part of the code that you have suggested. Now I have added in the question My urls.py. – ilbose Jan 31 '17 at 13:03
  • Well, the urls.py shows that the error is not in this code :-)) – e4c5 Jan 31 '17 at 13:37
  • 1
    Just look at the function that maps to that url. Look at the full stacktrace. See what line in your code is referred to it. If you still have trouble post a new question with the full stacktrace – e4c5 Jan 31 '17 at 13:55