Django: Form is not saving to database - python

I've seen similar types of problems on here but I still haven't been able to work out my problem. When I save PhotographerProfileForm in my view, the form is rendered correctly but after clicking update/submit nothing is actually saved.
No errors are shown either.
What I have now are the fields are prepopulated and I would like the ability to save over these in the database, but nothing happens and at the moment you can only update it from the admin panel.
models.py
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class PhotographerProfile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=200)
bio = models.TextField(max_length=500)
def __str__(self):
return self.user.username
User.profile = property(lambda u: PhotographerProfile.objects.get_or_create(user=u)[0])
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def create_profile(sender,instance,created,**kwargs):
if created:
profile, new = PhotographerProfile.objects.get_or_create(user=instance)
urls.py
urlpatterns = [
url(r'^profile/$', 'photoprofile.views.photographer_profile', name = 'photographer_profile'),
url(r'^profile/portfolio/$', 'photoprofile.views.photographer_portfolio', name='photographer_portfolio'),
]
views.py
#login_required
def photographer_profile(request):
photographerProfile = PhotographerProfile.objects.get(user=request.user)
form = PhotographerProfileForm(initial={'bio':photographerProfile.bio, 'location':photographerProfile.location})#This means you can prepoulate it
return render_to_response('photographerprofile.html',{'form':form}, RequestContext(request))
if request.method == 'POST':
form = PhotographerProfileForm(request.POST, instance = request.user.profile,)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/profile')
else:
user = request.user
profile = user.profile
form = PhotographerProfileForm()
return render(request, 'photographerprofile.html', {'form':form})
def photographer_portfolio(request):
photographerProfile = PhotographerProfile.objects.get(user=request.user)
return render_to_response('photographerportfolio.html', {'photographerProfile':photographerProfile}, RequestContext(request))
forms.py
class PhotographerProfileForm(forms.ModelForm):
class Meta:
model = PhotographerProfile
exclude = ('user',)
photographerprofile.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h2> Profile</h2>
{% for field in form %}
{{ field.error}}
{% endfor %}
<form action='/accounts/profile/' method='post'>
{% csrf_token %}
{{form|crispy}}
<input type='submit' value='Update'/>
<p>Click <a href='/accounts/profile/portfolio/'>here</a> to view portfolio. </p>
</form>
{% endblock %}

You return in the third line of your view, before the form has been processed. Remove that line.

Related

Django - Form not saving when submitted

Good afternoon all,
One of my form does not seem to save when submitted. I cannot see why, in particular as I have a similar form working just fine using the same code.
For some reason it work just fine using the admin panel.
My assumption is that I am missing something that tells the form it needs to be saved. But cannot find what.
Any ideas?
Models
RATING=(
(1,'1'),
(2,'2'),
(3,'3'),
(4,'4'),
(5,'5'),
)
class ProductReview(models.Model):
user=models.ForeignKey(User, on_delete=models.CASCADE)
product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE)
review_text=models.TextField(max_length=250)
review_rating=models.IntegerField(choices=RATING,max_length=150, default=0)
date_added = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
Views
def add_review(request, product_id):
product = Product.objects.get(pk=product_id)
form = ReviewAdd(request.POST or None, instance=product) #instance=product (populate field with existing information)
if form.is_valid():
form.save()
return redirect('product')
return render(request, 'main/add_review.html',{'form':form})
URL
from django.urls import path
from . import views
urlpatterns = [
...
path('product/add_review/<product_id>', views.add_review,name="add_review"),
]
Forms
class ReviewAdd(forms.ModelForm):
class Meta:
model = ProductReview
fields = ('review_text', 'review_rating')
labels ={
'review_text': '',
'review_rating': '',
}
widgets = {
'review_text': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Review'}),
}
Admin
from django.contrib import admin
from .models import Venue, User, Product, ProductReview
from django.urls import path
admin.site.register(User)
admin.site.register(ProductReview)
class ProductReview(admin.ModelAdmin):
list_display=['user','product','review_text','get_review_rating']
HTML Page
{% extends 'main/base.html' %}
{% load crispy_forms_tags %}
{% block title %}
{% endblock %}
{% block content %}
<center>
<h1>Add ReviewTo Database</h1>
<br/><br/>
{% if submitted %}
Success!
{% else %}
<form action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="Submit" value="Submit" class="btn btn-secondary">
</form>
{% endif %}
</center>
{% endblock %}
I detect 2 fixes
On your url, the parameter product_id might need the type of data it will going to receive
path('product/add_review/<int:product_id>', views.add_review,name="add_review"),
And in your view, you are sending an instance, and no data for a new rating.
In your view:
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
#login_required
def add_review(request, product_id):
product = get_object_or_404(Product, pk=product_id)
form = ReviewAdd(request.POST or None)
if form.is_valid():
new_rating = form.save(commit=False)
new_rating.product = product
new_rating.user = request.user
new_rating.save()
return redirect('product')
return render(request, 'main/add_review.html',{'form':form})

