Cannot get data into my database using django model forms - python

The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to do so instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that entered is saved anywhere? Here are the files below hopeful someone can see something I'm missing.
ps. I've connected my database, ran migrations and created a superuser as well but still nothing.
models.py
from django.db import models
Media_Choices = (
("TV", "TV"),
("Radio", "Radio"),
("Youtube", "Youtube"),
("Podcast", "Podcast"),
)
class Appear(models.Model):
Show = models.CharField(max_length=100)
Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices)
Episode = models.IntegerField()
Date = models.DateField(max_length=100)
Time = models.TimeField(auto_now=False, auto_now_add=False)
Producer = models.CharField(max_length=100)
Producer_Email = models.EmailField(max_length=254)
def __unicode__(self):
return self.Show + ' ' + self.Producer_Email
forms.py
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Appear
class AppsForm(ModelForm):
class Meta:
model = Appear
fields = '__all__'
def clean_Producer_Email(self):
Producer_Email = self.cleaned_data.get('Producer_Email')
if (Producer_Email == ""):
raise forms.ValidationError('field cannot be left empty')
for instance in Appear.objects.all():
if instance.Producer_Email == Producer_Email:
raise forms.ValidationError('Please fill in correct email')
return Producer_Email
views.py
from django.shortcuts import redirect, render
from django.http import HttpResponse
from .forms import AppsForm
from .models import Appear
def AppS(request):
if request == 'POST':
form = AppsForm(request.POST)
if form.is_valid():
Apps = form.save(Commit=False)
Apps.save()
else:
form = AppsForm()
return render(request, 'AppsForm.html', {'form': form})
def results(request):
return render(request, 'Results.html')
AppsForm.html
<body>
{% extends 'base.html' %}
{% block content %}
{% load crispy_forms_tags %}
<form action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="submit">
</form>
{% endblock %}
enter code here

You might be missing form errors due to which the form is not saving. Try printing if there are any form errors.
if form.is_valid():
Apps = form.save(Commit=False)
Apps.save()
else:
print(form.errors)

Related

Model form data not showing up in database. Form not saving data

The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to save into the database. Instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that is being entered is being saved anywhere? This is extremely confusing considering that I've done everything correctly.
ps. I've connected my database, ran migrations and created a superuser as well but still nothing.
models.py
from django.db import models
Media_Choices = (
("TV", "TV"),
("Radio", "Radio"),
("Youtube", "Youtube"),
("Podcast", "Podcast"),
)
class Appear(models.Model):
Show = models.CharField(max_length=100)
Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices)
Episode = models.IntegerField()
Date = models.DateField(max_length=100)
Time = models.TimeField(auto_now=False, auto_now_add=False)
Producer = models.CharField(max_length=100)
Producer_Email = models.EmailField(max_length=254)
def __unicode__(self):
return self.Show + ' ' + self.Producer_Email
forms.py
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Appear
class AppsForm(ModelForm):
class Meta:
model = Appear
fields = '__all__'
views.py
from django.shortcuts import redirect, render
from django.http import HttpResponse
from .forms import AppsForm
from .models import Appear
def AppS(request):
if request == 'POST':
form = AppsForm(request.POST)
if form.is_valid():
Apps = form.save(Commit=False)
Apps.save()
else:
form = AppsForm()
return render(request, 'AppsForm.html', {'form': form})
def results(request):
return render(request, 'Results.html')
AppsForm.html
<body>
{% extends 'base.html' %}
{% block content %}
{% load crispy_forms_tags %}
<form action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="submit">
</form>
{% endblock %}
Two Correction :
First : In AppsForm.html
<form action="" method="POST">
Provide a url to your form, where it should submit data
<form action="{% url 'url_name_for_Apps_view' %}" method="POST">
Second : In AppS view
This should be
if request == 'POST':
if request.method == 'POST':

Django forms are not saving any information

