I aim to redirect the view after the form has been saved. However django keeps throwing a NoReverseMatch error. Is there a step that I've missed or a misconfiguration?
views.py
def add_carpet(request):
context_dict = {}
carpet_form = forms.CarpetForm()
if request.method == "POST":
carpet_form = forms.CarpetForm(request.POST)
if carpet_form.is_valid():
carpet = carpet_form.save()
return redirect(reverse(
"dashboard_add_images",
kwargs={
"model_type": "carpet",
"id": carpet.id
}
))
context_dict["carpet_form"] = carpet_form
return render(
request,
'dashboard/add_carpet.html',
context_dict
)
def add_images(request, model_type, id):
...
add_images.hml
{% extends 'layouts/dashboard_base.html' %}
{% load django_bootstrap5 %}
{% load static %}
{% block title %}Add Images{% endblock title %}
{% block content %}
<div class="row">
<div class="col justify-content-end">
<h1 class="heading half_space text-muted">
Add Images for the {model}
<span class="divider-left"></span>
</h1>
</div>
</div>
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript %}
{# Display django.contrib.messages as Bootstrap alerts #}
{% bootstrap_messages %}
{# Display a form #}
<form enctype="multipart/form-data" action="{% url 'dashboard_add_images' %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% bootstrap_button button_type="submit" content="OK" %}
</form>
{% endblock content %}
From above you can see I added the enctype on the form but still no change.
urls.py
urlpatterns = [
path('add_carpet', views.add_carpet, name="dashboard_add_carpet"),
path('add_images/<str:model_type>/<uuid:id>', views.add_images, name="dashboard_add_images"),]
An example redirect url after a form has been submitted is this:
http://127.0.0.1:8000/dashboard/add_images/carpet/97afd259-6ec4-48fc-869f-2a00bbe29c70
Error:
Reverse for 'dashboard_add_images' with no arguments not found. 1 pattern(s) tried: ['dashboard/add_images/(?P<model_type>[^/]+)/(?P<id>[^/]+)$']
Related
I have this add page which uses a django form to get information which i am trying to store within "tasks" list and display in the todo html page.
i believe all my syntax is correct but it is not displaying the list of tasks when I submit the form.
on cmd it detects a GET request every time i submit the form, shouldnt it be saying post?
views:
from django.shortcuts import render
from django import forms
tasks = []
class newTaskForm(forms.Form):
task = forms.CharField(label="new task")
# Create your views here.
def index(request):
return render(request, "tasks/todo.html", {
"tasks": tasks
})
def add(request):
if request.method == "POST":
form = newTaskForm(request.POST)
if form.is_valid():
task = form.cleaned_data["task"]
tasks.append(task)
else:
return render(request, "tasks/add.html", {
"form": form
})
return render(request, "tasks/add.html", {
"form": newTaskForm
})
add:
{% extends "tasks/layout.html" %}
{% block body %}
<form action="{% url 'tasks:add' %}">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
Veiw list
{% endblock %}
todo:
{% extends "tasks/layout.html" %}
{% block body %}
<h1> To Do List</h1>
<ul>
{% for task in tasks %}
<li> {{ task }}</li>
{% endfor %}
</ul>
Add items
{% endblock %}
as #Iain Shelvington suggested, you need to put method="post" as
{% block body %}
<form method="post" action="{% url 'tasks:add' %}">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
Veiw list
{% endblock %}
**Can someone please help me solve this problem I just started learning Django.
I keep getting getting "PAGE NOT FOUND " whenever i open/click the list/entries
In my "entries" folder i have
Css.md
Django.md
Git.md
Python.md
HTML.md**
screenshot of "Page not found"
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:entry>", views.entry, name="entry"
views.py
from django import forms
class NewEntryForm(forms.Form):
title = forms.CharField(max_length=100)
content = forms.CharField(widget=forms.Textarea)
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def entry(request, entry):
entries = util.get_entry(entry)
if entries is None:
return render(request, "encyclopedia/error.html", {
"message1": "Sorry",
"message2": "your requested page was not found "
})
return render(request, "encyclopedia/index.html", {
"content": entries,
"form": NewEntryForm
})
index.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia - {{title}}
{% endblock %}
{% block body %}
<h1>All Pages</h1>
<ul>
{% for entry in entries %}
<li></li>
{% endfor %}
</ul>
{% endblock %}
entry.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia - {{title}}
{% endblock %}
{% block body %}
<div class="container">
<div class="row">
{% if not content%}
<div>Sorry, your requested page was not found </div>
{% else %}
{{ content | safe }}
<div>Edit this entry</div>
{% endif %}
</div>
</div>
{% endblock %}
edit anchor tag in entry.html. URL is given wrong, Do this
<div><a href="{% url 'entry' entry %}>Edit this entry</a></div>
instead of
<div><a href="{% url 'edit' entry %}>Edit this entry</a></div>
you forget to close "".
write this:
<div>Edit this entry</div>
simple.....
I'm working on a password reset feature for my django application.
I'm following along using this tutorial: https://www.youtube.com/watch?v=-tyBEsHSv7w&t=924s
Everything works great but I get this error when I give the email and press enter on password-reset/:
NoReverseMatch at /password-reset/
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name.
Here's my main/urls.py:
urlpatterns = [
path("password-reset/", auth_views.PasswordResetView.as_view(template_name='main/password_reset_form.html'),name="password_reset"),
path("password-reset/done/", auth_views.PasswordResetDoneView.as_view(template_name='main/password_reset_done.html'),name="password_reset_done"),
path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='main/password_reset_confirm.html'),name="password_reset_confirm"),
path("password-reset-complete/", auth_views.PasswordResetCompleteView.as_view(template_name='main/password_reset_complete.html'),name="password_reset_complete"),
]
password_reset_complete.html
{% extends 'main/header.html' %}
{% block content %}
<div class = "alert alert-info">Your password has been reset.</div>
Sign In Here
{% endblock %}
password_reset_form.html
{% extends 'main/header.html' %}
{% block content %}
<div class="container">
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button style="background-color:darkblue; color:white" class="btn btn-outline-info" type="submit">Request Password Reset</button>
</form>
</div>
{% endblock %}
password_reset_done.html
{% extends 'main/header.html' %}
{% block content %}
<div> An email has been sent with instructions to reset your password</div>
{% endblock %}
password_reset_confirm.html
{% extends 'main/header.html' %}
{% block content %}
<div class="container">
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button style="background-color:darkblue; color:white" class="btn btn-outline-info" type="submit">Reset Password</button>
</form>
</div>
{% endblock %}
The tutorial didn't change anything in the views.py file if I'm not mistaken.
I've done everything in the tutorial yet I still get this error.
Thanks
In some of my blog posts using django and markdown2, I am trying to include a form as follows:
views.py:
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if not instance.published:
raise Http404
return render(request, "posts/post_detail.html", {'instance': instance})
My template post_detail.html contains a {{ instance.get_markdown }} variable:
{% extends "base.html" %}
{% block body_content %}
<div>
{{ instance.get_markdown }}
</div>
{% endblock body_content %}
base.html:
<html>
<body>
{% block body_content %}
{% endblock body_content %}
</body>
</html>
models.py:
import markdown2
class Post(models.Model):
...
text = models.TextField(verbose_name=_("Text"))
...
def get_markdown(self):
return mark_safe(markdown2.markdown(self.text))
Example for a saved text in Post:
### Example
<form method = "POST">
{% csrf_token %}
First name:<input type="text" name="firstname">
<input type="submit" value="Submit">
</form>
This way, the page simply shows the string "{% csrf_token %}" within the form. How can I render the post with csrf protection?
My temporary solution is:
post_detail.html:
{% extends "base.html" %}
{% block body_content %}
<div>
{{ instance.get_markdown_text }}
</div>
{% if instance.form %}
<div>
<form method = "POST">{% csrf_token %}
{{ instance.get_markdown_form }}
</form>
</div>
{% endif %}
{% endblock body_content %}
models.py:
import markdown2
class Post(models.Model):
...
text = models.TextField(verbose_name=_("Text"))
form = models.TextField(verbose_name=_("Form"), blank=True, null=True)
...
def get_markdown_text(self):
return mark_safe(markdown2.markdown(self.text))
def get_markdown_form(self):
return mark_safe(markdown2.markdown(self.form))
I'm not very happy with this solution, because of the unnecessary field "form" and method get_markdown_form in Post and post_detail.html.
I am writing an application with django. everything has been working fine and I have been working in another page of the application then I decided to come back to the home page and I got this error.
Reverse for 'more' with keyword arguments '{u'slug': u''}' not found. 1 pattern(s) tried: ['(?P<slug>[-\\w]+)/$']
Everything was working perfectly and I cant seen to understand why.
If I change the template to another template lets say hello.html the whole url responds well but once I change it back to index.html I get that same error. any help would be appreciated
form.py
from django import forms
from posts.models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
"title",
"content",
"image",
"draft",
"publish",
]
views.py
def index(request):
results = Post.objects.all().filter(draft=False).filter(publish__lte=timezone.now())
que = request.GET.get("q")
if que:
results =results.filter(
Q(title__icontains=que)|
Q(content__icontains=que)).distinct()
paginator = Paginator(results, 8) # Show 25 contacts per page
pages ="page"
page = request.GET.get('page')
try:
query = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
query = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
query = paginator.page(paginator.num_pages)
context = {
"objects": query,
"pages": pages
}
template = 'index2.html'
return render(request,template,context)
html
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<h1>This is Home</h1>
{% include 'messages.html'%}
<form method="GET" action="">
{% csrf_token %}
<input type="text" name="q" value="{{ request.GET.q }}" placeholder="search" >
<input type="submit" name="submit" value="Go!">
</form>
{% for obj in objects %}
<h1> {{ obj.title }}</h1><br>
{% if obj.image %}
<img src="{{ obj.image.url }}" alt="{{ obj.title }}" width="250" height="250"><br>
{% endif %}
{{ obj.content|safe|truncatewords:20 }}
{{ obj.timestamp }}<br>
{{ obj.updated }}<br>
{% endfor %}
<br>
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ objects.number }} of {{ objects.paginator.num_pages }}.
</span>
{% if objects.has_next %}
next
{% endif %}
</span>
</div>
{% endblock %}
Absolute url in model
def get_absolute_url(self):
return reverse("more", kwargs={"slug": self.slug})
url pattern
url(r'^$', posts_views.index, name='index'),