Django not committing form to database - python

The use case is that a logged in use, can call up their profile into a form, edit it and it gets updated in the database.
With the code below the correct Profile data can be viewed. It can also be called up into an editable form. The form allows the data to be edited , but when it is submitted, the database is NOT updated and the original profile is displayed.
I’ve tried everything, including console print statements so I know that it is getting to the POST portion of the code, is a valid form and doing the initial save().
Any insights would be appreciated (I am using Django 1.11). I do not want to start a rabbit running but the only thing I have not tried is breakink the OneToOne relationship with User and using a foriegnkey because I want the profile entry creaed when the user registers.
Notes:
When I popped this in for testing purposes: save_data.user = request.user
I get the error: Exception Value:'User' object has no attribute 'cleaned_data'`from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=100, default='')
city = models.CharField(max_length=100, default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
balance = models.FloatField(default=0)
bank = models.FloatField(default=0)
image = models.ImageField(upload_to='profile_image', blank=True)
def __str__(self):
return self.user.username
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
Forms.py
from django import forms
from django.contrib.auth.models import User
from .models import UserProfile
class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('description', 'city', 'phone', 'balance', 'bank', 'website', 'image')
Views.py
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.contrib.auth import login, authenticate, update_session_auth_hash
from django.contrib.auth.forms import (
UserCreationForm,
UserChangeForm,
PasswordChangeForm
)
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from core.forms import ( EditAccountForm, SignUpForm,
ProfileForm
)
from core.models import UserProfile
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
def edit_profile(request):
if request.method == 'POST':
form = ProfileForm(request.POST, instance=request.user)
if form.is_valid():
save_data = form.save()
save_data.user = request.user
print(save_data)
save_data.save()
return redirect(reverse('core:profile'))
else:
udata = UserProfile.objects.get(user=request.user)
form = ProfileForm(instance=udata)
args = {'form': form}
return render(request, 'core/test.html', args)
urls.py
from django.conf.urls import url
from django.contrib import admin
#from playme.core import views as core_views
from core import views as core_views
from django.contrib.auth import views as auth_views
# SET THE NAMESPACE!
app_name = 'core'
urlpatterns = [
url(r'^$', core_views.index, name='index'),
url(r'signup/$', core_views.signup, name='signup'),
url(r'^account/$', core_views.account, name='account'),
url(r'^profile/$', core_views.view_profile, name='profile'),
url(r'^login/$', auth_views.login, {'template_name': 'core/login.html'}, name='user_login'),
url(r'^logout/$', auth_views.logout, {'next_page': '/play/'}, name='logout'),
url(r'^edit_account/$', core_views.edit_account, name='edit_account'),
url(r'^edit_profile/$', core_views.edit_profile, name='edit_profile'),
url(r'^change_password/$', core_views.change_password, name='change_password'),
]
The URL I am hitting is:
http://127.0.0.1:8000/play/profile/
Which then goes to :
http://127.0.0.1:8000/play/edit_profile/
The form loads up but when submitted goes back to:
http://127.0.0.1:8000/play/profile/
With no database update.

I'm surprised this doesn't give an error.
When you instantiate the form on a GET, you correctly pass the UserProfile object as the instance parameter - this is correct because the form has that as its model. But when you instantiate on POST, you incorrectly pass the User object - request.user. You should pass the profile, as you do in the other branch.
Note, in both cases you can get the profile more simply by just doing request.user.userprofile.

Well the form being invalid situation isn't being handled here at all. Your code should look like this
def edit_profile(request):
if request.method == 'POST':
form = ProfileForm(request.POST, instance=request.user)
if form.is_valid():
save_data = form.save(commit=False)
save_data.user = request.user
save_data.save()
return redirect(reverse('core:profile'))
else:
udata = UserProfile.objects.get(user=request.user)
form = ProfileForm(instance=udata)
args = {'form': form}
return render(request, 'core/test.html', args)
Note the change in indentation.

Related

How can I save a django form

So I want to save a Biographie for each new created User. The user can enter his Bio and it will the it to his Profile.
For this I created a model with OneToOneField
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, null=True, blank=True)
bio = models.CharField(max_length=30)
To create the form I did the following in forms.py:
class BioForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('bio',)
Then I created in the views.py the saving, so the bio will be saved to the specific user:
from .forms import LoginForm, RegisterForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth import get_user_model
def test_view(request):
form = BioForm(request.POST)
user = get_user_model
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.phone_number = request.phone_number
profile.save()
return render(request, 'test.html', {'form': form})
There is something big wrong in the views.py but I don't get it.
I can submit the form and the form will be saved (sometimes) but without the user who wrote it + I get this error:
ValueError at /test/
Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000253B7140D00>>": "Profile.user" must be a "User" instance
Try to assign the user id instead
from .forms import LoginForm, RegisterForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth import get_user_model
def test_view(request):
form = BioForm(request.POST)
user = get_user_model
if form.is_valid():
profile = form.save(commit=False)
profile.user_id = request.user.id
profile.phone_number = request.phone_number
profile.save()
return render(request, 'test.html', {'form': form})
Your problem is that the user you try to save with, is not an authenticated user that exists in the database. Only authenticated (logged in) users exist in the database and can be used in a relational field

Django associate form values to user

I'm very new to Django but I started to create a project and I need some help. My question is very basic but I can't find the right answer.
I made a questionnaire that works fine but I don't know how to do that if a logged in user adds his answers Django associate the answers to the user.
Views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.template import loader
from .models import Stressz_teszt
from .forms import StresszForm
from django.forms import ModelForm
def stressz_item(request):
form = StresszForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('stressz/login.html')
return render(request, 'stressz/stressz-form.html', {'form':form})
Urls.py
from . import views
from django.urls import path
from django.forms import ModelForm
urlpatterns = [
path('', views.index, name='index'),
path('login/', views.login, name='login'),
#stressz teszt form
path('add', views.stressz_item, name='stressz_item'),
path('<int:item_id>/', views.detail, name='detail'),
Forms.py
from django import forms
from django.forms import ModelForm
from .models import Stressz_teszt
class StresszForm(forms.ModelForm):
class Meta:
model = Stressz_teszt
fields = ['stressz_v01', 'stressz_v02', 'stressz_v03', 'stressz_v04', 'stressz_v05',] ...
Models.py
from django.db import models
from django.contrib.auth.models import User
class Stressz_teszt(models.Model):
def __str__(self):
return self.stressz_name
user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
stressz_name = models.CharField(max_length=200)
stressz_company = models.CharField(max_length=300)
stressz_v01 = models.IntegerField()
stressz_v02 = models.IntegerField()
stressz_v03 = models.IntegerField()
stressz_v04 = models.IntegerField()
stressz_v05 = models.IntegerField()
...
Thank you in advance!
You can do it like this :
def stressz_item(request):
if form.is_valid():
stressz_teszt = form.save(commit=False)
stressz_teszt.user_name = request.user
stressz_teszt.save()
return redirect('stressz/login.html')
return render(request, 'stressz/stressz-form.html', {'form': form})

django user creation using UserCreationForm issue

As per youtube tutorial the user is created with exactly same method but mine doesn't work. Why?
views.py
from django.shortcuts import render,redirect
from .forms import CreateUserForm
def registerView(request):
form=CreateUserForm()
if request.method=="POST":
form=CreateUserForm(request.POST)
if form.is_valid():
form.save()
user=form.cleaned_data.get('username')
messages.success(request,'Account was successfully created for '+ user)
return redirect('login')
context={'form':form}
return render(request,"accounts/register.html", context)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2']
Why is a user not created?

'register' object has no attribute 'get' in Django

Hi Everyone i make a blog with django but i need to register use and always i get this error:
AttributeError at /register/
'register' object has no attribute 'get'
i already search too many times but i don't get correct answer so make sure don't mark as a duplicate
Here is my Views.py
from django.shortcuts import render , get_object_or_404,redirect
from django.utils import timezone
from blog.models import *
from blog.forms import *
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.\
def user_register(request):
if request.method == "POST":
reg = register(data=request.POST)
if reg.is_valid():
user = reg.save()
user.set_password(user.password)
user.save()
else:
print(register.errors)
else:
reg = register()
return render(request,'register.html',{'reg':reg})
Here is my Models.py
class register(models.Model):
user = models.OneToOneField(User,on_delete="Cascade")
Here is my Forms.py
class register(forms.ModelForm):
class Meta():
model = User
fields = ('username','email','password')
I'm Wating For Your Answers!
Providing yoururls.py file would be helpful, but for the time being I'm going to assume it looks something like this:
urls.py
urlpatterns = [
path('register/', views.user_register, name='register'),
]
Either way, the issue is that your user_register function does not know how to handle GET requests (i.e. when you visit the URL which calls this function). You should define logic within user_register to handle a GET request. Something like this:
def user_register(request):
if request.method == "POST":
reg = register(data=request.POST)
if reg.is_valid():
user = reg.save()
user.set_password(user.password)
user.save()
else:
print(register.errors)
>if request.method=='GET':
> # do something
return render(request,'register.html',{'reg':reg})

How do I make a function in django to add comments to my reviews

I have a website made on Django and the users able to leave a review and Ive tried to make it so they can add comments, however they add a comment it just saves it to the database rather then adding it to the post. If anyone knows how I could change my code so that it instead adds the comments to the review that they message on rather then them not appearing on the website at all.
views.py:
from django.shortcuts import render, redirect #Render is used to show the HTML, and redirect is used when the user needs to be sent to a different page automatically.
from .models import Review #This imports the Review database.
from .forms import ReviewForm, CommentForm #This imports the comments and review form.
from django.utils import timezone
from django.contrib.auth.decorators import login_required #This requires the user to be logged in.
def review(request):
return render(request, 'review/review.html')
#login_required(login_url='/accounts/login/')
def review_new(request):
if request.method == "POST":
form = ReviewForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.date = timezone.now()
post.author = request.user
post.save()
return redirect('/review')
else:
form=ReviewForm()
return render(request, 'review/post_edit.html', {'form': form})
def add_comment_to_post(request):
if request.method == "POST":
form = CommentForm(request.POST)
comment = form.save(commit=False)
comment.Review = review
comment.save() #This will save the comment to the database.
return redirect('reivew': review)
else:
form = CommentForm()
return render(request, 'review/add_comment_to_post.html', {'form': form})
models.py:
from django.db import models
from django.conf import settings
from django.utils import timezone
class Review(models.Model):
title = models.CharField(max_length=140)
body = models.TextField(max_length=3000)
date = models.DateTimeField()
author=models.ForeignKey(settings.AUTH_USER_MODEL, `on_delete=models.CASCADE, null=True)`
class comment(models.Model):
review = models.ForeignKey('review.Review', on_delete=models.CASCADE, related_name='comments', null=True)
author=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
text = models.TextField(max_length=3000)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.text
urls.py:
from django.urls import path, include, re_path
from django.views.generic import ListView, DetailView
from review.models import Review
from . import views
urlpatterns = [
path('', ListView.as_view(
queryset=Review.objects.all().order_by("-date")[:25],
template_name="review/review.html")),
re_path('(?P<pk>(\d+))',DetailView.as_view(model=Review, template_name="review/post.html")),
path('new/', views.review_new, name='review_new'),
path('new/comment', views.add_comment_to_post, name='add_comment_to_post'),
]
I can see that you should change comment.Review = review to something like comment.review = Review.objects.get(id=review_id) where review_id is an id passed from the form. Also notice that your Comment model allows the review to be null, which means currently you are adding comments without linking them correctly to the original post/review they should be related to.

Categories

Resources