how to use context_processor properly in django - python

Here I am trying to redirect to another page if the form is submitted successfully but this code is not working properly .The code saves the form data sends the email , everything is fine but the problem is while redirecting to another page if the form succeed. The error I get is:
Django Version: 2.0.6
Exception Type: ValueError
Exception Value:
dictionary update sequence element #0 has length 0; 2 is required
context_processor.py
def volunteer_page2(request):
volunteer = Volunteer.objects.all().order_by('date')
if request.method == 'POST':
form = VForm(request.POST or None)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = "{0} with email address {1} has sent you new message \n\n{2}".format(name, email, form.cleaned_data['message'])
form.save(commit = False)
try:
send_mail(name, message, 'appname <settings.EMAIL_HOST_USER>', ['myemail'])
except:
return HttpResponse('Invalid header found')
form.save()
messages.success(request, 'Success')
return redirect('volunteer_page')
else:
messages.error(request, "Sorry try again")
else:
form = VForm()
return {'volunteer': volunteer, 'form':form}
views.py
def about_page(request):
about = About.objects.all().order_by('date')
banner = Banner.objects.all()
testimonial = Testimonial.objects.order_by('-pk')[0:2]
nav = Nav.objects.all()
footer = Footer.objects.all()
latest_event2 = Events.objects.order_by('-pk')[0:2]
context = {
'about': about,
'testimonial': testimonial,
'footer':footer,
'banner': banner,
'nav': nav,
'latest_event2': latest_event2,
}
return render(request, 'myapp/about.html', context)
settings.py
'myapp.context_processor.volunteer_page2'

Django's context processor should always return dictionary. In your code you are returning HttpResponse also. This is problem.

Related

django: problem with ajax request sent to ModelFormset template

I am trying to pass user data from one template inside of another template. For this I use an ajax request, as well explained here How do I integrate Ajax with Django applications?
although no error shows up, nothing gets pulled.
here is what my model formset view look like inside of template 1:
def New_Sales(request):
#context = {}
form = modelformset_factory(historical_recent_data, fields=('id','Id', 'Date','Quantity', 'NetAmount', 'customer_name'))
if request.method == 'GET':
formset = form(queryset= historical_recent_data.objects.none())
#blank_form = formset.empty_form
elif request.method == 'POST':
formset = form(request.POST)
#blank_form = formset.empty_form
if formset.is_valid():
request.session['sale'] = request.POST.get('sale')
for check_form in formset:
check_form.save()
quantity = check_form.cleaned_data.get('Quantity')
id = check_form.cleaned_data.get('Id')
update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity)
update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity)
return redirect('/invoice/pdf/assembly/')
#else:
#form = form(queryset= historical_recent_data.objects.none())
return render(request, 'new_sale.html', {'formset':formset})
and here is the view to access template 1 data into template 2:
def generate_pdf_assembly(request):
my_company = MyCompany.objects.get(id = 1)
request = request.session.get('sale')
context = {'request' : request, 'my_company' : my_company }
print(context)
and here is the ajax request to access the data from the template (in template 2):
<h3> {{ context }} </h3>
<script>
$.ajax({
method: "GET",
url: "/new_sale.html",
sucess: function(context){
alert(context);
},
failure: function(context){
alert('got an error');
}
});
</script>
I feel like there must be an issue with the request.session in the view since no evident error gets outputed neither in log nor chrome console but I am not competent to debug it further at this point.
UPDATE: after changing context for request in tag template, the value None shows up, definitely an issue with the requesting
def username_exists(request):
data = {'msg':''}
if request.method == 'GET':
username = request.GET.get('username').lower()
exists = Usernames.objects.filter(name=username).exists()
if exists:
data['msg'] = username + ' already exists.'
else:
data['msg'] = username + ' does not exists.'`enter code here`
return JsonResponse(data)

No HttpResponse object is returned when calling a view from another view?

