i'm facing some ValueError home.views.signup in my django program - django-views

I am trying to create a registration form and store values in database, And i am able to store data in database successfully but i am getting error like this.
please someone tell me what i have done wrong in my code.
Error :
ValueError at /signup
The view home.views.signup didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL: http://127.0.0.1:8000/signup
Django Version: 4.0
Exception Type: ValueError
Exception Value: The view home.views.signup didn't return an HttpResponse object. It returned None instead.
Code:
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from home.models import Public
from datetime import datetime
# Create your views here.
def signup(request):
if request.method == "POST":
name = request.POST.get("name")
email = request.POST.get("email")
pass1 = request.POST.get("password1")
pass2 = request.POST.get("password2")
user = Public(name= name, email= email, password= pass1, date= datetime.today())
if pass1 == pass2:
user.save()
else:
dictionary = {"error": "Password and Confirm password is not match"}
return render(request, 'signup.html', dictionary)
else:
return render(request, 'signup.html')

Related

KeyError in city name

I have made an small weather web app in django & it is working properly but
when a wrong city name is entered it start showing KeyError page.
from django.shortcuts import render, redirect
from django.contrib import messages
import requests
#search page
def search(request):
return render(request, 'index.html')
#forecast result page
def forecast(request):
c = request.POST['city']
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=7fee53226a6fbc936e0308a3f4941aaa&units=metric'.format(c)
r = requests.get(url)
data = r.json()
weather = {
'description': data['weather'][0]['description'],
'icon': data['weather'][0]['icon'],
'city': c.title(),
'temperature': data['main']['temp']
}
print(r)
return render(request, 'weather.html', {'weather': weather})
On entering wrong city name it is giving KeyError,So I want that instead of giving KeyError django will redirect it to my homepage i.e index.html with an error message below it.
The API will tell you if the city name is not valid.
r = requests.get(url)
if r.status_code == 404:
messages.add_message('City not found')
return redirect('home')
data = r.json()
...
First of all, please do not construct the querysetring yourself: querystrings can not include a lot of characters. You can use Django's QueryDict for that, like:
from django.http import QueryDict
qd = QueryDict(mutable=True)
qd.update(q=c, appid='7fee53226a6fbc936e0308a3f4941aaa', units='metric')
url = 'http://api.openweathermap.org/data/2.5/weather?{}'.format(qd.urlencode())
For cities like 'New York', it will encode this as:
>>> qd.urlencode()
'q=New+York&appid=7fee53226a6fbc936e0308a3f4941aaa&units=metric'
so it replaces the space with a +.
Furthermore you can use try-except here to redirect to a different page, like:
from django.http import QueryDict
from django.shortcuts import redirect
def forecast(request):
try:
city = request.POST['city']
except:
return redirect('name-of-some-view')
qd = QueryDict(mutable=True)
qd.update(q=city, appid='7fee53226a6fbc936e0308a3f4941aaa', units='metric')
url = 'http://api.openweathermap.org/data/2.5/weather?{}'.format(qd.urlencode())
try:
data = r.json()
weather = {
'description': data['weather'][0]['description'],
'icon': data['weather'][0]['icon'],
'city': c.title(),
'temperature': data['main']['temp']
}
except KeyError:
return redirect('name-of-some-view')
return render(request, 'weather.html', {'weather': weather})
You can use the Django Messages Framework [Django-doc] to show messages to a user.

'QueryDict' object has no attribute 'GET'

