Django DetailView update on one page not working - NoReverseMatch error - django

I have a problem with update of my DetailView, so once i try to submit the updated values I am receiving an error NoReverseMatch at /task/164/. Could you please give me a hint what is wrong?
Thx!
urls:
path('excel_upload', ex_views.ExcelUploadView.as_view(), name='excel-upload'),
path('user_list', ex_views.UsersListView.as_view(), name = "user-list"),
path('excel_table', ex_views.ExcelTableView.as_view(), name = "excel-table"),
path("task/add", ex_views.TaskAddView.as_view(), name="task-add"),
path("task/<int:pk>/", ex_views.TaskDetailView.as_view(), name="task-detail"),
forms.py
class AddEditTaskForm(forms.ModelForm):
class Meta:
model = Task
exclude = ['created_by']
widgets = {
"due_date": forms.DateInput(attrs={'type':'date'}),
"completed_date": forms.DateInput(attrs={'type': 'date'}),
"name":forms.TextInput(),
"note": forms.Textarea(),
}
views.py
class TaskDetailView(DetailView):
model = Task
template_name = "hana/task_detail.html"
# Add POST method
def post(self, request, pk):
task = get_object_or_404(Task, pk=pk)
form = AddEditTaskForm(request.POST, instance=task)
if "add_edit_task" in request.POST:
if form.is_valid():
form.save()
messages.success(request, "The task has been edited.")
return redirect('excel-table')
return render(request, 'hana/task_detail.html', {'form': form})
error:
NoReverseMatch at /task/164/
Reverse for 'task-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['task\/(?P[0-9]+)\/$']
Request Method: POST
Request URL: http://127.0.0.1:8000/task/164/
Django Version: 3.0.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'task-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['task\/(?P[0-9]+)\/$']
Exception Location: /home/lukasz/envtest2/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677
template:
<form method="post" action="{% url 'task-detail' object.id %}" role="form" class="d-inline">
{% csrf_token %}
<div style="display:inline;">
<button class="btn btn-info btn-sm" type="submit" name="toggle_done">
{% if task.completed %} Mark Not Done {% else %} Mark Done {% endif %}
</button>
</div>
</form>
<a class="btn btn-danger btn-sm mt-1 mb-1" href={% url 'task-delete' object.id %}">Delete</a>

Your issue is caused by mixing class based and function based views. Your function based post view uses the same template as your class based TaskDetailView, but since it doesn't have the same "magic" inherited from DetailView, there is no object passed in the context dictionary (you only pass form).
The proper fix would be to stick to the same view architecture when possible, but a trivial fix would be:
return render(request, 'hana/task_detail.html', {'form': form, 'object': task})

Related

How to get a parameter from a form and insert it in the url with django?

I am a beginner with django.
I want to get a parameter that the user has to enter from a form. This parameter must be visible in the url except that the django server returns an error because the parameter is empty.
Here is what I did:
This is my template:
<form method="POST" action="{% url 'direct_aeg' id_aeg %}" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
<div class="input-field button"><input type="submit" name="submit_btn" value="Recherche AEG"></div>
</form>
this is my forms.py:
from django import forms
class Form_direct_aeg(forms.Form):
id_aeg = forms.IntegerField(label="N° AEG",required=True)
this is my views.py
def direct_aeg(request,id_aeg):
# doing some_stuff
def show_aeg_tool(request):
if request.method == 'POST':
form = Form_direct_aeg(request.POST)
if form.is_valid():
id_aeg = form.cleaned_data['id_aeg']
url = str(id_aeg)
return redirect(url)
else:
form = Form_direct_aeg()
return render(request, 'home/select_suivi_aeg.html', context={
'form': form,
})
this is my urls.py
path('a/b/c/d/direct_aeg/<int:id_aeg>', aeg.direct_aeg, name='direct_aeg'),
as soon as I load the page I get the following error:
Reverse for 'direct_aeg' with arguments '('',)' not found. 1 pattern(s) tried: ['a/b/c/d/direct_aeg/(?P<id_aeg>[0-9]+)\\Z']
I have this error because the id_aeg parameter must be initialized. How to solve this problem?

Django - Passing an extra argument from template to urls.py to class-based view

