Django form requires resubmission - python

I have a simple form in Django, and in my template I want to display each individual object for the whole queryset which I am saving the form to. The error I am getting is that my form does not seem to submit on the first attempt. Only when I click the submit button, manually refresh the page and then 'confirm form resubmission' do I see my updated queryset objects displayed in the template.
I am saving my form like this in my views:
exercise_name = ExerciseName.objects.all()
if request.method == 'POST':
form = ExerciseNameForm(request.POST)
if form.is_valid():
form.save(commit=True)
else:
form = ExerciseNameForm()
and passing the queryset to the template through the following context:
{ 'exercise_name': exercise_name }
and iterating through it like
{% for exercise_title in exercise_name %}
#content displaying each iteration
{% endfor %}
with my form to update it like:
<div>
<form method = "POST">{% csrf_token %}
{{form.as_p}}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</div>
I am not sure why it is making me refresh the page and resubmit the form again in order to see the updated queryset after submitting the form?

You should be doing something like this:
if request.method == 'POST':
form = ExerciseNameForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponse("data submitted successfully")
else:
return render(request, "your_template.html", {'form':form})
else:
form = ExerciseNameForm()
return render(request, "your_template.html", {'form':form})

Related

Django restricting users from updating/deleting other users posts

views.py
#login_required(login_url='/login')
def updatepost(request,pk):
post = Post.objects.get(id=pk)
form = PostForm(instance=post)
if request.method =='POST':
form = PostForm(request.POST, request.FILES, instance=post)
if form.is_valid():
form.save()
return redirect ('mainpage')
context = {'form':form}
return render( request, 'postform.html', context )
postform.html
{% include 'main.html'%}
{% block content %}
{%if user.is_authenticated%}
{% if user.id == post.user.id%}
<div>
<form method="POST" action ="">
{% csrf_token %}
{{form.as_p}}
<input type="Submit" value ="Submit"/>
</form>
</div>
{%endif%}
{%endif%}
{% endblock content %}
I am trying to restrict user who is logged in - from updating , deleting other users posts.
However when I Try to use {% if user.id == post.user.id%} , the page becomes blank even for the user who is editing his own post. The same goes for deleting.
It works on mainpages - where posts are displayed (it hides edit and delete buttons).
What is the reason that the post is not showing inside the template ?
I don't understand that even {{post.user}} in postform.html does not appear , neither on deleteform etc. - why this data of objects of a post is not being sent to postform.html ?
You should change the context to access the post instance from your template.
context = {'form': form, 'post': post}
You can only access the context values from the templates. So pass the ones you want to use while you are returning a response.

Django Multiple Form on same page interact with each other

I have a page with two forms. When I click on the button Update Profile on the left Form it also send the POST request to the the second form which is not what I want. I don't want them to interact together. How can I do that?
views.py
#login_required(login_url='signin')
def dashboard(request):
global user_id
data = Account.objects.filter(user=request.user)
profile_data = Profile.objects.get(user=request.user)
profile_form = ProfileForm(request.POST or None, instance=profile_data)
addaccount_form = AddAccountForm(request.POST or None)
# Update Profile Settings
if profile_form.is_valid():
print("worked")
profile_form.save()
if request.method == "POST":
if addaccount_form.is_valid():
# save account to DataBase
return HttpResponseRedirect("http://127.0.0.1:7000/dashboard/")
context = {
'data': data,
'profile_form': profile_form,
'addaccount_form': addaccount_form,
}
return render(request, "main/dashboard.html", context)
dashboard.html
<form action="" method="POST">
{% csrf_token %}
{{profile_form}}
<button type="submit" class="updatebut">Update Profile</button>
</form>
<form action="" method="POST">
{% csrf_token %}
{{addaccount_form}}
<button type="submit" class="addbut">Add Account</button>
</form>
You can check which form in your request
if 'profile_form' in request.POST:
profile_form = ProfileForm(request.POST or None, instance=profile_data)
if profile_form.is_valid():
print("worked")
profile_form.save()
elif 'addaccount_form' in request.POST:
addaccount_form = AddAccountForm(request.POST or None)
if addaccount_form.is_valid():
# save account to DataBase
return HttpResponseRedirect("http://127.0.0.1:7000/dashboard/")
You can add a name to each one of your submit buttons (ex. name="addaccount" and name="updateprofile")
And in your view, add the following:
if 'addaccount' in request.POST:
---do the addacount
elif 'updateprofile' in request.POST:
---do the profile update
Quick and dirty!