I have request like this
Request URL: http://A.B.C.18:8010/pbx/directory/?hostname=msk-m9-sip232.db.ru&section=directory&tag_name=domain&key_name=name&key_value=test1.db.ru&Event-Name=REQUEST_PARAMS&Core-UUID=96bec236-d834-4c19-971d-d9a5c7aafd58&FreeSWITCH-Hostname=msk-m9-sip232.db.ru&FreeSWITCH-Switchname=msk-m9-sip232.db.ru&FreeSWITCH-IPv4=A.B.C.232&FreeSWITCH-IPv6=%3A%3A1&Event-Date-Local=2014-12-30%2001%3A35%3A09&Event-Date-GMT=Mon,%2029%20Dec%202014%2021%3A35%3A09%20GMT&Event-Date-Timestamp=1419888909111423&Event-Calling-File=sofia_reg.c&Event-Calling-Function=sofia_reg_parse_auth&Event-Calling-Line-Number=2481&Event-Sequence=3594&action=sip_auth&sip_profile=internal&sip_user_agent=Bria%204%204.1%2073903-085cc850-M&sip_auth_username=10001&sip_auth_realm=test1.db.ru&sip_auth_nonce=a7a0ed08-8839-4925-83e9-665bdb0ad7fe&sip_auth_uri=sip%3Atest1.db.ru&sip_contact_user=10001&sip_contact_host=X.Z.A.137&sip_to_user=10001&sip_to_host=test1.db.ru&sip_via_protocol=udp&sip_from_user=10001&sip_from_host=test1.db.ru&sip_call_id=MWRjMTAyZjdiMTQ4OGZmMTIyOWRiMjc1NzI2M2MxNDY&sip_request_host=test1.db.ru&sip_auth_qop=auth&sip_auth_cnonce=dc542a5c5e9d34f7ed48a58bb6f3a9c3&sip_auth_nc=00000001&sip_auth_response=3419868ab9af9e4e5585cbaabba08f0b&sip_auth_method=REGISTER&key=id&user=10001&domain=test1.db.ru&ip=X.Z.A.137
and see this error
Exception Value:
'QueryDict' object has no attribute 'GET'
on
data = request.GET
If I change request to
Request URL: http://A.B.C.18:8010/pbx/directory/?hostname=msk-m9-sip232.db.ru&section=directory&tag_name=domain&key_name=name&key_value=test1.db.ru&Event-Name=REQUEST_PARAMS&Core-UUID=96bec236-d834-4c19-971d-d9a5c7aafd58&FreeSWITCH-Hostname=msk-m9-sip232.db.ru&FreeSWITCH-Switchname=msk-m9-sip232.db.ru&FreeSWITCH-IPv4=A.B.C.232&FreeSWITCH-IPv6=%3A%3A1&Event-Date-Local=2014-12-30%2001%3A35%3A09&Event-Date-GMT=Mon,%2029%20Dec%202014%2021%3A35%3A09%20GMT&Event-Date-Timestamp=1419888909111423&Event-Calling-File=sofia_reg.c&Event-Calling-Function=sofia_reg_parse_auth&Event-Calling-Line-Number=2481&Event-Sequence=3594&action1=sip_auth&sip_profile=internal&sip_user_agent=Bria%204%204.1%2073903-085cc850-M&sip_auth_username=10001&sip_auth_realm=test1.db.ru&sip_auth_nonce=a7a0ed08-8839-4925-83e9-665bdb0ad7fe&sip_auth_uri=sip%3Atest1.db.ru&sip_contact_user=10001&sip_contact_host=X.Z.A.137&sip_to_user=10001&sip_to_host=test1.db.ru&sip_via_protocol=udp&sip_from_user=10001&sip_from_host=test1.db.ru&sip_call_id=MWRjMTAyZjdiMTQ4OGZmMTIyOWRiMjc1NzI2M2MxNDY&sip_request_host=test1.db.ru&sip_auth_qop=auth&sip_auth_cnonce=dc542a5c5e9d34f7ed48a58bb6f3a9c3&sip_auth_nc=00000001&sip_auth_response=3419868ab9af9e4e5585cbaabba08f0b&sip_auth_method=REGISTER&key=id&user=10001&domain=test1.db.ru&ip=X.Z.A.137
all is fine!
I change only one parameter
action to action1
urls.py
from django.conf.urls import patterns, url
from face import views as fv
from pbx import views as pv
urlpatterns = patterns('',
url(r'directory/$', pv.get_user_info,),
)
views.py
from django.shortcuts import render
from django.db.models import Q
from face import models as fm
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response, get_object_or_404
from django.http import Http404
from django.http import HttpResponse
import json, datetime
from django.utils.html import escape
...
def get_all_domains(location):
location = get_object_or_404(fm.PBXServerLocation, name=location)
domains = fm.PBXDomain.objects.filter(location=location).filter(Q(status=1) | Q(status=2))
return render_to_response('section_directory.xml', {'domains': domains})
def get_user_info(data):
location = get_object_or_404(fm.PBXServerLocation, name=data.get('hostname', default=None))
domains = fm.PBXDomain.objects.filter(location=location).filter(Q(status=1) | Q(status=2))
domain = data.get('domain', default=None)
if domain is not None and domain in domains:
domain = get_object_or_404(fm.PBXDomain, name=domain)
user = fm.PBXUser.objects.filter(user_id=data.get('user', default=None), pbx_domain=domain)
return render_to_response('section_directory_user.xml', {'user': user})
else:
raise Http404
#csrf_exempt
def get_user_info(request):
if request.method == "GET":
data = request.GET
else:
data = request.POST
# list_users
if data.get('section', default=None) == "directory" and \
data.get('tag_name', default=None) == "" and \
data.get('key_name', default=None) == "" and \
data.get('key_value', default=None) == "":
return get_all_domains(data.get('hostname', default=None))
# user register from endpoint
elif data.get('section', default=None) == "directory" and \
data.get('action', default=None) == "sip_auth":
get_user_info(data)
else:
domain = get_object_or_404(fm.PBXDomain, name=data.get('domain'))
user = get_object_or_404(fm.PBXUser, user_id=data.get('user'), pbx_domain=domain)
return render_to_response('user.xml', {'user': user, 'data': data})
Error:
AttributeError at /pbx/directory/
'QueryDict' object has no attribute 'method'
./pbx/views.py in get_user_info
if request.method == "GET":
UPDATE2:
I reduced the request
AttributeError at /pbx/directory/
'QueryDict' object has no attribute 'method'
Request Method: GET
Request URL: http://37.18.2.18:8010/pbx/directory/?section=directory&action=sip_auth
Django Version: 1.7.1
Exception Type: AttributeError
Exception Value:
'QueryDict' object has no attribute 'method'
Exception Location: ./pbx/views.py in get_user_info, line 47
Python Executable: /usr/local/bin/uwsgi
You have two functions called get_user_info. The second one, which is a view, overwrites the first.
So when your view attempts to call the function, what it actually calls is itself.
Rename the standalone fiction to something else.

