Is it possible to render an HTML page without having a view model in Django if a page is going to display only static HTML?
Basically, I want to delete an issue from a webpage and then show a 'successfully deleted' static HTML page after deleting.
But I got blew error, anyone could help?
NoReverseMatch at /project/1/issue/14/delete_issue/
Reverse for 'nice_delete.html' not found. 'nice_delete.html' is not a valid view function or pattern name.
view.py
def delete_issue(request,project_id,issue_id):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
issue = get_object_or_404(Issue,id=issue_id)
issue.delete()
return redirect(reverse('project:issue_tracker:nice_delete.html'))
urls.py
urlpatterns =[
path('',views.list_of_issue,name='list_of_issue'),
path('<int:issue_id>/',views.issue_detail,name='issue_detail'),
path('<int:issue_id>/comment',views.add_comment,name='add_comment'),
path('new_issue/',views.new_issue,name='new_issue'),
path('<int:issue_id>/edit_issue/',views.edit_issue,name='edit_issue'),
path('<int:issue_id>/delete_issue/',views.delete_issue,name='delete_issue'),
]
nice_delete.html
{% extends 'base.html' %}
{% block content %}
<p>Successfully delete this issue</p>
{% endblock %}
You can use TemplateView for this. Just add to your urlpattern:
from django.views.generic import TemplateView
urlpatterns =[
path('',views.list_of_issue,name='list_of_issue'),
path('<int:issue_id>/',views.issue_detail,name='issue_detail'),
path('<int:issue_id>/comment',views.add_comment,name='add_comment'),
path('new_issue/',views.new_issue,name='new_issue'),
path('<int:issue_id>/edit_issue/',views.edit_issue,name='edit_issue'),
path('<int:issue_id>/delete_issue/',views.delete_issue,name='delete_issue'),
path('deleted/', TemplateView.as_view(template_name="nice_delete.html"), name='success_deletion'),
]
And use success_deletion url in delete_issue view for redirection:
def delete_issue(request,project_id,issue_id):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
issue = get_object_or_404(Issue,id=issue_id)
issue.delete()
return redirect('success_deletion')
Related
I'm having trouble getting my register application in Django to work. I am using the built-in UserCreationForm form. I can go to the URL and the form shows up but when I put info into the fields and click the submit button nothing happens. It should pop up an error screen saying "missing the csrf_field" (I know this because I'm following TechWithTim's tutorial and that's what happens to him). But when I click the "Register" button nothing happens.
views.py:
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def register(response):
form = UserCreationForm()
return render(response, "register/register.html", {"form":form})
register.html:
{% extends "main/base.html" %}
{% block title %}Create an Account{% endblock %}
{% block content %}
<form method="POST" class="form-group">
{{form}}
<button type="submit" class="btn btn-success">Register</button>
</form>
{% endblock %}
urls.py:
from django.contrib import admin
from django.urls import path, include
from register import views as v
urlpatterns = [
path('', include("main.urls")),
path("register/", v.register, name="register"),
path('admin/', admin.site.urls),
]
main/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("<int:id>", views.index, name='index'),
path("", views.home, name='home'),
path("create/", views.create, name='create'),
]
I added the application to my settings.py file as well.
This is my first question on here and I tried to format it properly so sorry if I didn't
In order for Django to recieve the data the user entered in the form, you need to pass the request's POST data to the form, if it exists. That would look like this:
form = UserCreationForm(response.POST)
But note that response.POST will not exist if it's not a POST request. (For example, if the user is viewing the form for the first time.) The Django docs have an example of how to process form data.
Alternatively, you can look at the tutorial you're using, which has an example of how to get the POST data out of the form:
# views.py
from django.shortcuts import render, redirect
from .forms import RegisterForm
# Create your views here.
def register(response):
if response.method == "POST":
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
return redirect("/home")
else:
form = RegisterForm()
return render(response, "register/register.html", {"form":form})
(Source.)
I am trying to handle a 404 http response error on the site. I want my 404.html content to be displayed, but for some reason when I run my local host I do get the response displayed, but my site doesn't look the same as in my contents aren't being displayed as they should. I don't know why this is happening, but I want to make sure I am properly calling in my handler. Any suggestions would be appreciated.
My views.py
def handler404(request, exception):
return render(request, 'webpage/404.html')
My 404.html
{% extends "webpage/base.html" %}
{% block content %}
{% load static %}
<h1>404 Error</h1>
{% endblock %}
My Url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('webpage.urls')),
]
handler404 = views.handler404
Here is the ref to handle the custom error page: https://docs.djangoproject.com/en/3.0/topics/http/views/#customizing-error-views
In the main py:
handler404 = 'app_name.views.handler404'
In the views add :
def handler404(request, exception):
return render(request, "webpage/404.html", {})
I am trying to create a simple Django webpage that uses forms, but my forms are not visible. I have read all of the Django docs and read multiple questions related to this issue, but I have found no solution that fixes my problem.
Here are the relevant files:
views.py
from django.shortcuts import render
from .forms import FileForm
with open('calendar.txt') as f:
file_content = f.read()
def home(request):
return render(request, 'main/index.html',{'file_content':file_content})
def form_get(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = FileForm(request.POST)
# check whether it's valid:
if form.is_valid():
pass
else:
form = FileForm()
return render(request, 'index.html', {'form': FileForm.form})
urls.py
from django.conf.urls import url
from django.contrib import admin
from main import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
]
index.py
{% extends "base.html" %}
{% block content %}
<h1>Welcome to the calendar!</h1>
<form action="/#" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
{{form}}
{% endblock content %}
Link to program
From what I have read, I suspect there may be an issue in the urls.py file, but I've been looking over it many times and I haven't found anything wrong. Any thoughts?
Try
def form_get(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = FileForm(request.POST)
# check whether it's valid:
if form.is_valid():
pass
else:
form = FileForm()
return render(request, 'main/index.html', {'form': form})
See how I changed the context for the render from {'form': FileForm.form} to {'form': form}. The path to the index.html file was also wrong.
After fixing the view, you need to add an actual URL to go to it. Your current URL has
url(r'^$', views.index, name='home'),
Note how is using views.index and not views.form_get. Change the URL to use form_get and it will work.
url(r'^$', views.form_get, name='home'),
Don't know if you want to have / go to the form, or if you would rather have / still go to home, where you have a link to the form. But in that case, you do not want to share the same index.html file.
But seems like you may be trying to merge those two, but in that case, you need a single view, which can both show the content of the file, and ask for the file. But will be easier if you have two views, and leave the form to just take the input, and then redirect to the second view to show the results.
I got an error that,
Page not found (404)
Request Method: GET
Request URL: `http://localhost:8000/accounts/registration/accounts/registration/accounts/registration/accounts/profile.html` .
I think routes are wrong But I cannot understand how to fix the routes.
In accounts app,I wrote
in urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth.views import login, logout
urlpatterns = [
url(r'^login/$', login,
{'template_name': 'registration/accounts/login.html'},
name='login'),
url(r'^logout/$', logout, name='logout'),
url(r'^regist/$', views.regist,name='regist' ),
url(r'^regist_save/$', views.regist_save, name='regist_save'),
url(r'^registration/accounts/registration/accounts/profile.html$', views.regist_save, name='regist_save'),
]
in views.py
#require_POST
def regist_save(request):
form = RegisterForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
context = {
'user': request.user,
}
return redirect('registration/accounts/profile.html', context)
context = {
'form': form,
}
return render(request, 'registration/accounts/regist.html', context)
in accounts(child app)/templates/registration/accounts/profile.html directory,
{% extends "registration/accounts/base.html" %}
{% block content %}
user.username: {{ user.username }}<hr>
user.is_staff: {{ user.is_staff }}<hr>
user.is_active: {{ user.is_active }}<hr>
user.last_login: {{ user.last_login }}<hr>
user.date_joined: {{ user.date_joined }}
{% endblock %}
You have some serious misunderstandings here.
You can't have a template without a view. You have written a template for the profile, but you haven't written a view. You need the view that loads the profile data and then renders the profile.html template.
Secondly, your URL has nothing to do with the template location; as you have done in regist_save, you should define a sensible URL pointing to that view - for the profile, you probably want something like r'^profile/$'.
So, the fifth entry in your urls.py should be:
url(r'^profile/$', views.profile, name='profile'),
and you need a corresponding function named profile in views.py.
Finally, when you redirect you need to use an actual URL entry - again, it has nothing to do with templates. So in your regist_save view, you should do:
return redirect('profile')
I am getting the following error:
NoReverseMatch at /lld/new/
Reverse for 'display_lld' with arguments '()' and
keyword arguments '{'slug': u'stack-overflow-new-document'}' not found.
0 pattern(s) tried: []
I can't get to the bottom of it, though I think it has something to do with either my url regex or the document.slug variable passed to the index.html template in views.py.
views.py:
from django.shortcuts import get_object_or_404, render, redirect
from .models import Document
from .forms import DocumentForm
def index(request):
document_list = Document.objects.order_by('-date_updated')
context = {'document_list': document_list}
return render(request, 'lld/index.html', context)
def display_lld(request, slug):
document = get_object_or_404(Document, slug=slug)
return render(request, 'lld/display_lld.html', {'document': document})
def new_lld(request):
if request.method == "POST":
form = DocumentForm(request.POST)
if form.is_valid():
document = form.save(commit=False)
document.save()
return redirect('display_lld', slug=document.slug)
else:
form = DocumentForm()
return render(request, 'lld/new_lld.html', {'form': form})
site urls.py:
urlpatterns = [
url(r'^lld/', include('lld.urls', namespace="lld")),
url(r'^admin/', include(admin.site.urls)),
]
app urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
# example: /lld/
url(r'^$', views.index, name='index'),
# example: /lld/new/
url(r'^new/$', views.new_lld, name='new_lld'),
# ex: /lld/customername-projectname/
url(r'^(?P<slug>([\w-]+))/', views.display_lld, name='display_lld'),
]
index.html:
{% if document_list %}
<ul>
{% for document in document_list %}
<li>{{ document.customer }} / {{ document.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No documents are available.</p>
{% endif %}
Create New LLD
The form creates the new document fine, it shows up in the admin. But when I click on the forms save button it brings up the NoReverseMatch error rather than redirecting back to the created document. The newly created document is listed on the index page and I can navigate to it by clicking on it's link there, it just appears to throw the error in the form redirect.
When calling redirect, you have left out the lld namespace. You need to include the namespace when you use redirect or reverse, the same way as you already do when you use the {% url %} tag in your templates:
return redirect('lld:display_lld', slug=document.slug)
from django.core.urlresolvers import reverse
return redirect(reverse('lld:display_lld', args=[document.slug]))