Making a topic public to all users in Django

I've got a project where users can enter topics and have the option to make the topic public or private. I want all public topics to be visible to everyone, and private topics to only be visible by the owner of that topic (Project is from Python Crash Course exercise 20-5).
I'm not getting any errors when I click through my project, but when I create a new topic and select the "public" option, it is still not showing up for public viewing.
I've researched similar problems and followed all the suggestions here
How to make a topic public to all users in django? and here Django - How to make the topics, that you create public? Learning Log Project with no luck.
I'm guessing my queryset is not rendering data correctly? I've read the Django documentation on querysets as well, but nothing I've tried has worked. I'm really new to programming so any help would be appreciated. Thank you!
Here's my models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
public = models.BooleanField(default=False)
def __str__(self):
"""Return a string representation of the model"""
return self.text
class Entry(models.Model):
"""Something specific learned about a topic"""
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
"""Retrun a string representation of the model"""
if len(self.text) < 50:
return f"{self.text}"
else:
return f"{self.text[:50]}..."
views.py:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404
from .models import Topic, Entry
from .forms import TopicForm, EntryForm
# Create your views here.
def index(request):
"""The home page for Learning Log"""
return render(request, 'learning_logs/index.html')
#Checks whether logged in user has access to topic
def check_topic_owner(request, topic):
if topic.owner != request.user:
raise Http404
def topics(request):
"""Shows all topics"""
#Gets public topics
public_topics = Topic.objects.filter(public=True).order_by('date_added')
#Gets private topics
if request.user.is_authenticated:
private_topics = Topic.objects.filter(owner=request.user).order_by('date_added')
topics = public_topics | private_topics
else:
topics = public_topics
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context)
def topic(request, topic_id):
"""Show a single topic and all its entries"""
topic = get_object_or_404(Topic, id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'learning_logs/topic.html', context)
#login_required
def new_topic(request):
"""Add a new topic"""
if request.method != 'POST':
#No data submitted; create a blank form.
form = TopicForm()
else:
#POST data submitted; process data
form = TopicForm(data=request.POST)
if form.is_valid():
new_topic = form.save(commit=False)
new_topic.owner = request.user
new_topic.save()
return redirect('learning_logs:topics')
#Display a blank or invalid form
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
#login_required
def new_entry(request, topic_id):
"""Add a new entry for a particular topic"""
topic = get_object_or_404(Topic, id=topic_id)
check_topic_owner(request, topic)
if request.method != 'POST':
#No data submitted, create a blank form
form = EntryForm()
else:
#POST data submitted; process data
form = EntryForm(data=request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.topic = topic
if new_entry.topic.owner == request.user:
new_entry.save()
else:
return Http404
return redirect('learning_logs:topic', topic_id=topic_id)
#Display a blank or invalid form
context = {'topic': topic, 'form': form}
return render(request, 'learning_logs/new_entry.html', context)
#login_required
def edit_entry(request, entry_id):
"""Edit an existing entry"""
entry = get_object_or_404(Entry, id=entry_id)
topic = entry.topic
check_topic_owner(request, topic)
if request.method != 'POST':
#Initial request; prefill with the current entry
form = EntryForm(instance=entry)
else:
#POST data submitted; process data
form = EntryForm(instance=entry, data=request.POST)
if form.is_valid():
form.save()
return redirect('learning_logs:topic', topic_id=topic.id)
context = {'entry': entry, 'topic': topic, 'form': form}
return render(request, 'learning_logs/edit_entry.html', context)
new_topic.html:
{% load bootstrap4 %}
{% block page_header %}
<h3>Add a new topic:</h3>
{% endblock page_header %}
{% block content %}
<form method="post" action="{% url 'learning_logs:new_topic' %}" class="form">
{% csrf_token %}
{% bootstrap_form form %}
<div class="form-check">
<input class="form-check-input" type="checkbox" value=True id="public" />
<label class="form-check-label" for="public">
<p>Make post public?<p/>
</label>
</div>
{% buttons %}
<button name="submit" class="btn btn-primary">Add topic</button>
{% endbuttons %}
</form>
{% endblock content %}
And forms.py:
from .models import Topic, Entry
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text']
labels = {'text': ''}
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['text']
labels = {'text': ''}
widgets = {'text': forms.Textarea(attrs={'cols': 80})}
And topics.html:
{% block page_header %}
<h1>Topics</h1>
{% endblock page_header %}
{% block content %}
<ul>
{% for topic in topics %}
<li><h4>
{{ topic }}
</h4></li>
{% empty %}
<li><h4>No topics have been added yet.</h4></li>
{% endfor %}
</ul>
<h4>Add a new topic</h4>
{% endblock content %}
Edit:
I've gotten the project to work as expected now with the help from hasnain095. Here is my updated new_topic.html. I still don't understand how the checkbox is being generated since I've deleted the html which I thought was specifically generating it, but since it's still working, I'm content.
{% extends "learning_logs/base.html" %}
{% load bootstrap4 %}
{% block page_header %}
<h3>Add a new topic:</h3>
{% endblock page_header %}
{% block content %}
<form method="post" action="{% url 'learning_logs:new_topic' %}" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button name="submit" class="btn btn-primary">Add topic</button>
{% endbuttons %}
</form>
{% endblock content %}
I think the issue is that you've only specified the field 'text in your Topic Form:
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text']
labels = {'text': ''}
but in new_topic.html file, you have only one checkbox input, no place to enter the text
<div class="form-check">
<input class="form-check-input" type="checkbox" value=True id="public" />
<label class="form-check-label" for="public">
<p>Make post public?<p/>
</label>
</div>
{% buttons %}
<button name="submit" class="btn btn-primary">Add topic</button>
{% endbuttons %}
Your checkbox for "Make post public?" is getting mapped to the field "text" of your Topic.
To fix do:
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text', 'public']
labels = {'text': ''}
and
<div class="form-check">
<input class="form-check-input" type="checkbox" value=True id="public" />
<label class="form-check-label" for="public">
<p>Make post public?<p/>
</label>
<input class="form-input" type="input" value=True id="text1" />
<label class="form-label" for="text1">
<p>Text<p/>
</label>
</div>
Use unions to add to a queryset:
def topics(request):
"""Shows all topics"""
# Gets public topics (renamed to topic_set to not shadow function name)
topic_set = Topic.objects.filter(public=True).order_by('date_added')
# Add private topics, if any. We save some work by not including the public
# topics.
if request.user.is_authenticated:
topic_set = topic_set.union(
Topic.objects.filter(public=False, owner=request.user)
)
context = {'topics': topic_set}
return render(request, 'learning_logs/topics.html', context)
Side note: add indexes to fields you filter on:
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
public = models.BooleanField(default=False, db_index=True)
def __str__(self):
"""Return a string representation of the model"""
return self.text
It's working for me after use union to append private topics to public topic, but there maybe some different. list below, hope will help:
views.py
def check_topic_owner(topic, request):
if not topic.public:
if topic.owner != request.user:
raise Http404
def topics(request):
#Gets public topics
public_topics = Topic.objects.filter(public=True)
#Gets private topics and append the public topic
if request.user.is_authenticated:
private_topics = Topic.objects.filter(owner=request.user)
topics = public_topics.union(private_topics).order_by('date_added')
else:
topics = public_topics
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context)
models.py
class Topic(models.Model):
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
public = models.BooleanField(default=False)
def __str__(self):
return self.text