Django Error :: Exception Type:IntegrityError Exception Value: column user_id is not unique

I dont understand what I am doing wrong!! I am getting this error everytime i click on submit. This is a simple registration form
Request Method: POST
Request URL: http://127.0.0.1:8000/register/
Django Version: 1.5.1
Exception Type: IntegrityError
Exception Value:
column user_id is not unique
Exception Location: /home/xxxx/Desktop/forfte/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 362
Python Executable: /home/xxx/Desktop/forfte/bin/python
Python Version: 2.7.3
My Models::
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
class Vendor(models.Model):
user= models.OneToOneField(User)
def __unicode__ (self):
return self.user
def create_vendor_user_callback(sender, instance, **kwargs):
vreg, new=Vendor.objects.get_or_create(user=instance)
post_save.connect(create_vendor_user_callback,User, )
View::
# Create your views here.
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template import RequestContext
from vreg.forms import RegistrationForm
from vreg.models import Vendor
from django.contrib.auth import authenticate
def VendorRegistration(request):
if request.user.is_authenticated():
return HttpRequestRedirect('/profile/')
if request.method=='POST':
form= RegistrationForm(request.POST)
if form.is_valid():
print "i am in"
print type(form.cleaned_data['emailadd'])
print type(form.cleaned_data['username'])
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))
Would be really nice if I could get some Help!! Thanks in advance
Your form processing method creates a User and a matching Vendor. But you also have a post-save signal on User that creates a Vendor for that user. That means you end up trying to create two vendors, whereas a OneToOne field implies a unique relationship of one vendor per user.
Either get rid of the signal, or take the Vendor creation code out of the form processing view.

