I am changing the password if the current user is logged in.
views.py:
def change_password(request,pk=None):
user = MyUser.objects.get(pk=pk)
if request.method == "POST":
form = PasswordChangeForm(user=user, data=request.POST)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
context = {
'form': form,
'title': _('Password change'),
}
return render(request, "nurse/change_password.html")
else:
form = PasswordChangeForm(user=user)
context = {
'form': form,
'title': _('Password change'),
}
return render(request,"nurse/change_password.html")
The function is working fine, but after this function call, I am not getting user.id in my html file.
What am I doing wrong?
Related
def add(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
title = form.cleaned_data["title"]
content = form.cleaned_data["content"]
return HttpResponseRedirect(reverse("index",args=(title,content, {
"entries": util.save_entry(title, content)
})))
else:
return render(request, "encyclopedia/add.html",{
"form": form
})
else:
return render(request, "encyclopedia/add.html",{
"form": ContactForm()
})
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
I cant seem to get the redirecting to work. Everything else works up till there please help. Below are my code and error
views.py
error
urls.py
I have default Django registration form. It is sent to render to the page based on type of request and user login status. This logic is implemented in views.py file. Somehow, if user is not logged in and GET request is sent to the page, my view returns UnboundLocalError: local variable 'form' is referenced before assignment. How could this happen?
P.S. Here's my view.
def EmplRegisterView(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
group = Group.objects.get(name = 'Employers')
user.groups.add(group)
login(request, user)
return redirect('ProfileSetup')
else:
if request.user.is_authenticated:
logout(request)
form = UserCreationForm()
else:
form = UserCreationForm()
context = {
'form':form,
}
return render(request, "registerPage.html", context)
Try this way
def EmplRegisterView(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
group = Group.objects.get(name = 'Employers')
user.groups.add(group)
login(request, user)
return redirect('ProfileSetup')
if request.user.is_authenticated:
logout(request)
context = {
'form':form,
}
return render(request, "registerPage.html", context)
In View 1's form their is a field called 'reference'. I need to access whatever value is submitted in that field in View 2 and set a variable equal to it. Right now I am just getting an error "orders matching query does not exist".
This is what I'm trying (I've commented the code in view2 to indicate where im getting the error).
views.py
def view1(request, pk):
item = get_object_or_404(Manifests, pk=pk)
if request.method == "POST":
form = CreateManifestForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('view2')
else:
form = CreateManifestForm(instance=item)
return render(request, 'edit_manifest_frombrowse.html', {'form': form})
def view2(request):
form = CreateManifestForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save()
...
reference_id = request.POST.get('reference') #this is how Im trying to get reference from the previos view
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist"
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
forms.py
class CreateManifestForm(forms.ModelForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB')
I just want to be able to use whatever value is submitted in the 'reference' field in view1 in view2 and assign it equal to reference_id
Something like this:
from django.urls import reverse
def view1(request, pk):
item = get_object_or_404(Manifests, pk=pk)
if request.method == "POST":
form = CreateManifestForm(request.POST, instance=item)
if form.is_valid():
obj = form.save()
reference_id = request.POST.get('reference') or obj.reference.id
return redirect(reverse('view2')+f'?reference={reference_id}')
else:
form = CreateManifestForm(instance=item)
return render(request, 'edit_manifest_frombrowse.html', {'form': form})
def view2(request):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
form.save()
...
data = getattr(request, 'POST', None) or getattr(request, 'GET', {})
reference_id = data.get('reference') #this is how Im trying to get reference from the previos view
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist"
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
I defined an initial value to my title field, but once I execute it, it shows no error and the initial value is not showing in my field how do I solve it? Thanks
def form_view(request):
if request.method == "POST":
initial_data = {
'title': 'default title'
}
form = ProductForm(request.POST, initial=initial_data)
if form.is_valid():
form.save()
form = ProductForm()
else:
form = ProductForm()
return render(request, "form.html", {"form": form})
You've put it in the wrong place. If you want it to show when the form is first rendered, you shouldn't put it in the POST block - which is called when the form is submitted - but the else block.
if request.method == 'POST':
form = ProductForm(request.POST)
...
else:
form = ProductForm(initial=initial_data)
So I have a signup on my base.html, then the form redirects to a signup page.
def signIn(request):
if request.user.is_authenticated():
context = {
"extendVar":"baseLoggedIn.html",
}
return HttpResponseRedirect("out")
if request.user.is_authenticated()==False:
# form=SignUpForm(request.POST or None)
if request.method=="POST":
email=request.POST.get('email','')
password = request.POST.get('password','')
user = auth.authenticate(username=email,password=password)
print(email)
print(password)
print(user)
if user is not None:
print("notNone")
auth.login(request,user)
return HttpResponseRedirect("out")
else:
print("None quàlol")
context={
"failure":"Password and e-mail did not match",
}
return HttpResponseRedirect("out") #redirects to base.html
context = {
"extendVar":"baseNotLoggedIn.html",
}
return render(request, "base.html",context)
the only problem is, when I do this, it redirects to the home page, but the home page doesn't have any errors, and I can't figure out a way to display the error that the password + email did not match, since i'm redirecting.
You need to pass your message as part of context, and your HttpResponseRedirect does not take any context as a parameter, so you need to return render(request, "base.html", context) instead of HttpResponseRedirect. Then you can access the "failure" key from context.
Also, keep your code clean!
def sign_in(request):
if request.user.is_authenticated():
context = {
"extendVar":"baseLoggedIn.html",
}
return HttpResponseRedirect("out")
else:
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = auth.authenticate(username=email, password=password)
print(email)
print(password)
print(user)
if user:
print("notNone")
auth.login(request, user)
return HttpResponseRedirect("out")
else:
print("None quàlol")
context={
"failure":"Password and e-mail did not match",
}
return render(request, "base.html", context)
else: # form invalid, pass as variable back to user with form errors
return render(request, "base.html", {'form': form}
context = {
"extendVar":"baseNotLoggedIn.html",
}
return render(request, "base.html",context)