Basically, I would like to get some advice about how to transition from a form page back to a previous page when the form is submitted.
There are other posts on similar situations but none seem to show how to implement this using a class-based view, so any advice here would be most appreciated.
So far I have come up with the approach below. Here, I am trying to pass a parameter holding the URL of the previous page, from the template for the previous page to urls.py and then onto the view. However, I don't think I am using the correct syntax in urls.py as the value of the previous_url parameter in the view is simply "previous_url".
Link in the template for the table page
Edit
URL
path('entry/<int:pk>/edit/', EntryUpdateView.as_view(previous_url="previous_url"), name='entry_update'),
View
class EntryUpdateView(LoginRequiredMixin, UpdateView):
model = Entry
template_name = 'entry_update.html'
fields = ('source', 'target', 'glossary', 'notes')
previous_url = ""
def form_valid(self, form):
obj = form.save(commit=False)
obj.updated_by = self.request.user
obj.save()
return HttpResponseRedirect(self.previous_url)
Update form
<form method="POST" novalidate>
{% csrf_token %}
<div class="mb-3">
{{ form.source|as_crispy_field }}
</div>
<div class="mb-3">
{{ form.target|as_crispy_field }}
</div>
<div class="mb-3">
{{ form.glossary|as_crispy_field }}
</div>
<div class="mb-3">
{{ form.notes|as_crispy_field }}
</div>
<div class="text-center mt-3">
<button type="submit" class="btn btn-outline-primary mx-2">Update</button>
</div>
</form>
Error
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/entry/5131/edit/previous_url
If this helps anyone, I was able to get the value of previous_url within form_valid() using self.request.GET.get('previous_url').
def form_valid(self, form):
obj = form.save(commit=False)
obj.updated_by = self.request.user
obj.save()
previous_url = self.request.GET.get('previous_url')
return HttpResponseRedirect(previous_url)

User deactivation in Django

I am trying to allow users to deactivate their accounts on my django website. Here is what I have tried:
views.py
from django.contrib.auth.models import User
#login_required
def deactivate_user(request, username):
context = {}
try:
user = User.objects.get(username=username)
user.is_active = False
user.save()
context['msg'] = 'Profile successfully disabled.'
except User.DoesNotExist:
context['msg'] = 'User does not exist.'
except Exception as e:
context['msg'] = e.message
return render(request, 'index.html', context=context)
urls.py
path('deactivate-user/<slug:username>', deactivate_user, name='deactivate_user'),
base.html
<form action="{% url 'users:deactivate_user' slug=username.slug %}" method="post">
{% csrf_token %}
<button type="submit" class="active">Yes, Deactivate</button>
<button type="button" data-dismiss="modal">Cancel</button>
</form>
I am getting a NoReverseMatch error Reverse for 'deactivate_user' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['users/deactivate\\-user/(?P<username>[-a-zA-Z0-9_]+)$'] Have tried a few different parameters in the template but can't get anything to work.
You are saying
<form action="{% url 'users:deactivate_user' slug=username.slug %}" method="post">
slug isn't a keyword in your pattern, its a type, similar to <int:pk>, it should be username=username.slug

Multiple POST request is not working after submit