Django request.user.is_authenticated() not working when sending form data

i've a probelem with the request.user.is_authenticated()
this the view.
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template import RequestContext
from forms import RegistrationForm
def ContributorRegistration(request):
if request.user.is_authenticated():
'''if user is logged in -> show profile'''
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
'''if post, check the data'''
form = ContributorRegistration(request.POST)
if form.is_valid():
''' if form is valid, save the data'''
user = User.objects.create_user(username=form.cleaned_data['username'],email = form.cleaned_data['email'], password= form.cleaned_data['password'])
user.save()
contributor = user.get_profile()
contributor.location = form.cleaned_data['location']
contributor.save()
return HttpResponseRedirect('profile.html')
else:
'''form not valid-> errors'''
return render_to_response('register.html',{'form':form},context_instance=RequestContext(request))
else:
'''method is not a post and user is not logged, show the registration form'''
form = RegistrationForm()
context={'form':form}
return render_to_response('register.html',context,context_instance=RequestContext(request))
basically,
if the user is logged in then the profile.html is shown: OK
if the user is not logged in and he's not posting data then the form is shown: OK
when i submit the data from the form i receive back this error:
Request Method: POST
Request URL: http://localhost:8000/register/
Django Version: 1.4.1
Exception Type: AttributeError
Exception Value:
'QueryDict' object has no attribute 'user'
Exception Location: /Users/me/sw/DjangoProjects/earth/views.py in ContributorRegistration, line 9
where line 9 is if request.user.is_authenticated():
so seems that the request does not have the user object when submitting the form data.
how can i solve?
Thanks
You're filling your own view function with the request.POST data as if it was the form.
if request.method == 'POST':
'''if post, check the data'''
form = ContributorRegistration(request.POST)
if form.is_valid():
Should be
if request.method == 'POST':
'''if post, check the data'''
form = RegistrationForm(request.POST)
if form.is_valid():
In order to have access to request.user object, you need to have the User authentication middleware installed in your application. To do this (extremely easy), do the following:
Go to your settings.py and add 'django.contrib.auth' and 'django.contrib.contenttypes' to the INSTALLED_APPS tupple.
You are very likely to require a syncdb command for it to be fully installed (you need some database tables for user authentication).
python manage.py syncdb
And that should make it work.
Is it just me or is the name of your form the same as your view function ContributorRegistration?
Perhaps you've made a typo.

Django URL View parameter help

I'm having some trouble trying to pass a string from a URL to the views. My page has user pages, and if you go to site.com/username it brings up that users page. But when I try going it says this: [invalid literal for int() with base 10: 'username'].
Here's my code:
urls.py:
(r'^user/(?P<userName>[^/]+)/$', 'mischief_blog.mischief_app.views.user_view'),
views.py:
def user_view(request, userName):
postList = userPost.objects.filter(author=userName)
return render_to_response('user.html', {"user": user_name, "postList": postList}, context_instance=RequestContext(request))
get name from url:
(r'^user/(?P<userName>\w+)/$', 'mischief_blog.mischief_app.views.user_view'),
get user from name, then get posts from user: (get_object_or_404) and (User)
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
def user_view(request, userName=None):
user = get_object_or_404(User, username=userName)
postList = userPost.objects.filter(author=user)
return render_to_response('user.html', {"user": user, "postList": postList}, context_instance=RequestContext(request))