django transfer variable between html's - python

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 %}

Related

django url error when rendring a template

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

Class view returns object has no attribute 'rindex' error

I'm trying to rewrite my function based view to class based view. It raises this error:
.../test/User1
'UserDetailView' object has no attribute 'rindex'
The problem is probably obvious, I'm new in class based views.
So what to do to be able get any profile using url .../test/username?
My new view:
class UserDetailView(DetailView):
model = User
def get_object(self, queryset=None):
return get_object_or_404(self.model, pk=self.kwargs["pk"])
URLS.PY:
url(r'^test/(?P<username>[a-zA-Z0-9]+)/$', views.UserDetailView(),name="user_detail"),
And template:
{% extends "base.html" %}
{% block content %}
{{ userprofile.as_p }}
{% endblock %}
My old view is this:
def get_user_profile(request, username):
user = User.objects.get(username=username)
jobs = user.jobs.all()
table = MyJobsTable(jobs)
context = {
'my_jobs': table,
"user": user
}
return render(request, 'auth/profiles/my-profile.html', context=context)
And HTML:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load render_table from django_tables2 %}
{% block content %}
{% if user.is_authenticated %}
<h3>{% if user.userprofile.is_translator %} Prekladateľský účet: {% else %} Štandardný
účet: {% endif %}{{ user.username }} </h3>
<ul>
<li>Username: {{ user.username }}</li>
<li>First name: {{ user.first_name }}</li>
<li>Last name: {{ user.last_name }}</li>
<li>Email: {{ user.email }}</li>
<li>Telephone: {{ user.userprofile.telephone }}</li>
<li>Languages: {{ user.userprofile.languages.as_p }}</li>
{# TODO: DOPLNIT ATRIBUTY + ked je aj translator#}
</ul>
{% if user.jobs %}
<p>My Jobs</p>
{% render_table my_jobs %}
{% else %}
<p>You have no jobs</p>
{% endif %}
<form class="navbar-form navbar-right" action="/edit-profile" method="get">
<button type="submit" class="btn btn-success">Edit Your Profile</button>
</form>
<form class="navbar-form navbar-right" action="/register-as-translator" method="get">
<button type="submit" class="btn btn-success">Become A Translator</button>
</form>
{% endif %}
{% endblock %}
URLS.PY:
url(r'^profile/(?P<username>[a-zA-Z0-9]+)/$', views.get_user_profile)
The issue is in your urls.py. With a class-based view, you always need to use the as_view classmethod:
url(r'^test/(?P<username>[a-zA-Z0-9]+)/$', views.UserDetailView.as_view(), name="user_detail"),

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

Setting up Django Form Wizard

I'm attempting to set up a Django Form Wizard, but I'm having trouble getting it to work. I've followed the example, from the Django website, but can't get anything to work. When I go to the URL that should have my multistep form, only the template html thats extended shows up. What am I doing wrong here?
FORMS.PY
class ScheduleDate(forms.Form):
date = forms.CharField()
class ScheduleTime(forms.Form):
time = forms.CharField()
VIEWS.PY
FORMS =[('date', ScheduleDate),
('time', ScheduleTime)]
TEMPLATES = [('date', 'main/schedule_date2.html'),
('time', 'main/schedule_time.html')]
class ContactWizard(SessionWizardView):
def get_template_name(self):
return TEMPLATES[self.steps.current]
def done(self, form_list, **kwargs):
print 'testing'
return HttpResponseRedirect('main/home.html')
URLS.PY
urlpatterns = patterns('',
url(r'^checkout/$', views.ContactWizard.as_view([ScheduleDate, ScheduleTime]), name='checkout'))
SCHEDULE_DATE2.HTML(From the Django Website)
{% extends "base.html" %}
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
<input type="submit" value="{% trans "submit" %}"/>
</form>
{% endblock %}
Thanks!

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