I am simply trying to map a view to a path in urls.py, but when I try to it throws this error:
Registration didn't return an HttpResponse object
urls.py
urlpatterns = patterns('',
(r'^Register/$', Registration),
(r'^Newuser/$', ProcessRegistration),
)
views.py
def Registration(request):
RegForm = RegistrationForm(request.POST or None)
if request.method == 'POST':
if RegForm.is_valid():
clearUserName = RegForm.cleaned_data['userNm']
clearPass = RegForm.cleaned_data['userPass']
RegForm.save()
try:
return HttpResponseRedirect('/Newuser/?userNm=' + clearUserName)
except:
raise ValidationError(('Invalid request'), code='300') ## [ TODO ]: add a custom error page here.
else:
RegForm = RegistrationForm()
return render(request, 'VA/reuse/register.html', {
'RegForm': RegForm
})
def ProcessRegistration(request):
clearUserName = request.GET.get('userNm')
return HttpResponse("Wee")
When I visit /Register, it throws the above error.
Any idea why its not working? It is returning a response of Wee
the validators=[] for userNm was messing it up within my models.py . I was up doing:
class Client(models.Model):
userNm = models.EmailField(verbose_name="Email",max_length=50,unique=True,validators=[RegexValidator('^\w{6,50}$','format: invalid username','Invalid Entry')])
userPass = models.CharField(verbose_name="Password", max_length=50)
I changed the userNm declaration to:
userNm = models.EmailField(verbose_name="Email",max_length=50,unique=True)
Related
here is my code views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from quiz.forms import NewQuizForm, NewQuestionForm
from quiz.models import Answer, Question, Quizzes, Attempter, Attempt
from courses.models import Module
from completion.models import Completion
# Create your views here.
def NewQuiz(request, course_id, module_id):
user = request.user
module = get_object_or_404(Module, id=module_id)
if request.method == 'POST':
form = NewQuizForm(request.POST)
if form.is_valid():
title = form.cleaned_data.get('title')
description = form.cleaned_data.get('description')
due = form.cleaned_data.get('due')
allowed_attempts = form.cleaned_data.get('allowed_attempts')
time_limit_mins = form.cleaned_data.get('time_limit_mins')
quiz = Quizzes.objects.create(user=user, title=title, description=description, due=due, allowed_attempts=allowed_attempts, time_limit_mins=time_limit_mins)
module.quizzes.add(quiz)
module.save()
return redirect('new-question', course_id=course_id, module_id=module_id, quiz_id=quiz.id)
else:
form = NewQuizForm()
context = {
'form': form,
}
return render(request, 'quiz/newquiz.html', context)
def NewQuestion(request, course_id, module_id, quiz_id):
user = request.user
quiz = get_object_or_404(Quizzes, id=quiz_id)
if request.method == 'POST':
form = NewQuestionForm(request.POST)
if form.is_valid():
question_text = form.cleaned_data.get('question_text')
points = form.cleaned_data.get('points')
answer_text = request.POST.getlist('answer_text')
is_correct = request.POST.getlist('is_correct')
question = Question.objects.create(question_text=question_text, user=user, points=points)
for a, c in zip(answer_text, is_correct):
answer = Answer.objects.create(answer_text=a, is_correct=c, user=user)
question.answers.add(answer)
question.save()
quiz.questions.add(question)
quiz.save()
return redirect('new-question', course_id=course_id, module_id=module_id, quiz_id=quiz.id)
else:
form = NewQuestionForm()
context = {
'form': form,
}
return render(request, 'quiz/newquestion.html', context)
def QuizDetail(request, course_id, module_id, quiz_id):
user = request.user
quiz = get_object_or_404(Quizzes, id=quiz_id)
my_attempts = Attempter.objects.filter(quiz=quiz, user=user)
context = {
'quiz': quiz,
'my_attempts': my_attempts,
'course_id': course_id,
'module_id': module_id,
}
return render(request, 'quiz/quizdetail.html', context)
and quiz/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<course_id>/<module_id>/quiz/newquiz', views.NewQuiz, name='new-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/newquestion', views.NewQuestion, name='new-question'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/', views.QuizDetail, name='quiz-detail'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/take', views.TakeQuiz, name='take-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/take/submit', views.SubmitAttempt, name='submit-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/<attempt_id>/results', views.AttemptDetail, name='attempt-detail'),
]
and template
<i class="material-icons"></i>Add new quiz
in the project urls.py
path('quiz/',include('quiz.urls')),
it says like this "Reverse for 'new-quiz' with arguments '(11, '')' not found. 1 pattern(s) tried: ['course/(?P<course_id>[^/]+)/(?P<module_id>[^/]+)/quiz/newquiz$']"which means it detect the first argument but not the others why???
Use single quotes in your template, so 'new-quiz' instead of "new-quiz":
<i class="material-icons"></i>Add new quiz
Uploading a file is only allowed once the form is submitted. The upload url must not be accessible otherwise.
After the user logs in, the upload url is directly accessed. How can i restrict this? This will create multiple entries of file upload for the same form
models.py
class uploadmeta(models.Model):
path = models.ForeignKey(Mdform, verbose_name="ID", on_delete=models.PROTECT)
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
datafile = models.FileField(upload_to=get_upload_folder, verbose_name="Dataset", validators=[validate_file_extension])
def get_absolute_url(self):
return reverse('file_list', kwargs={'pk': self.pk})
views.py
if request.user.is_authenticated:
if request.method == 'POST':
form = uploadmetaform(request.POST, request.FILES)
if form.is_valid():
path = form.cleaned_data['path']
if uploadmeta.objects.filter(path=path).exists():
user = form.cleaned_data['user']
datafile = form.cleaned_data['datafile']
context = {
'path': path,
'user': user,
'datafile': datafile
}
template = loader.get_template('nameexists.html')
return HttpResponse(template.render(context, request))
else:
user = form.cleaned_data['user']
datafile = form.cleaned_data['datafile']
path = dict(form.fields['path'].path)[path]
print(path)
b = form(path=path, user=user, datafile=datafile)
b.save()
context = {
'path': path,
'user': user,
'datafile': datafile
}
template = loader.get_template('thankyou.html')
return HttpResponse(template.render(context, request))
else:
form = uploadmetaform()
return render(request, 'uploaddata.html', {'form': form})
else:
return render(request, 'home.html')```
from django.shortcuts import render
from basicform.forms import BasicForm
from django.template import loader
from django.http import HttpResponse
from basicform.choices import *
from basicform.models import BasicFormModel
def responseform(request):
if request.method == 'POST':
basicForm = BasicForm(request.POST)
if basicForm.is_valid():
name = basicForm.cleaned_data['name']
if BasicFormModel.objects.filter(name=name).exists():
favourite_color = basicForm.cleaned_data['favourite_color']
choices = basicForm.cleaned_data['choices']
context = {
'name': name,
'favourite_color': favourite_color,
'choices': choices
}
template = loader.get_template('nameexists.html')
return HttpResponse(template.render(context, request))
else:
favourite_color = basicForm.cleaned_data['favourite_color']
choices = basicForm.cleaned_data['choices']
print("cleanded choices="+choices)
choices = dict(basicForm.fields['choices'].choices)[choices]
print(choices)
b = BasicFormModel(name=name, favourite_color=favourite_color, choices=choices)
b.save()
context = {
'name': name,
'favourite_color': favourite_color,
'choices': choices
}
template = loader.get_template('thankyou.html')
return HttpResponse(template.render(context, request))
else:
form = BasicForm()
return render(request, 'responseform.html', {'form':form});
I am trying to pass 2 parameters to a view but it gives this type error
i dont know if its a problem with the urls or my redirect
//urls.py
urlpatterns = [
#
url(r'^receive/[a-zA-Z]+/[0-9]+/$', receive_money)
]
//subtract_money view
def subtract_money(request):
if request.user:
users = User.objects.all()
users_ids = users.values_list('id', flat=True)
users_list = []
for id in users_ids:
user = users.get(pk=id)
if user.username != "ravinkohli" and user.username != request.user.username:
users_list.append(user)
if request.POST and request.POST.get('amount'):
username = request.user.username
withdraw = request.POST.get('amount')
wallet = Wallet.objects.get(pk=request.user.userprofile.wallet_id_id)
# if withdraw > wallet.amount:
# return render(request, 'send_money.html', {'error': 'Amount can not be greater than balance','users': users_list})
wallet.subtract_money(withdraw)
wallet.save()
now = datetime.now()
trans = Transaction(from_name=username, wallet_id=wallet,to=request.POST.get('receiver'), date=now, amount=withdraw)
trans.save()
return redirect('/receive/%s/%s/' % (request.POST.get('receiver'), withdraw))
else:
return render(request, 'send_money.html',{'users': users_list})
else:
return HttpResponseRedirect('/login/?next={}'.format('/subtract_money/'))
//receiver view
def receive_money(request, username, amount):
add_amount = amount
wallet = Wallet.objects.get(username=username)
wallet.add_money(add_amount)
wallet.save()
return redirect('user_profile.html', {'user': request.user,'userprofile': Userprofile.objects.get(user=request.user), 'wallet': wallet})
Since you are expecting 2 arguments it should be
url(r'^receive/(?P<username>[a-zA-Z]+)/(?P<amount>[0-9]+)/$', receive_money)
try something with the following url, but I don't think its a good idea to construct a url like this.
urlpatterns = [
#
url(r'^receive/(?P<username>[a-zA-Z]+)/(?P<amount>[0-9]+)/$', receive_money)
]
I made a simple pet store app and just added search box feature and I received this error
ValueError at /pet/search/
The view mysite.pet.views.search_page didn't return an HttpResponse object.
I tried to change render_to_response into HttpResponseRedirect but still got the same error.
Linking back to my search_page function in views.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
I did some research and I understand a view has to return a HttpResponse when a HttpRequest is made and render_to_response is just a shortcut.Can someone help explain why this function won't work.Thank you
You are getting this problem because you havn't written a HttpResponse object if request type is not POST
To overcome this in your view write somthing which will process if request type is not post
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
Hope this will help you thanks
The error is because when the function is called the method type is not POST and it does not find the corresponding HttpResponse object.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
return render_to_response("any.html",{} , context_instance = RequestContext(request))
def addsponser(request):
if request.method == 'POST':
# return HttpResponse(request,'error is here')
if (request.POST.get('firstname') and
request.POST.get('lastname') and
request.POST.get(' email') and
request.POST.get('phone_Number') and
request.POST.get('gender') and
request.POST.get('state') and
request.POST.get('adress') and
request.POST.get('postal_code') and
request.POST.get('town')
):
fname = request.POST.get('firstname')
lname = request.POST.get('lastname')
em = request.POST.get(' email')
phn = request.POST.get('phone_Number')
gnd = request.POST.get('gender')
stt = request.POST.get('state')
add = request.POST.get('adress')
pstc = request.POST.get('postal_code')
twn = request.POST.get('town')
try:
sponser = Sponsers()
sponser.firstname = fname
sponser.lastname = lname
sponser.email = em
sponser.Phone_Number = phn
sponser.gender = gnd
sponser.state = stt
sponser.adress = add
sponser.postal_code = pstc
sponser.town = twn
sponser.save()
messages.success(request, "sponser Added")
return redirect('sponsers')
except Exception:
messages.error(request, "Failed to add sponser")
return redirect('sponsers')
else:
pass
else:
return redirect('sponsers')
I was trying to dynamically generate fields as shown in http://jacobian.org/writing/dynamic-form-generation/. My case slightly differs in that I am looking to use multiplechoicefield that is dynamically created. This is what I came up with...
views.py
def browseget(request):
success = False
if request.method == 'POST':
list_form = ListForm(request.POST)
if list_form.is_valid():
success = True
path = list_form.cleaned_data['path']
minimum_size = list_form.cleaned_data['minimum_size']
follow_link = list_form.cleaned_data['follow_link']
checkboxes = list_form.cleaned_data['checkboxes']
....do something
else:
list_form = ListForm(name_list)
ctx = {'success': success, 'list_form': list_form, 'path': path, 'minimum_size': minimum_size}
return render_to_response('photoget/browseget.html', ctx, context_instance=RequestContext(request))
forms.py
class ListForm(forms.Form):
path = forms.CharField(required=False)
minimum_size = forms.ChoiceField(choices=size_choices)
follow_link = forms.BooleanField(required=False, initial=True)
def __init__(self, *args, **kwargs):
name_list = kwargs.pop('name_list', None)
super(ListForm, self).__init__(*args, **kwargs)
print 'Received data:', self.data
if name_list:
name_choices = [(u, u) for u in name_list]
self.fields['checkboxes'] = forms.MultipleChoiceField(required=False, label='Select Name(s):', widget=forms.CheckboxSelectMultiple(), choices=name_choices)
def clean_path(self):
cd = self.cleaned_data
path = cd.get('path')
if path == '': path = None
return path
def clean_minimum_size(self):
cd = self.cleaned_data
minimum_size = cd.get('minimum_size')
if minimum_size is None: minimum_size = 0
return int(minimum_size)
The form generates and displays perfectly... until I post some data. The 'checkboxes' field doesn't show up in list_form.cleaned_data.items() while it shows in self.data. As it is the form breaks with a KeyError exception. So Im asking, how do i access the checkboxes data?
You're not passing in the name_list parameter when you re-instantiate the form on POST, so the field is not created because if name_list is False.