I have a webpage where user chooses one object from a model. Based on the button clicked, certain actions are executed. One of the actions is by calling one of the views, and dislaying another webpage.
So, when user visits http://127.0.0.1:8000/clinic/manage, he sees the below form:
Code:
#login_required
def manage_clinics(request):
msg = ''
if request.method == 'POST':
clid = int(request.POST.get('clinics'))
print("POST details", request.POST)
if request.POST.get('createdoctor')=='Create Doctor':
clinicobj = Clinic.objects.get(clinicid=clid)
print("Creating Doctor for clinic:", clinicobj)
createdoctor(request, clinicobj.label)
else:
form = ChooseClinicMetaForm()
return render(request, 'clinic/manageclinics.html', {'form': form, 'msg': msg})
If he clicks on 'Create Doctor', the following view function is to be executed:
#login_required
def createdoctor(request, cliniclabel):
msg =''
cliniclink = '/clinic/'+cliniclabel+'/createdoctor'
cl = Clinic.objects.get(label=cliniclabel)
if request.method == 'POST':
print("POST details", request.POST)
form = DoctorMetaForm(request.POST)
if form.is_valid():
print("Form is valid.")
# form.save()
username = request.POST.get('username')
name = request.POST.get('name')
email = request.POST.get('email')
phone = request.POST.get('phone')
msg = SaveDoctortoSQLNew(request)
print(msg)
if 'Error:' not in msg:
doctorobj = doctor.objects.get(name=name, email=email, phone=phone, username=username)
clinicobj = Clinic.objects.get(label=cliniclabel)
permobj = ClinicPermissions(clinicid=clinicobj, doctorid=doctorobj, viewperms =1)
permobj.save()
msg = "Successfully created a doctor and assigned permissions"
else:
msg = "Invalid details."
print(msg)
else:
# cl = Clinic.objects.get(label=cliniclabel)
form = DoctorMetaForm()
return render(request, 'clinic/doctorprofile.html', {'form': form, 'rnd_num': randomnumber(), 'cliniclink': cliniclink, 'msg': msg, 'clinic':cl})
When this is executed, I get the following exception:
[14/Oct/2018 14:40:37] "GET /appointments/static/appointments/js/bootstrap.min.js.map HTTP/1.1" 404 1758
POST details <QueryDict: {'csrfmiddlewaretoken': ['3Jt28ToKqHiP6rGaTmbOOZH0yNRaU1TCOx427C6sV42VCbFrbrdJVlpzaSQiI3EK'], 'clinics': ['1'], 'createdoctor': ['Create Doctor']}>
Creating Doctor for clinic: Dr Joel's ENT Clinic
POST details <QueryDict: {'csrfmiddlewaretoken': ['3Jt28ToKqHiP6rGaTmbOOZH0yNRaU1TCOx427C6sV42VCbFrbrdJVlpzaSQiI3EK'], 'clinics': ['1'], 'createdoctor': ['Create Doctor']}>
Invalid details.
2018-10-14 14:40:40,928 django.request ERROR Internal Server Error: /clinic/manage
Traceback (most recent call last):
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 137, in _get_response
"returned None instead." % (callback.__module__, view_name)
ValueError: The view clinic.views.manage_clinics didn't return an HttpResponse object. It returned None instead.
So this is apparently because no HttpResponse object is returned. But doesnt the createdoctor function return just that? Or is python complaining about the return of the statement createdoctor(request, clinicobj.label)? Am I supposed to wrap this up in a HttpResponse?
It appears like you forgot to add return in manage_clinics
#login_required
def manage_clinics(request):
msg = ''
if request.method == 'POST':
clid = int(request.POST.get('clinics'))
print("POST details", request.POST)
if request.POST.get('createdoctor')=='Create Doctor':
clinicobj = Clinic.objects.get(clinicid=clid)
print("Creating Doctor for clinic:", clinicobj)
return createdoctor(request, clinicobj.label)
else:
form = ChooseClinicMetaForm()
return render(request, 'clinic/manageclinics.html', {'form': form, 'msg': msg})

Issue on sending message from contact page - Django 1.6

