save() got an unexpected keyword argument 'force_insert' - django

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, f'Your account has been created. Log In to continue.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
This is the code when I run it I get an error. But that error shouldn't be there since I am not overriding the the save() method. please help.

try to get each form input one by one and then save the form. for example:
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
data = YourModelName()
data.input1 = form.cleaned_data['input1']
data.input2 = form.cleaned_data['input2']
# ...
form.save()
messages.success(request, 'Your account created. You can now Login.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})

I have a feeling that you are doing Corey Schafer's Django tutorial. If so, other users have had the same problem, which is discussed here:
Django - TypeError - save() got an unexpected keyword argument 'force_insert'
The issue lies in overriding the save method in your Profile model

Related

Django error with views for form display and save

I have a vĂ­ews to display and save a form as below:
#login_required(login_url='/login') # Check login
def addlisting(request):
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ProductForm()
return render(request, 'listing/addlisting.html', {
'form': form
})
But When I load the html file I got this error
ValueError at /addlisting
The view listing.views.addlisting didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/addlisting
Django Version: 3.2.3
Exception Type: ValueError
Exception Value:
The view listing.views.addlisting didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\Daisy\OneDrive\Documents\Work\django\shecodes\bookapp\env\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable: C:\Users\Daisy\OneDrive\Documents\Work\django\shecodes\bookapp\env\Scripts\python.exe
Python Version: 3.8.2
Python Path:
['C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\bookapp',
'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env\\Scripts\\python38.zip',
'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38\\DLLs',
'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38\\lib',
'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38',
'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env',
'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env\\lib\\site-packages']
Server time: Sun, 30 Jan 2022 07:41:40 +0000
Please take a look.
Thanks in advance !!!!!!!!!!!!!!!!!!!!
Are you sure you are using POST method?
Please try it out:
#login_required(login_url='/login') # Check login
def addlisting(request):
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ProductForm()
return render(request, 'listing/addlisting.html', {'form': form})
return redirect('home')
NOTE: Just trying to get with the error. please just check it out that you are redirected to home. if you get to the home that means you are not using the POST method as well.
Yep that is the error: Request Method: GET
you are using GET. please send the request using POST method.
Good idea to use:
from django.views.decorators.http import require_http_methods
#require_http_methods(["POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
pass
please read more about using decoratos to allow the method you want on your function: https://docs.djangoproject.com/en/4.0/topics/http/decorators/
this may help you:
from django.views.decorators.http import require_http_methods
#require_http_methods(["POST"])
#login_required(login_url='/login') # Check login
def addlisting(request):
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
form = ProductForm()
return render(request, 'listing/addlisting.html', {'form': form})
There is not else part in your views.py so while rendering page GET request is called and because of that it throws didn't return an HttpResponse object. So add else part and render your ProductForm as
#login_required(login_url='/login') # Check login
def addlisting(request):
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ProductForm()
return render(request, 'listing/addlisting.html', {'form': form})
else: #<------------ add else part here which will `render` your form
form = ProductForm()
return render(request, 'listing/addlisting.html', {'form': form})

Can we use instance in the form?

hello guys i am working on form i didint find how to get instance in the form. This is not a model form
def form(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
else:
form = Form()
return render(request, 'app/form.html', {'form': form})
You should have a form class something like below:
forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Now To handle the form we need to instantiate it in the view for the URL where we want it to be published:
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
# process the data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Refer the Django documentation for more details.
https://docs.djangoproject.com/en/3.0/topics/forms/

Django link two apps

im currently facing the problem that i want to call a view from another app (accounts app which holds the user model) within my main app (a blog app).
this is the error i get:
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
urls.py
...
from quickblog import views as core_views
from accounts import views as views_accounts
...
url(r'^myaccount/$', views_accounts.view_profile, name='myaccount'),
views.py (accounts app):
from django.shortcuts import render, redirect
from django.urls import reverse
from accounts.forms import (
RegistrationForm,
EditProfileForm
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('accounts:home'))
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'reg_form.html', args)
def view_profile(request, pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user
args = {'user': user}
return render(request, 'profile.html', args)
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect(reverse('accounts:view_profile'))
else:
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'edit_profile.html', args)
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect(reverse('accounts:view_profile'))
else:
return redirect(reverse('accounts:change_password'))
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'change_password.html', args)
This is my first django app, is there maybe anything i need to know about linking two apps within one project?
thanks

confirmation form step2.html Django

