Delete button in a template is inactive - python

enter code hereI have a group_edit.html which permit to update info of a group and delete it.
Upade(save) works great but button for delete is doing nothing.
Thanks for help:
My group_edit.html:
{% block page %}
<form method="POST">
{% csrf_token %}
<div class="col-lg-4 col-md-4 col-sm-4 content">
{% bootstrap_form form %}
<button type="submit" class="btn btn-pink pull-right">Save</button>
<button type="reset" class="btn btn-warning pull-left">Delete</button>
</div>
Back to list
</form>
{% endblock %}
My confirm_delete.html template:
{% block title %}Delete{% endblock %}
{% block heading %}<h3 class="page-header-center">Object Delete</h3> {% endblock %}
{% block page %}
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ obj }}"?</p>
<input type="submit" value="Confirm" class="btn btn-warning">
Cancel
</form>
{% endblock %}
my views.py:
def group_edit(request, group_id):
form = GroupForm(instance=Group.objects.get(group_id=group_id))
if request.method == "POST":
form = GroupForm(request.POST, instance=Group.objects.get(group_id=group_id))
if form.is_valid():
form.save()
messages.success(request, 'Group saved') # message for inform user of success - See messages in html file
return redirect(group_list)
return render(request, 'imports/group_edit.html', {
"group_id": group_id,
"form": form,
})
def confirm_delete(request, group_id):
obj = GroupForm(instance=Group.objects.get(group_id=group_id))
if request.method == "POST":
obj.delete()
messages.success(request, 'Deleted') # message for inform user of success - See messages in html file
return render(request, 'imports/group_list.html')
context = {
"obj": obj
}
return render(request, "imports/confirm_delete.html", context)
and my urls.py:
path('group_edit/<int:group_id>/', views.group_edit, name='group-edit'),
path('confirm_delete/<int:group_id>/', views.confirm_delete, name='confirm-delete'),

In your link, the span of <a> is empty. So instead of
Delete
it should be:
Delete
Probably it is better to specify the {% url ... %} parameters with named parameters:
Delete

Related

why my user can't be authenticated after register,but can after login

I started an app named 'blogs' as a programming book required,when I finished the 'register' function which can register a user and login with it.I found that the user can be added to database normally,but it can't be authenticated.but when I used the username login normally,it can work!I checked my codes for many times,but I can't find the fault.Please give me some help,thank you very much!
Here are my codes:
users:views.py:
def register(request):
if request.method != 'POST':
form = UserCreationForm()
else:
form = UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
authenticated_user = authenticate(username=new_user.username, password=request.POST['password1'])
login(request,authenticated_user)
return HttpResponseRedirect(reverse('blogs:index'))
context = {'form':form}
return render(request,'users/register.html',context)
users:register.html:
{% extends "blogs/base.html" %}
{% block content %}
<form method="post" action="{% url 'users:register' %}">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">register</button>
<input type="hidden" name="next" value="{% url 'blogs:index' %}" />
</form>
{% endblock content %}
blogs:base.html:
Welcome to blog -
{% if user.is_authenticated %}
hello,{{ user.username }} -
logout
{% else %}
register -
login
{% endif %}
{% block content %}{% endblock content %}
Where do you get 'password1' from? Probably you have it in your login.html and confuse. Change that line with authenticated_user = authenticate(username=new_user.username, password=new_user.password) . Hope it will help.

User login info is deleted when I delete posts

User login info is deleted when I delete posts.I wrote in views.py
def top(request):
if request.method == 'POST':
loginform = LoginForm(request, data=request.POST)
if loginform.is_valid():
user = loginform.get_user()
info = Info.objects.order_by('-created_at')
return render(request, 'top.html', {'info':info,'user': user})
loginform = LoginForm()
info = Info.objects.order_by('-created_at')
return render(request, 'top.html',{'info':info,'loginform':loginform,'user': request.user})
def delete(request):
delete_ids = request.POST.getlist('delete_ids')
if delete_ids:
Info.objects.filter(id__in=delete_ids).delete()
return redirect(reverse("app:top"))
in top.html
<div>
{% if user and not user.is_anonymous %}
<h2>{{ user.username }}</h2>
{% else %}
<form action="" method="POST">
<div>
{{ loginform.non_field_errors }}
{% for field in loginform %}
{{ field }}
{{ field.errors }}
{% endfor %}
</div>
<button type="submit">LOGIN</button>
{% csrf_token %}
</form>
{% endif %}
<div>
<form action="{% url 'app:delete' %}" method="POST">
{% csrf_token %}
{% for i in info %}
<input id="chkbox" type="checkbox" name="delete_ids" value="{{ i.pk }}" />
<div>
<p>{{ i.name }}</p>
</div>
{% endfor %}
<button type="submit">Delete</button>
</form>
Firstly I login to this app by putting LOGIN button,user.username is shown. And when I put Delete button to delete info,login info is deleted too(user.username is not shown).info is deleted but I really cannot understand why login info is deleted too.I cannot send user's info in redirect(reverse("app:top")),so shouldn't I use redirect?How should I fix this?
Looks like you forgot to login user. Try to add login() method:
from django.contrib.auth import login
def top(request):
if request.method == 'POST':
loginform = LoginForm(request, data=request.POST)
if loginform.is_valid():
user = loginform.get_user()
login(request, user)
Also it's better to use is_authenticated instead of is_anonymous:
{% if user.is_authenticated %}

