django url error when rendring a template - python

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'),

Related

URL with multiple parameters throws a NoReverseMatch error

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>[^/]+)$']

Reverse for 'favorite' with arguments '('',)' not found, following Bucky's Django tutorial on YouTube

I keep getting NoReverseMatch at /music/2/ error, and it's pointing me to the parent template that i'm inheriting from, base.html, but i can't find anything wrong with it. I know it's probably annoying when someone asks you to search for errors, but maybe someone can easily see what i'm unable to see
{% extends "music/base.html" %}
{% block content %}
<p> Album : {{one_album}} </p>
<p> Song list : </p>
{% if somethings_wrong %}
<p> {{ somethings_wrong }} </p>
{% endif %}
<form action = "{% url 'music:favorite' album.id %}" method="post" >
{% csrf_token %}
{% for song in album_entries %}
<input type="radio" id="song{{forloop.counter}}" name="song" value="{{ song.id }}">
<label for="song{{ forloop.counter }}">
{{ song.song_title }}
{% if song.is_favorite %} #afterwards, set this explicitly to true, for learning purposes
<img src="https://i.imgur.com/olM72b8.png"/> #check if this slash is necessary later
{% endif %}
</label><br>
{% endfor %}
<input type="submit" value="Favorite">
</form>
{% endblock content %}
Here's the base.html
<p>
Link to the homepage
</p>
{% block content %}
{% endblock content %}
Here's the Views.py :
from django.shortcuts import render
from django.http import HttpResponse
from .models import Album, Song
def index(request):
albums = Album.objects.all()
context = {'albums': albums}
return render(request, 'music/index.html', context)
def detail(request, album_id):
# show album and every entry in that album.
one_album = Album.objects.get(id=album_id)
album_entries = one_album.song_set.all()
context = {'one_album' : one_album, 'album_entries' : album_entries}
return render(request, "music/album.html", context)
# Create your views here.
def favorite(request, album_id):
one_album = Album.objects.get(id=album_id)
try:
context = {'one_album' : one_album}
selected_song = one_album.song_set.get(id=request.POST["song"])
except(KeyError, Song.DoesNotExist):
somethings_wrong = "Something's not right with your choice"
context = {'one_album' : one_album, 'somethings_wrong' : somethings_wrong}
return render(request, "music/album.html", context)
else:
selected_song.is_favorite = True
selected_song.save()
return render(request, "music/album.html", context)
i think error is somewhere here, urls.py and models.py are pretty simple. I've added is_favorite booleanfield to Song class, which is False by default, and urls.py is pretty straightforward
path('<int:album_id>/favorite', views.favorite, name='favorite')
variable that you want to refer to is one_album
but you are calling it album.
change
<form action = "{% url 'music:favorite' album.id %}" method="post" >
to
<form action = "{% url 'music:favorite' one_album.id %}" method="post" >

django transfer variable between html's

Hi i am trying to create a search engine and i need to make the table id stay in the link.
In my CrawledTables have all the tables with the id...and i need to pass that id into the var pk through the links...cause then i request to get that pk and use the pk to get the table name. and then use the table name to get the data inside the table i searched for...and make a search engine inside those table info.
Error:
Reverse for 'table_search' with no arguments not found. 1 pattern(s) tried: [u'search/(?P<pk>\\d+)/$']
This is my views.py
def search_form(request):
return render(request, 'search/search.html')
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
name = Crawledtables.objects.filter(name__icontains=q)
return render(request, 'search/results.html', {'name': name, 'query': q})
else:
return HttpResponse('Please submit a search term.')
def search_form_table(request):
return render(request, 'search/search_table.html', {'tbl_nm': table_name})
def search_table(request, pk):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
table_name = Crawledtables.objects.get(id=pk)
print table_name
t = create_model(table_name.name)
print t
title = t.objects.filter(title__icontains=q)
print title
return render(request, 'search/results_table.html', {'tbl_name': table_name,
'details': title,
'query': q})
else:
return HttpResponse("Please submit a search term!")
this is my search/urls.py
urlpatterns = [
url(r'^results$', views.search, name='search'),
url(r'^$', views.search_form, name='form'),
url(r'^(?P<pk>\d+)/$', views.search_form_table, name='table_search'),
url(r'^(?P<pk>\d+)/results$', views.search_table, name='table_results'),
]
this is my search.html
<form action="/search/results" method="GET">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
results.html
<p> You searched for: <strong>{{ query }}</strong></p>
{% if name %}
<p> Found {{ name|length }}</p>
<ul>
{% for nm in name %}
<li>{{ nm.name }} {{ nm.date }}</li>
{% endfor %}
</ul>
{% else %}
<p> No results found</p>
{% endif %}
search_table.html
<form action="/search/{{ pk }}/results" method="GET">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
results_table.html
<p> You searched for: <strong>{{ query }}</strong></p>
{% if details %}
<p> Found {{ details|length }}</p>
<ul>
{% for list in details %}
<li> {{ list.title }}</li>
{% endfor %}
</ul>
{% else %}
<p> No results found</p>
{% endif %}
You are getting the error because of <a href="{% url 'search:table_search' %}"> in your results.html. Change the href like this.
{% for nm in name %}
<li>{{ nm.name }} {{ nm.date }}</li>
{% endfor %}