So I have been trying to build a manager of activities with django and I'm still on the scratch. I was trying to test if the code can simply show if a acitivity is done or not, but it don't change anything. Everything looks good to me and I don't know if the error is in the form, in the view that saves the form or in anything else. I already tried to change the widget and fields of form and haven't been succeed in it.
models.py:
from django.db import models
from django.contrib.auth.models import User
class Activity(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=30)
is_complete = models.BooleanField()
def __str__(self):
return self.title
forms.py:
from .models import Activity
class ActivityUpdateForm(ModelForm):
class Meta:
model = Activity
fields = ['is_complete']
views.py:
from .models import Activity
from .forms import ActivityUpdateForm
def home(request):
acts = Activity.objects.all()
if request.method == 'POST':
form = ActivityUpdateForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ActivityUpdateForm()
context = {
'acts': acts,
'form': form,
}
return render(request, 'diary/home.html', context)
template:
{% for act in acts %}
<form method="POST">
{% csrf_token %}
<p>{{ act.title }}</p>
<p>Is complete: {{ act.is_complete }}</p>
{{ form }}
<p>{{ act.author }}</p>
<button type="submit">Submit</button>
</form>
{% endfor %}```
This is not elegant, but you just might need to do this:
data = Activity.objects.get(author=request.user)
data.is_complete = form.cleaned_data["is_complete"]
data.save()
Please delete form.save() and write the code above.
i'm not sure if this works, but please give it a try.

Model is only updated in the Django Administration app and not in my app

I have just noticed that the model that I am displaying in my app is only showing new items that have been entered in the Django Administration app, and isn't showing anything that I enter directly from my own application. Could anyone explain what is going on?
Here is my models.py:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
class Ticket(models.Model):
"""
Add a ticket
"""
title = models.CharField(max_length=225,blank=False)
content = models.TextField()
created_date = models.DateTimeField(auto_now_add=True)
published_date = models.DateTimeField(blank=True, null=True, default=timezone.now)
views = models.IntegerField(default=0)
upvotes = models.IntegerField(default=0)
image = models.ImageField(upload_to="img", blank=True, null=True)
def __unicode__(self):
return self.title
and here is my admin.py in the same app:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Ticket
admin.site.register(Ticket)
and here is my forms.py:
from django import forms
from tickets.models import Ticket
class TicketsForm(forms.ModelForm):
class Meta:
model = Ticket
fields = ['title', 'content', 'image', 'published_date']
and views.py:
def ticket_detail(request,pk):
"""
Create a view that will return a single ticket object based on the ticket id
and render it to the 'show_tickets.html' template
"""
ticket = get_object_or_404(Ticket,pk=pk)
ticket.views +=1
ticket.save()
return render(request, "ticketdetail.html", {'ticket':ticket})
def create_or_edit_ticket(request, pk=None):
"""
Create a view that allows us to create or edit a ticket depending if
the tickets id is null or not.
"""
ticket = get_object_or_404(Ticket, pk=pk) if pk else None
if request.method == "POST":
form = TicketsForm(request.POST, request.FILES, instance=ticket)
if form.is_valid():
ticket = form.save()
return redirect(ticket_detail, ticket.pk)
else:
form = TicketsForm(instance=ticket)
return render(request, "issuetrackerticketform.html", {'form':form})
the actual form that is used to enter a new ticket:
{% extends "base.html" %}
{% load bootstrap_tags %}
{% block content %}
<h1>Add Issues</h1>
<form method="POST" class="col-md-12" enctype="multipart/form-data">
{% csrf_token %}
{{ form | as_bootstrap }}
<span class="glyphicon glyphicon-ok-sign" aria-hidden="true"></span>Create Issue
</form>
{% endblock %}
By making use of a link (…), you will make a GET request to the view to that link, not submit the form with a POST request to the view. You thus should submit the form, for example with <button type="submit">…</button>):
<form method="POST" class="col-md-12" enctype="multipart/form-data">
{% csrf_token %}
{{ form | as_bootstrap }}
<button type="submit"><span class="glyphicon glyphicon-ok-sign" aria-hidden="true"></span>Create Issue</button>
</form>

Link Username To Post Created By User

I would like to link the user who created the post by their username that way people know who it was posted by but I can't seem to get it to work and yes I am logged in and I have a working register and login form already.
Every time I go to submit some news from the form when logged in I get this error NOT NULL constraint failed: news_news.author_id
models.py
from django.db import models
from django.contrib.auth.models import User
from markdownx.models import MarkdownxField
from markdownx.utils import markdownify
from taggit.managers import TaggableManager
class News(models.Model):
author = models.ForeignKey(User, unique=True, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
short_desc = models.CharField(max_length=500)
content = MarkdownxField()
tags = TaggableManager()
slug = models.SlugField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Category, News
from .forms import NewNewsForm
from django.shortcuts import render
def show_news_view(request):
news = News.objects.values('author', 'title', 'short_desc', 'tags', 'created_at', 'updated_at')
context = {
'news': news
}
return render(request, "news/news_home.html", context)
def new_news_form_view(request):
if request.method == "POST":
form = NewNewsForm(request.POST or None)
if form.is_valid():
form.save()
form = NewNewsForm()
return redirect('/news')
else:
form = NewNewsForm()
context = {
'form': form
}
return render(request, "news/news_form.html", context)
EDIT:
forms.py
from django import forms
from .models import News
class NewNewsForm(forms.ModelForm):
class Meta:
model = News
fields = ['title', 'short_desc', 'content', 'category', 'tags', 'slug']
news_form.html
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% else %}
<p>Please login before you can submit a news story.</p>
{% endif %}
{% endblock content %}
You are not passing the user.
Later edit with a simpler solution:
Simply pass commit=False when saving the form. Which will create your News object without commiting it to DB. Simply set the author afterwards and save the object.
def new_news_form_view(request):
if request.method == "POST":
form_data = request.POST or None
form = NewNewsForm(form_data)
if form.is_valid():
news = form.save(commit=False)
news.author = request.user
news.save()
return redirect('/news')
else:
form = NewNewsForm()
context = {
'form': form
}
return render(request, "news/news_form.html", context)

ModelForm returning server error (500)

See the code below. I'm trying to use ModelForms to add records to a database, but it keeps returning the server error - seemingly against the .save() action, but I'm not quite sure. Any help towards how I can fix this would be really appreciated.
#view.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, render_to_response, get_object_or_404
from django.template import RequestContext
from forms import ContactForm, wallForm
from django.core.mail import send_mail
from home.models import wall
from django.forms import ModelForm
def wallpost(request):
if request.method == 'POST':
new_post = wallForm(request.POST)
if form.is_valid():
f = form.cleaned_data['postContent']
new_post.save()
return HttpResponseRedirect('/home/')
else:
form = wallForm()
return render(request, 'home/wall_post.html', {'form': form,})
#model.py
from django.db import models
class wall(models.Model):
clusterId = models.ForeignKey(cluster)
userId = models.ForeignKey(user)
postContent = models.CharField(max_length=800)
likes = models.IntegerField(default=0)
post_timestamp = models.DateTimeField('date published')
clusterId.blank = True
userId.blank = True
postContent.blank = True
likes.blank = True
post_timestamp.blank = True
#forms.py
from django import forms
from django.forms import ModelForm
from home.models import wall
class wallForm(ModelForm):
class Meta:
model = wall
#template.py
<h1>Posting test</h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="" method="post">
<table>
{{ form.as_p }}
</table>
{% csrf_token %}
<input type="submit" value="Submit">
</form>
<b>Go back...</b>
Your problem is here:
def wallpost(request):
if request.method == 'POST':
new_post = wallForm(request.POST)
if form.is_valid():
f = form.cleaned_data['postContent']
new_post.save()
return HttpResponseRedirect('/home/')
else:
form = wallForm()
return render(request, 'home/wall_post.html', {'form': form,})
In this line if form.is_valid(), form is not actually defined. You probably want if new_post.is_valid(), and similarly form.cleaned_data should be new_post.cleaned_data.
Also, its not clear what you are doing with this line f = form.cleaned_data['postContent'], because you don't use f anywhere.
Thanks for your input. After setting debug = True, I realised that the error was coming from two different points.
Two of my foreign key fields in my model could not be empty (despite setting their model attribute blank = True). Once this was resolved, there was then an error in the database;
I'm not sure what caused the database error, but when I dropped the database, created a new one, and re-ran syncdb, everything seemed to work fine. Must have something to do with fields not lining up.
Thanks again for the help.

Categories

Resources