I am not able to retrive OneToOneField data from backend Django

i can get data from backend from User e.g user.id but when i want to get data from OneToOneField e.g user.checkAdmin.isAdmin its not displaying any data in html page
views.py
def registerView(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
isAdminForm = checkAdminForm(request.POST) #
if form.is_valid() and isAdminForm.is_valid():
user = form.save()
isAdminFormObject = isAdminForm.save(commit=False)
isAdminFormObject.user = user
isAdminFormObject.save()
return redirect('login_url')
else:
form = UserCreationForm()
isAdminForm = checkAdminForm()
return render(request, 'registration/register.html',{'form':form,'isAdminForm':isAdminForm})
Forms.py
from django import forms
from .models import checkAdmin
class checkAdminForm(forms.ModelForm):
class Meta:
model = checkAdmin
fields = ['isAdmin']
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class checkAdmin(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
isAdmin = models.BooleanField(default=False)
def __str__(self):
return self.user.username
dashboard.html
{% extends 'index.html' %}
{% block content %}
<h1>Welcome, {{ user.id }}</h1>
<h1>check?,{{ user.checkAdmin.isAdmin }}</h1>
<button>Mark Attendance</button> <button>Mark Leave</button> <button>View Attance</button>
Logout
{% endblock %}
use checkadmin instead of checkAdmin
{% extends 'base.html' %}
{% block content %}
<h1>Welcome, {{ user.id }}</h1>
<h1>check?,{{ user.checkadmin.isAdmin }}</h1>
<button>Mark Attendance</button> <button>Mark Leave</button> <button>View Attance</button>
Logout
{% endblock %}

Django ModelForm; User, this field is required

I am having some issues with a (model)form consisting of just a single button. When I try to submit the form this message is displayed:
user
This field is required.
The ModelForm looks like this:
from django.forms import ModelForm
from .models import HulpOproep
class HulpOproepForm(ModelForm):
class Meta:
model = HulpOproep
fields = ['user', ]
The Model looks like this:
class HulpOproep(models.Model):
user = models.ForeignKey(User)
time = models.DateTimeField(auto_now_add=True, verbose_name='Tijd')
def __str__(self):
return '%s %s' % (self.user.username, str(self.time))
def username(self):
return self.user.username
def first_name(self):
return self.user.first_name
def last_name(self):
return self.user.last_name
class Meta:
verbose_name = 'Hulp Oproep'
verbose_name_plural = 'Hulp Oproepen'
The View looks like this:
def verzend_oproep(request):
if request.method == 'POST':
form = HulpOproepForm(request.POST)
if form.is_valid():
oproep = form.save(commit=False)
oproep.user = request.user
oproep.save()
return redirect('portal/index/')
else:
form = HulpOproepForm()
return render(request, 'portal/verzend_oproep.html', {'form': form})
The Template:
{% extends "base.html" %}
{% block head %}
<title>Zorggroep | Hulp Oproep</title>
{% endblock %}
{% block body%}
<h1>Verstuur Hulpoproep</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_P }}
{{ form.errors }}
<button type="submit" class="save btn btn-default">Verstuur</button>
</form>
{% endblock %}
The 'user' in the HulpOproep model is a ForeignKey and should be the currently logged in user's User object. I tried to specify this using the line:
oproep.user = request.user
So what should happen is:
Get the current user's 'User' object and use it as the 'HulpOproepForm.user'. This way the 'HulpOproepForm.user' is the 'HulpOproep.user' and a Foreign Key.
I have followed multiple tutorials and have searched around, but I cannot find a solution. I'm sorry if the answer is logical, but I have been using Django for only 5 days and have 1.5 months of programming experience under my belt.
Thank you!
Thanks PatNowak and Radek!
I did not know the form was waiting for user input instead of code input. I managed to fix it by adding exclude to the ModelForm.
class HulpOproepForm(ModelForm):
class Meta:
model = HulpOproep
exclude = ['user', 'time']