my haystck results are not displaying on the results page

I am new to python and django and I was following a tut with major errata. right now I am trying to get the results page to display my results. This is not my code, it's from a tutorial. Here is my code.
my views.py
def post_search(request):
form = request.GET.get('q')
results = SearchQuerySet().models(Post).filter(content=form)
# count total results
total_results = results.count()
template = 'blog/post/search.html',
context = {
'form': form,
'results': results,
'total_results': total_results
}
return render(request, template, context)
my search.html
{% extends "blog/base.html" %}
{% block title %}Search{% endblock %}
{% block content %}
{% if request.GET %}
<h1>Posts containing "{{ form.query }}"</h1>
<h3>Found {{ total_results }} result{{ total_results|pluralize}}</h3>
{% for result in results %}
{% with post=result.object %}
<h4>{{ post.title }}</h4>
{{ post.body|truncatewords:5 }}
{% endwith %}
{% empty %}
<p>There are no results for your query.</p>
{% endfor %}
<p>Search again</p>
{% else %}
<h1>Search for posts</h1>
<form action="." method="get">
<div>
<div class="input-group">
<input type="text" class="form-control" autocomplete="off" name="q" id="search" placeholder="search" value="{{ request.GET.q }}">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">search</button>
</span>
</div><!-- /input-group -->
<ul class="list-group" id="search-results" style="margin: 5px 0 0 0; width: 325px">
</ul>
</div>
</form>
{% endif %}
{% endblock content%}
my post_text.txt
{{ object.title }}
{{ object.tags.all|join:", " }}
{{ object.body }}
search_indexes.py
from haystack import indexes
from .models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
publish = indexes.DateTimeField(model_attr='publish')
# title_auto = indexes.EdgeNgramField(model_attr='title')
# content_auto = indexes.EdgeNgramField(model_attr='content')
def get_model(self):
return Post
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.all()
the only thing that shows on the page after I run a search is
Posts containing ""
Found 1 result
Search again
and if I do this
{{results}}
it returns this
[<SearchResult: blog.post (pk='2')>]
where it says post containing a name will show
found results returns a number which lets me know that the results are working
any and all help or guidance in the right direction is greatful. Tried to read the docs. They seem so vague to me. and as I said I am a novice.and there are only video on the topic and that with frank hibbert and he uses it with ajax

Django Multiple File upload failing

I have a single HTML page with 2 Django Forms in it, all in the same <form>..</form> tag. Everything works great, except when I try to upload multiple files.
Each form has their own image, and for some reason I can only save the image from the first form. Other data from the second form still gets saved, but without any image. I don't see any errors or exception raised, so I don't know what's going wrong :s.
Here's my views.py
def display_form(request):
if request.method == 'POST':
form_team = TeamForm(request.POST, request.FILES, prefix="team")
form_player = PlayerForm(request.POST, request.FILES, prefix="play")
#form_ketua = KetuaForm(request.POST, request.FILES, prefix="ketua")
if all([form.is_valid() for form in [form_team, form_player]]):
# save Team data first, overwrite if exists
try:
team = Team.objects.get(kota=form_Team.cleaned_data['name'])
team.profil = form_Team.cleaned_data['profil']
team.save()
except Team.DoesNotExist:
team = Team(**form_Team.cleaned_data)
team.save()
play = form_Player.save(commit=False)
play.name = team
play.save()
else:
form_team = TeamForm(prefix="team")
form_player = PlayerForm(prefix="play")
#form_ketua = KetuaForm(prefix="ketua")
print "a"
# list with tuple (form, legend) to pass as context
forms = [(form_Team, 'Team Data'),
(form_Player, 'Player Profile'),
]
return render_to_response(
'form/team.html',
{
'formlist': forms,
},
)
What am I doing wrong?
EDIT: Here's my template
{% extends "base.html" %}
{% block title %}Form - {{ title }}{% endblock %}
{% block content %}
<form action="." method="POST" enctype="multipart/form-data">{% csrf_token %}
{% for formitem in formlist %}
{% if formitem.1 %}
<fieldset>
<legend>{{ formitem.1 }}</legend>
{% endif %}
{{ formitem.0.non_field_errors }}
{% for field in formitem.0.visible_fields %}
<div class="formfield">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
{% if formitem.1 %}
</fieldset>
{% endif %}
{% endfor %}
<div id="formbuttons">
<input type="submit" value="Submit" class="button">
<input type="reset" value="Reset" class="button">
</div>
</form>
{% endblock %}
looks like you are missing a play.save() (you save the form with commit=False)

Categories

Resources