django logout me after render_to_response()

this is my views.py
def createpost(request, id=None):
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid() and request.method == 'POST':
instance = form.save(commit=False)
instance.user = request.user
instance.save()
messages.success(request, "successfully create!")
return HttpResponseRedirect('/post')
else:
context ={
'form': form
}
return render_to_response('createPost.html', context)
and createPost.html code that i want show the post page with errors
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
{% if request.user.is_authenticated %}\
<form method="POST" name="PostForm" action="/post/createpost/" enctype="multipart/form-data"> {% csrf_token %}
{{form|as_bootstrap_inline}}
<input type="hidden" name="user_id" value="{{ user.id }}" />
<button type="submit" class="btn btn-primary">Save AD</button>
{% else %}
<div>Please Register First!</div>
{% endif %}
</form>
{% endblock content %}
But when the error happens, it redirects and logs me out . How can I post the authenticated user to my post page ?
You should probably use render with request
rewrite your else part in views.py
e.g -
else:
context ={
'form': form,
}
return render(request, 'createPost.htm', context)
You shoud use render instead, render_to_response does not make request available see documentation:
This function preceded the introduction of render() and works similarly except that it doesn’t make the request available in the response. It’s not recommended and is likely to be deprecated in the future.
That is why {% if request.user.is_authenticated %} validation in template not passed.

Django - Template tags not working properly after form validation

I am having a form which takes some value as input, and I am processing the input and returning the required output. Now when I tried to display the output it not displaying on the webpage.
The following is my forms.py:
class CompForm(forms.ModelForm):
class Meta:
model = Comp
fields = ('inp',)
The following is my views.py:
def index(request):
form = CompForm(request.POST or None)
context = {
'form': form,
}
print context
if form.is_valid():
...
...
outData = "The values you gave is correct"
errData = "The values you gave is incorrect"
print context
context['outData'] = outData
context['errData'] = errData
print context
return render(request, 'comp/index.html', context)
The following is my index.html:
{% extends "comp/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form method="post" action="">
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-primary" type="submit" name="Submit" />
</form>
</div>
</div>
{% if outData %}
{{ outData.as_p }}
{% endif %}
{% if errData %}
{{ errData.as_p }}
{% endif %}
{% endblock %}
In the terminal I am able to get the outData and errData in the dictionary, but its not getting displayed in the webpage. What might be the mistake? Kindly help.
You are trying to called the method as_p on strings which doesn't make sense.
as_p() is a helper method on form instances to make it easier to render them in the template so you need:
{{ form.as_p }}
you can also use as_table and as_ul
You can read more in the documentation

Django Very simple navigation bar, my form does not show up after {% extend "base.html" %}

I am writing a very simple navigation bar. For example I have my login view down below. When I open the login page I can see my the results of my base.html but for some reason I can not see the results of my login.html, meaning I cant see the form I wrote only the top links bar.
view.py -- login view
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
m = UserLogin.objects.get(user_name=request.POST['user_name'])
if m.password == request.POST['password']:
request.session['member_id'] = m.id
return HttpResponseRedirect('/game')
else:
c = {'form': form,
'error_message': "Your username and password didn't match."}
c.update(csrf(request))
return render_to_respons('game/login.html', c)
else:
form = UserLoginForm()
c = {'form': form}
c.update(csrf(request))
return render_to_response('game/login.html', c)
base.html
<div id="navigation">
Home
Upload
Register
Login
</div>
login.html
{% extends "base.html" %}
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/game/login/" method="post">
{% csrf_token %}
<table border='0'>
<div class="fieldWrapper"><tr><td>
{{ form.user_name.errors }}</td><td></td></tr><tr><td>
<label for="id_user_name">User Name:</label></td><td>
{{ form.user_name }}</td></tr>
</div>
<div class="fieldWrapper"><tr><td>
{{ form.password.errors }}</td><td></td><tr><td>
<label for="id_password">Password:</label></td><td>
{{ form.password }}</td></tr>
</div>
</table>
<input type="submit" value="Login" />
</form>
You need to define blocks to use template inheritance. For example, change your base.html to:
<div id="navigation">
Home
Upload
Register
Login
</div>
{% block content %}{% endblock %}
then place your login code into the content block:
{% extends "base.html" %}
{% block content %}
...login.html content goes here
{% endblock %}
Check out the docs for more detail.

Categories