I am trying to use 2 post method in a single page one is for login and other one is for contact us
login is working fine but after submitting contact us the content of login and contact us page is gone
I tried to pass various type of dictionary but still, it's not working
app/views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from homePage.forms import SignInForm,DropUsaMessage
# Create your views here.
def homePage(request):
if request.method == 'POST' and 'SignIn' in request.POST:
sign_in_detail = SignInForm(request.POST)
if sign_in_detail.is_valid():
return render(request, "index2.html",{})
elif request.method == 'POST' and 'SendMessage' in request.POST:
message_detail = DropUsaMessage(request.POST)
if message_detail.is_valid():
return render(request, "index.html",{})
else:
sign_in_detail = SignInForm()
message_detail = DropUsaMessage()
context={
"form":sign_in_detail,
"forms":message_detail
}
return render(request, "index.html",context)
index.html
<div class="container contact-form">
<form method="post">
<h3>Drop Us a Message</h3>
{% csrf_token %}
{{ forms }}<br><br>
<div class="form-group">
<input type="submit" name="SendMessage" class="btnContact" value="Send Message" />
</div>
</form>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<img src="{% static 'img/sampleImage.jpg' %}" width="100%" height="100%" class="d-inline-block align-top" alt="">
</div>
<div class="col-md-4">
<form method="POST">
{% csrf_token %}
{{ form }}
<div class="form-check">
<span class="fpswd">Forgot password?</span>
</div>
<button type="submit" class="btn btn-primary" name="SignIn">Submit</button>
</form>
</div>
</div>
</div>
app/forms.py
from django import forms
from django.core import validators
class SignInForm(forms.Form):
email=forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Enter E-mail',"id": 'exampleInputEmail1'}))
password=forms.CharField(widget=forms.PasswordInput(attrs={"class":'form-control',"placeholder":'Enter Password',"id":'exampleInputPassword1'}))
class DropUsaMessage(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={"class":'form-control',"placeholder":'Your Name'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Your E-mail',"id": 'exampleInputEmail1'}))
phone = forms.IntegerField(widget=forms.NumberInput(attrs={"class":'form-control',"placeholder":'Your Phone Number'}))
message = forms.CharField(widget=forms.Textarea(attrs={"class":'form-control',"placeholder":'Type Your Message',"style":'width:100%; height: 150px'}))
Expected Result:
After filling up the contact us form the field will be there.
Actual result:
there is no field in Contact us(except Send Message button) and no field in SignInForm(no e-mail and no password).
Just follow the code flow and you'll notice that in the case of a POST request and "SignIn" in the post, you return the rendered "index2.html" template without any context (form and forms will be undefined in your template). Idem for the other case:
return render(request, "index2.html", {}) # empty context
Worse, if the form posted is not valid, you'll notice you only define one for the forms and not the other one, so when the code execution reaches the line context = {"form": ..., "forms": ...}, one of them will be undefined and your view will "crash", return a 500 error.
context = {'form': sign_in_detail, # sign_in_detail never defined for second "if"
'forms': message_detail} # message_detail never define for first "if"
In general, when a POST is successful, you should always redirect to another view (or the same view). That's the internet convention, in order to avoid page reload issues that would resubmit the same data. Do this:
return redirect('home') # or whatever your homepage url pattern is called
Also, it would make more sense to post your forms to different views (change the action attribute of each of your <form> tags) so you can process them in separate views which is cleaner code:
<form action="{% url 'create_message' %}" method="post">

User can post comment only after login in Django

I'm coding a news website,I want the user can submit the comment of the news only after they have logged in,if not,the website will return to login.html.
Now I have made it that only the user who have logged in can submit a comment,the issue is once I log off and submit a comment the error says:
Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x10fed10b8>>": "NewsComments.user" must be a "UserProfile" instance.
Note:I have rewrote the User models and rename it UserProfile .It works very well.
Here is my news/views.py:
def newsDetailView(request, news_pk):
news = News.objects.get(id=news_pk)
title = news.title
author = news.author_name
add_time = news.add_time
content = news.content
category = news.category
tags = news.tag.annotate(news_count=Count('news'))
all_comments = NewsComments.objects.filter(news=news)
comment_form = CommentForm(request.POST or None)
if request.method == 'POST' and comment_form.is_valid():
comments = comment_form.cleaned_data.get("comment")
comment = NewsComments(user=request.user, comments=comments, news=news)
comment.save()
return render(request, "news_detail.html", {
'title': title,
'author': author,
'add_time': add_time,
'content': content,
'tags': tags,
'category': category,
'all_comments': all_comments,
'comment_form': comment_form
})
Here is my news.detail.html
<form method="POST" action="">{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlTextarea1"><h5>评论 <i class="fa fa-comments"></i></h5></label>
<textarea id="js-pl-textarea" class="form-control" rows="4"
placeholder="我就想说..." name="comment"></textarea>
<div class="text-center mt-3">
<input type="submit" id='js-pl-submit' class="btn btn-danger comment-submit-button" value='Submit'>
</input>
</div>
</div>
</form>
Here is my urls.py:
path('-<int:news_pk>', newsDetailView, name="news_detail"),
You could use djangos login-required-decorator.
#login_required
def newsDetailView(request, news_pk):
...
EDIT to expand the idea from my comments.
You could have two views, one with the login_required decorator. (You could also use class-based-views (CBV) if you prefer)
def view_news_details(request, news_pk):
...
#login_required
def post_comments(request, news_pk):
...
Each view would have their own url:
url(r'^(?P<news_pk>[0-9]+)/$', views.view_news_details, name='view-details'),
url(r'^(?P<news_pk>[0-9]+)/comment/$', views.post_comments, name='comment'),
Then you can have only one template but with conditional rendering. This template will be rendered by the view views.view_news_details, but the form will send its data to the other view (note the forms action attribute).
... display the news details here ...
{% if request.user.is_authenticated %}
<form method="POST" action="{% url 'comment' news_instance.pk %}">
... here goes the content of the form ...
</form>
{% endif %}
Redirect the user to your login view before let him submit any data in your views.py :
# Codes here
if request.method == 'POST': # We separe those two "if statements", because
# We want to redirect the user to login even if the form is not valid, User can bypass your security concern
# For Django < 2.0, use it with () if request.user.is_authenticated():
if request.user.is_authenticated:
return redirect("login_url_name") # Or HttpResponseRedirect("login_url")
if comment_form.is_valid():
comments = comment_form.cleaned_data.get("comment")
# Rest of codes
Important
In your template, give access to the form to only authenticated users
{% if request.user.is_authenticated %}
<form method="POST" action="">{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlTextarea1"><h5>评论 <i class="fa fa-comments"></i></h5></label>
<textarea id="js-pl-textarea" class="form-control" rows="4"
placeholder="我就想说..." name="comment"></textarea>
<div class="text-center mt-3">
<input type="submit" id='js-pl-submit' class="btn btn-danger comment-submit-button" value='Submit' />
</div>
</div>
</form>
{% endif %}
You can check whether the requested user is logged-in or not by user.is_authenticated() method, which returns a boolean value.
Try the following snippet,
def newsDetailView(request, news_pk):
# code
if request.method == 'POST' and comment_form.is_valid():
if not request.user.is_authenticated():
return HttpResponse("Please do login")
comments = comment_form.cleaned_data.get("comment")
comment = NewsComments(user=request.user, comments=comments, news=news)
comment.save()
return render(request, "news_detail.html", {
'title': title,
'author': author,
'add_time': add_time,
'content': content,
'tags': tags,
'category': category,
'all_comments': all_comments,
'comment_form': comment_form
})