What is the best way to show confirmation on step2.html in Django?
forms.py:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea())
views.py:
from django.views.generic import FormView
from .forms import ContactForm
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import HttpResponseRedirect
def step1(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
#save and cleared_form
return HttpResponseRedirect('/step2/')
else:
form = ContactForm()
return render(request, 'step1.html', {'form': form})
def step2(request):
ctx = { 'Test_1': 'email#email.com'}
return render(request, 'step2.html', ctx)
step2.html:
{{Test_1}}
On step 2 I want to show fields submitted on step 1, how to achieve that?
Good solution will be to show step2.html in step1 view when valid form is submitted, instead of redirecting user to step2. That way you will have access to your form data in view and template.
When submitting confirmation, values from step 1 can be passed by hidden fields or saved into session storage.
Example:
def step1(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
ctx = {'contact_data': form.cleaned_data}
return render(request, 'step2.html', ctx)
else:
form = ContactForm()
return render(request, 'step1.html', {'form': form})
You can save whole form data (cleaned_data) into session storage before redirection in step 1. That way you will be able to retrieve that data in step 2. Example:
def step1(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
#save and cleared_form
request.session.contact_form = form.cleaned_data
return HttpResponseRedirect('/step2/')
else:
form = ContactForm()
return render(request, 'step1.html', {'form': form})
def step2(request):
contact_data = request.session.get('contact_form', None)
if contact_data is None:
return HttpResponseRedirect('/step1/')
# someone is entering step 2 directly, without submitted form in step 1, we should redirect him back to step 1.
ctx = {'contact_data': contact_data}
return render(request, 'step2.html', ctx)
Consider using Form wizard. It will handle for you passing submitted data between steps (using cookies or session). All you need to do is: create 2 views, one with proper form, one with just some confirmation button and in template for step 2 retrieve all data from step 1.

Django Error:: global name 'HttpRequestRedirect' is not defined

I am getting this error, I tried working on it a lot but cannot understand whats wrong.
I am basically trying to make a signup registration that has a couple of forms to be filled
Request Method: GET
Request URL: http://127.0.0.1:8000/gi/
Django Version: 1.5.1
Exception Type: NameError
Exception Value:
global name 'HttpRequestRedirect' is not defined
Exception Location: /home/xx/Desktop/GoAmma/vendorAmmma/vreg/views.py in GIRegistration, line 42
Python Executable: /home/xx/Desktop/forfte/bin/python
Python Version: 2.7.3
The view is as shown below:
# Create your views here.
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from vreg.forms import RegistrationForm, LoginForm
from vreg.models import Vendor
from django.contrib.auth import authenticate, login, logout
def VendorRegistration(request):
if request.user.is_authenticated():
return HttpRequestRedirect('/profile/')
if request.method=='POST':
form= RegistrationForm(request.POST)
if form.is_valid():
user=User.objects.create_user(username=form.cleaned_data['username'], email= form.cleaned_data['emailadd'], password= form.cleaned_data['password'])
user.save()
vreg=Vendor(user=user)
vreg.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html', {'form':form}, context_instance=RequestContext(request))
else:
''' user is not submitting form show them blank registration form'''
form= RegistrationForm()
context={'form':form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
#login_required
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
vreg= request.user.get_profile
context={'vreg':vreg}
return render_to_response('profile.html',context,context_instance=RequestContext(request))
#login_required
def GIRegistration(request):
if request.user.is_authenticated():
return HttpRequestRedirect('/profile/')
if request.method=='POST':
form= GIForm(request.POST)
if form.is_valid():
contact = form.save()
contact.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('generalinfo.html', {'form':form}, context_instance=RequestContext(request))
else:
''' user is not submitting form show them blank registration form'''
form= GIForm()
context={'form':form}
return render_to_response('generalinfo.html', context, context_instance=RequestContext(request))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method=='POST':
form=LoginForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
password=form.cleaned_data['password']
vreg= authenticate(username=username,password=password)
if vreg is not None:
login(request,vreg)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('login.html',{'form':form}, context_instance= RequestContext(request))
else:
return render_to_response('login.html',{'form':form}, context_instance= RequestContext(request))
else:
'''user not submitting form show the login form'''
form= LoginForm()
context={'form': form}
return render_to_response('login.html',context,context_instance= RequestContext(request))
def LogoutRequest(request):
logout(request)
return HttpResponseRedirect('/')
Its HttpResponseRedirect not HttpRequestRedirect.
Change this return HttpRequestRedirect('/profile/') to return HttpResponseRedirect('/profile/')
P.S. Never use hardcoded urls in your code, use Reverse Resolution of URLs