I have this method on my views.py:
def contact_us(request):
form = ContactUsForm()
d = {'form': form}
if request.method == 'POST':
form = ContactUsForm(request.POST)
if form.is_valid():
Contact.objects.create(
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
message=form.cleaned_data['message'],
)
try:
send_mail(first_name,last_name,email,message,['kristian.koci#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
d['message'] = _('Thank You! We will contact you shortly')
else:
d['form'] = form
return render_to_response('profiles/contact_us.html', d,
context_instance=RequestContext(request))
This is the url:
http://beta.contratalos.com/profiles/contact_us/
I want to send that message to the recipient I've specified on sned_mail method.
But everytime I try it throws this error:
NameError: global name 'first_name' is not defined
File "apps/profiles/views.py", line 737, in contact_us
send_mail(first_name,last_name,email,message,['kristian.koci#gmail.com'])
Any ideas on what that could be?
Thanks in advance!
You are not declaring the variable first_name, last_name anywhere.
The following code will help you.
temp_contact=Contact.objects.create(
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
message=form.cleaned_data['message'],
)
temp_contact.save()
try:
send_mail(temp_contact.first_name,temp_contact.last_name,temp_contact.email,temp_contact.message, ['kristian.koci#gmail.com'])
except:
...
Edit:
The following code will help you send the right thing.
temp_contact=Contact.objects.create(
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
message=form.cleaned_data['message'],
)
temp_contact.save()
try:
email_subject = "Contact Registration - "+temp_contact.email
email_content = "Name:"+temp_contact.first_name+" "+temp_contact.last_name+"\nContent:"+temp_contact.message
send_mail(email_subject,email_content,temp_contact.email, ['kristian.koci#gmail.com'])
except:
...

ModelForm For Registration HttpResponseError

First off, I know what the error means, I'm just confused on the configuration.
I'm getting an error of:
views.Registration didn't return an HttpResponse object
The issue is when I visit localhost/Register, I get the above error.
Q: If I want localhost/Register to show form from RegistrationForm() when it loads the register.html template within render() (at the bottom) when /Register is accessed. How do I do that? Do I need to create another view like /NewUser that I currently have specified? My thought was that render() was going to execute to show the template (with the form inside it) when viewing /Register
Code:
a view of:
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/?user=' + 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', {
'form': RegForm
})
You need to render something if the request is 'GET' instead of 'POST': ie.
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/?user=' + 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', {
'form': RegForm
})
else:
RegForm=RegistrationForm()
return render(request, 'template.html', {'formset': RegForm})
of course, you should change the context for your template, depending on whatever it is you need to render.
No, you should just move everything from the else onwards back one indentation level. Otherwise, nothing is returned if the request is not a POST.

Django -- Redirecting Views with Parameters

In the Django app I am building I would like to have the user creation process go as follows: As user signs up, if valid is then redirected to create a LIST object, and if valid is then redirected to what will be a dashboard for the LIST object just created. My views.py are as follows:
def user_signup(request):
if request.method == 'POST':
form = forms.UserSignupForm(data=request.POST)
if form.is_valid():
user = form.save()
g = Group.objects.get(name='test_group')
g.user_set.add(user)
# log user in
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, u'Welcome to Social FollowUp')
return redirect('user_create')
else:
form = forms.UserSignupForm()
return TemplateResponse(request, 'user_signup.html', {
'form': form,
})
#login_required
#permission_required('')
def user_create(request):
if request.method == 'POST':
list_form = forms.ListForm(request.POST)
if list_form.is_valid():
list_create = list_form.save()
messages.success(request, 'List {0} created'.format(list_create.list_id))
return redirect('user_dashboard')
else:
list_form = forms.ListForm()
return TemplateResponse(request, 'dashboard/create.html', {'list_form': list_form, })
def user_dashboard(request, list_id):
try:
list_id = models.List.objects.get(pk=list_id)
except models.List.DoesNotExist:
raise Http404
return TemplateResponse(request, 'dashboard/view.html', {'list_id': list_id})
My urls.py for these views is as follows:
url(r'user/signup/$', views.user_signup, name='user_signup'),
url(r'u/dashboard/(?P<list_id>\d+)/$', views.user_dashboard, name='user_dashboard'),
url(r'u/list/create/$', views.user_create, name='user_create'),
When I try to run through the process, the first two views work correctly. However when I redirect to the user_dashboard I get the following error:
Reverse for 'user_dashboard' with arguments '' and keyword arguments '{}' not found.
which sites this:
return redirect('user_dashboard')
I'm assuming this has something to do with me not passing in a list_id, however, even when I tried to pass in a hardcoded value it did not work (like this):
return redirect('user_dashboard', {'list_id': 2})
What am I doing wrong here?
Try:
return redirect(reverse('user_dashboard', args=(2,)))
Your code
return redirect('user_dashboard')
would not work because in your url pattern, you have
url(r'u/dashboard/(?P<list_id>\d+)/$', views.user_dashboard, name='user_dashboard'),
which requires list_id as a parameter.

Categories

Resources