Avoiding page refresh when a form is used in Django

I have a very basic Django view:
def myview(request):
if request.method == 'POST':
if 'button1' in request.POST:
form1 = form = myForm(request.POST)
# check whether it's valid:
if form.is_valid():
profile = form.save()
profile.user = request.user
profile.save()
messages.success(request, f"Success")
return HttpResponseRedirect(request.path_info)
else:
form = myForm()
return render(request,
"main/mytemplate.html",
context={"form":form})
And its template:
<form method="post" novalidate>
{% csrf_token %}
{% include 'main/includes/bs4_form.html' with form=form %}
<button name="button1" type="submit" class="btn btn-primary">SUBMIT</button>
</form>
Everything works here, when this form is used, some data is saved on my DB. What i would like to change, though, is the page reload after the form is used.
When the Submit button is hit, the page will be refreshed. Since it makes the navigation way slower, i would like to have the view not refreshing the page each time the form is used.
Is it possible to accomplish this in Django? For example, instead of refreshing the page, i would like to only load part of it, or to have a 'Reload' icon while the view is doing its work.
I'm pretty new to Ajax, so i don't know how to get started on this.

Django edit Form doesn't save

I'm a Django beginner and i have a little problem. I made a form for create the model FantaSquadra, and this works. Then I made a form to edit the model and when I press the submit button it doesn't do anything.
Can someone help me?
urls.py:
path('add/fantasquadra/', views.addFantaSquadra, name='creazione_fanta'),
path('edit/fantasquadra/<int:fantasquadra_id>/', views.editFantaSquadra, name='edit_fanta'),
views.py:
def addFantaSquadra(request):
elenco_fantasquadre = FantaSquadra.objects.all()
if request.method == "POST":
form = NewFantaSquadraForm(request.POST)
if form.is_valid():
fanta_item=form.save(commit=False)
fanta_item.save()
else:
form = NewFantaSquadraForm()
return render(request, 'sondaggio/fantasquadre.html', {'form': form})
def editFantaSquadra(request, fantasquadra_id):
item = get_object_or_404(FantaSquadra, pk=fantasquadra_id)
form = NewFantaSquadraForm(request.POST or None, instance=item)
elenco_fantasquadre = FantaSquadra.objects.all()
if form.is_valid():
form.save()
return render(request, 'sondaggio/fantasquadre.html', {'form': form})
forms.py:
class NewFantaSquadraForm(forms.ModelForm):
class Meta:
model = FantaSquadra
fields = ['nome_fantasquadra','proprietario']
fantasquadre.html
<html>
<h1>Scrivi il nome della tua fantasquadra</h1>
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
</html>
You have a link inside your button, for some reason. The link is taking priority over the button submission, so the data is never actually posted to the view.
Remove that <a> element.

Display User Profile getting ERROR: 'AnonymousUser' object has no attribute '_meta'

I have a simple view that is suppose to check if there is post data,
if so update the user data using UserChangeForm. Else get the form
data of user and display.
Issue: AttributeError at /profile/edit 'AnonymousUser' object has no
attribute '_meta'
I think it might be this line in the edit_profile view
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
Not sure what. Here is the view.py edit_profile
def edit_profile(request):
# Handle post request - if the user submits a form change form details and pass the intance user
if request.method == 'POST':
form = UserChangeForm(request.POST, intance=request.user)
if form.is_valid():
form.save()
return redirect('accounts/profile')
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
profile_edit.html
{% extends 'base.html' %}
{% block head %}
<title>Profile</title>
{% endblock %}
{% block body %}
<div class="container">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save Changes</button>
</form>
</div>
{% endblock %}
You can't update an AnnonymousUser (that is special user class set for not logged in users). One solution of your problem is to disallow viewing this page by not authenticated user by decorating your view using login_required decorator.
You got error because there is not user logged in.
You can instead use try method.
In your code use if user.is_authenticated
if user.is_authenticated():
if request.method == 'POST':
form = UserChangeForm(request.POST, intance=request.user)
if form.is_valid():
form.save()
return redirect('accounts/profile')
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
else:
raise PermissionDenied

Categories

Resources