Django updating profile photo - python

Look I have a problem with displaying photos after updating.
I have a function from my views.py
def addHW(request):
if request.user.is_authenticated:
obj = Profile.objects.get(user=request.user.id)
else:
obj = ''
profile = request.user.profile
form = CustomerForm(instance=profile)
template = 'HW/add.html'
context = {'form': form, 'profile': obj}
if request.method == 'POST':
form = CustomerForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
Profile.objects.get(user=request.user.id).photo.delete()
form.save()
return render(request, template, context)
and after deleting previous photo and saving of new photo, page must be reloaded. And page shows visual reloading, but HTML shows src of previous image. And after manual refreshing page displays new src of photo.
How i can resolve it?

In case of a successful post, you need to make a redirect to implement the Post/Redirect/Get pattern. – Willem Van Onsem 32 mins ago

Related

Problems with Django URL routing

I'm building a website, to be used in dental practices, however I'm having trouble with the URL routing. I'm wanting af URL pattern like: Denthelp/kartotek/#nameofclinic#/opretpatient.
My suggestion looks like this:
urls.py:
path('kartotek/<str:kl_id>/', views.kartotek, name="kartotek"),
path('kartotek/<str:kl_id>/opretpatient/', views.opretpatient, name="opret_patient"),
Views. py:
def kartotek(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
E_patient = kliniknavn.patient_set.all()
context = { 'kliniknavn':kliniknavn, 'E_patient':E_patient}
return render(request,'DentHelp/kartotek.html', context )
def opretpatient(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save()
return redirect('kartotek/<str:kl_id>/')
context = {'form':form, 'kliniknavn':kliniknavn}
return render(request,'DentHelp/kartotek/<str:kl_id>/opretpatient.html', context)
When running code I get an OSError for the last line of code shown here.
Have you guys have any advise for this to work?
You are mixing up render with redirect. render renders a template dynamically with attributes from context, where redirect redirects the user to a different view. To call render, you need to provide template name and context. For redirect, you need to provide url name and parameters (if required). Here is how you should do in your code:
def opretpatient(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save()
return redirect('kartotek', kl_id) # url name and parameter
context = {'form':form, 'kliniknavn':kliniknavn}
return render(request, 'DentHelp/kartotek/opretpatient.html', context) # template name and context

Obtaining data from the form with GET data. Django

How can I get data from the form using the GET method?
For example, I have this form:
class LoansSearchForm(forms.Form):
balance = forms.IntegerField(label='', required=False)
In my view display in the form template this way:
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
But i still a error:
'LoansSearchForm' object has no attribute 'cleaned_data'
When trying to get them this way:
word = form['balance']
I receive a field with completed data. How to get the data from my the form correctly?
Is my form written correctly? Should I use something like that?
(sorry if my question is trivial, but I found very little information about GET forms)
if request.method == 'GET':
form = LoansSearchForm(request.GET)
if form.is_valid():
print('Hello World')
else:
form = LoansSearchForm()
Recommended: run form.is_valid() and then you do form.cleaned_data
def search_results(request):
form = LoansSearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
word = cd['balance']
else:
word = None
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it anywhere.
more on cleaned data - documentation
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data # here <------
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
The problem with your code is that forms are not filled on initialization but when you call form.is_valid, if the form is indeed valid, then it populates cleaned_data
You can read more about the related documentation.
I used name=form.data['field_name'], think it answers your answer of obtaining form values on submit.

Incorrect display PasswordChangeForm with additional html span tag

Im actually struggling with PasswordChangeForm in Django, but I don't know why label and input for password confirmation display on right side. I guess its an issue with span class helptext which should be smaller which dont disturb for pass.conf input. Look at my pic and code: https://ibb.co/3CjTVrt
I've tried to apply some mods in CSS file with no results.
def change_password(request):
if request.method == "POST":
form = PasswordChangeForm(user=request.user, data=request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user) # Important!
messages.success(request, 'Hasło zostało pomyślnie zmienione.')
return redirect("flats_rent:zmień_hasło")
else:
form = PasswordChangeForm(request.user)
response = render(request, 'flats_rent/settings.html', {'form': form})
response.set_cookie('password_changed', 'true')
return response
Expected: correct display of the form with 3 fields under themselves
Actual: just like in the pic

django comments views from scratch

I'm working on a blog build on django and doing the comment stuff and I would like to build it from scratch here my views function:
def topic_detail(request, slug):
topic = get_object_or_404(Topic, slug=slug)
form = CommentForm()
if request.method == 'POST':
if request.user.is_authenticated:
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.topic = topic
comment.created_by = request.user
comment.save()
return redirect('board:topic_detail', slug=topic.slug)
else:
redirect('accounts:login')
else:
form = CommentForm()
return render(request, 'topic.html', {'topic':topic, 'form':form})
my page layout would be:
< ............................>
Something I want to write
<.............................>
Comment Field
<.............................>
Comments
So when user presses the button, server will check if that user is authenticated. If yes comment is updated, If no user will be directed to login views. Here the problem, when I'm logged in everything works fine, but when I log out test the views, It does not redirect me to the login views but just reload the page. I would appreciate if you help me.
Thanks!
You should use return redirect(....) instead of just redirect(...) to return the actual HttpResponse. Now your code continues to the last line and renders the same page again.

URL is not changing though page redirects in django

I have developed a simple django project in which photos will be stored and displayed. The problem is whenever I redirect to a page, the page gets loaded but the url does not change in the address bar. So when i refresh the page again, I am getting errors. For example,
I created an album. For that the url is: 127.0.0.1:8000/create_album/
Then it has to redirect to the albums page where all albums of user are stored.
That url is 127.0.0.1:8000/10/
But i am not getting that url when i redirect to that page.
The views.py:
**def create_album(request):
if not request.user.is_authenticated():
return render(request, 'photo/login.html')
else:
form = AlbumForm(request.POST or None, request.FILES or None)
if form.is_valid():
album = form.save(commit=False)
album.user = request.user
album.album_logo = request.FILES['album_logo']
album.save()
return render(request, 'photo/detail.html', {'album': album})
context = {
"form": form,
}
return render(request, 'photo/create_album.html', context)
def detail(request, album_id):
if not request.user.is_authenticated():
return render(request, 'photo/login.html')
else:
user = request.user
album = get_object_or_404(Album, pk=album_id)
return render(request, 'photo/detail.html', {'album': album, 'user': user})**
The page has to be redirected to photo/detail.html. It redirects to the required page but the url doesn't change. Please help me with this.
It is good practice to do a redirect upon submitting a form. Here's how you can change your code to perform the redirect:
from django.shortcuts import render, redirect
from django.urls import reverse
def create_album(request):
if not request.user.is_authenticated():
return render(request, 'photo/login.html')
else:
form = AlbumForm(request.POST or None, request.FILES or None)
if form.is_valid():
album = form.save(commit=False)
album.user = request.user
album.album_logo = request.FILES['album_logo']
album.save()
return redirect(reverse('detail', kwargs={'album_id':album.id}))
context = {
"form": form,
}
return render(request, 'photo/create_album.html', context)
This assumes that the url/view is named detail in your url patterns.
You could try this first, and if it doesn't work could we see your HTML code for the form?

Categories

Resources