Django save() is not saving form to database

Hello I have problem with saving forms to database. When I try to save the AdHistoryForm in ads_history_add view the forim is rendered correctly but after submitting nothing happens aside of redirecting me to ads_history_list view.
In addition when I try to submit this form with empty field it doesnt show any errors (I included them in template), so maybe it is validation thing.
When I try to add Ad in ads_add view everything is ok.
Can you help me?
models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
class Ad(models.Model):
title = models.CharField(max_length=128, verbose_name=_("name"), help_text=_("required"), unique=True)
content = models.TextField(verbose_name=_("content"), blank=True)
url = models.URLField(verbose_name=_("website"), blank=True)
date_create = models.DateTimeField(auto_now_add=True)
date_modify = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
class AdHistory(models.Model):
ad = models.ForeignKey(Ad)
user = models.ForeignKey(User)
comment = models.TextField(verbose_name=_("comment"), help_text=_("required"))
date_create = models.DateTimeField(auto_now_add=True)
date_modify = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.comment
forms.py
from django import forms
from .models import Ad, AdHistory
class AdForm(forms.ModelForm):
class Meta:
model = Ad
fields = ['title', 'content', 'url']
class AdHistoryForm(forms.ModelForm):
class Meta:
model = AdHistory
fields = ['comment']
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.utils.translation import ugettext as _
from .models import Ad, AdHistory
from .forms import AdForm, AdHistoryForm
#login_required
#user_passes_test(lambda u: u.is_superuser)
def ads_list(request):
ads_list = Ad.objects.all().order_by('-date_modify')
context = {'list': ads_list}
return render(request, 'ads_list.html', context)
#login_required
#user_passes_test(lambda u: u.is_superuser)
def ads_add(request):
form = AdForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('ads_list')
context = {'form': form}
return render(request, 'ads_form_add.html', context)
#login_required
#user_passes_test(lambda u: u.is_superuser)
def ads_history_list(request, ad_id):
ad = get_object_or_404(Ad, pk=ad_id)
history_list = AdHistory.objects.select_related().filter(ad=ad).order_by('-id')
context = {'list': history_list, 'object': ad}
return render(request, 'ads_history_list.html', context)
#login_required
#user_passes_test(lambda u: u.is_superuser)
def ads_history_add(request, ad_id):
ad = get_object_or_404(Ad, pk=ad_id)
f = AdHistoryForm(request.POST or None)
if f.is_valid():
new_entry = f.save(commit=False)
new_entry.ad = ad
new_entry.user = request.user
new_entry.save()
return redirect('ads_history_list', ad_id)
context = {'form': f, 'object': ad}
return render(request, 'ads_history_add.html', context)
urls.py
rom django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from ads import views
urlpatterns = patterns(
'',
url(r'^$', views.ads_list, name="ads_list"),
url(r'^add/', views.ads_add, name="ads_add"),
url(r'^(?P<ad_id>\d+)/history/$', views.ads_history_list, name="ads_history_list"),
url(r'^(?P<ad_id>\d+)/history/add$', views.ads_history_add, name="ads_history_add"),
)
both form templates inherits from this template:
<form role="form" method="post" action=".">
{% csrf_token %}
<table class="table table-bordered crm-form">
{% for field in form.visible_fields %}
<tr>
<th>
{{ field.label }}
</th>
<td>
{{ field }}
<small>{{ field.help_text }}</small>
{% if field.errors %}
<div class="alert alert-danger" role="alert">{{ field.errors }}</div>
{% endif %}
</td>
</tr>
{% endfor %}
</table>
<button type="submit" name="submit" class="btn btn-success crm-float-right">
{% trans 'Save' %}
</button>
</form>
The POST request never reaches your ads_history_add view because your ads_history_add URL pattern does not have a trailing slash. Without the trailing slash, action="." in the ads_form_add.html template results in a POST to (?P<ad_id>\d+)/history/
Add the trailing slash and everything should work as expected. Alternatively, you could omit the action attribute to tell the browser to POST to the current URL.
Also note that, although not relevant here, it is probably a good habit to display {{ form.non_field_errors }}.

Categories