Reputation: 965
I want to be able to set a cookie on my django site when somebody creates an account. This is currently my view:
from django import forms
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.core.mail import send_mail
CARRIER_CHOICES =(
('@txt.freedommobile.ca', 'Freedom Mobile'),
('@txt.luckymobile.ca', 'Lucky Mobile'),
('none', 'None'),
)
class RegisterForm (forms.Form):
username = forms.CharField()
password = forms.CharField()
check_password = forms.CharField()
email = forms.EmailField()
phone = forms.IntegerField(required=False)
carrier = forms.ChoiceField(choices=CARRIER_CHOICES, required=False)
def register (request):
form_error = 'none'
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
check_password = form.cleaned_data['check_password']
email = form.cleaned_data['email']
phone = form.cleaned_data['phone']
carrier = form.cleaned_data['carrier']
phone = str(phone)
if password == check_password:
phone_email = phone + carrier
user = User.objects.create_user(username, email, password)
user.is_staff = False
user.is_active = True
user.is_superuser = False
send_mail(
'TachlisGeredt.com Account',
'Congrats! You have succesfully created an account with TachlisGeredt.com!',
'[email protected]',
[email],
fail_silently=False,
)
return redirect ("/register/success")
else:
form = RegisterForm(request.POST)
return render (request, 'register.html', {'form':form})
I'ver tried making cookies a million different ways but its really confusing. They all seem to need me to make a variable called 'response', do 'response.set_cookie' or whatever the command is, and then do 'return response'. How do I avoid that, because I am already using 'render' to render a template, and I don't get how this 'response' thing would integrate.
Upvotes: 2
Views: 1138
Reputation: 495
Like this:
def some_view(request):
response = render(request, 'some_template.html')
response.set_cookie(key='have_a_cookie', value=1337)
return response
See django docs for other parameters (e.g. expires
) you may wish to set.
Upvotes: 6