Django Tutorials part 3: Error while creating view and template - python-3.x

I started learn Django (1.11) and I follow Django Tutorials. In this part I should create dynamic view (index method) with template. But after I created template
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
and index view that uses template
from django.http import HttpResponse
from django.template import loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
I've go an Error:
*NameError at /polls/
*global name 'latest_question_list' is not defined**

Try this one:
...
from django.template import loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {'latest_question_list': latest_question_list, }
return HttpResponse(template.render(context, request))

Try this instead:
from django.shortcuts import render
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request,'polls/index.html',context)

Related

display images in djangoi template from database in Django3

Here i am using Django 3 and Python 3.7 where i want to display the the signature as image in my html page
Here is my views.py
def jobsignature_view(request, pk):
job = CreateJob.objects.filter(id=pk)
job_data={}
for val in job_id:
job_data['job_id'] = pk
job_data['signature'] = val.signature
......
....
Here is my models.py
class Cre(models.Model):
signature = models.TextField(default='', blank=True, null=True)
here in my database it is saving as
id signature
1 b'b3V0cHV0'
Here is my template.html
I confirm that this work has been completed:
<div class="span12">
{{ form.media }}
{% if job_data.signature != None and job_data.signature != '' %}
<img src="data:image/png;base64,{{job_data.signature}}"/>
{% endif %}
</div>
here is how its is displaying
How can i make my signature display here please help me
In your life I think for a search on a primary key it is more appropriate to use get(), your primary key is unique, we expect only one object. Filter() is used to return a queryset of otherwise multiple items :
def jobsignature_view(request, pk):
job = CreateJob.objects.get(id=pk)
return render(request, 'myapp/yourpage.html', {'job': job})
In the html template :
{% if job %}
<img src="{{job.signature}}"/>
{% endif %}
For the model I think you should use ImageField :
from django.core.files.storage import FileSystemStorage
from django.db import models
fs = FileSystemStorage(location='/media/photos')
class CreateJob(models.Model):
...
signature = models.ImageField(storage=fs)

django list_filter is not scrollable

I have a long list of elements (50 elements) and I wanted to use that as a list_filter in django admin panel. But when I use this list, on very right side where FILTER panel appears I can see only 20 items and it is not scrollable so rest of 30 is hidden. How can I get those 30 items in FILTER section or How scrolling will be possible so that all 50 items can be viewed.
You can create a custom filter for your field and use a dropdown as selector.
I strongly recommend using https://github.com/mrts/django-admin-list-filter-dropdown which already provide a couple of filters.
If you want to create your own:
admin.py
from django.contrib.admin.filters import RelatedOnlyFieldListFilter
class RelatedOnlyDropdownFilter(RelatedOnlyFieldListFilter):
template = 'filters/related_filter.html'
#admin.register(ModelName)
class YourModelAdmin(admin.ModelAdmin):
list_filter = (
('field', RelatedOnlyDropdownFilter),
)
related_filter.html
{% load i18n %}
<script type="text/javascript">var filter_by_select = function(opt) { window.location = window.location.pathname + opt };</script>
<h3>{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}</h3>
<ul class="admin-filter-{{ title|cut:' ' }}">
{% if choices|slice:"4:" %}
<li>
<select class="form-control"
onchange="filter_by_select(this.options[this.selectedIndex].value)">
{% for choice in choices %}
<option{% if choice.selected %} selected="selected"{% endif %}
value="{{ choice.query_string|iriencode }}">{{ choice.display }}</option>
{% endfor %}
</select>
</li>
{% else %}
{% for choice in choices %}
<li{% if choice.selected %} class="selected"{% endif %}>
{{ choice.display }}</li>
{% endfor %}
{% endif %}
</ul>
I suggest you to use this cool third-party.
django-admin-autocomplete-filter
It's easy to use and user-friendly in case of your problem.
For example look at this. models.py
from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=128)
class Album(models.Model):
name = models.CharField(max_length=64)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
cover = models.CharField(max_length=256, null=True, default=None)
admin.py
from django.contrib import admin
from admin_auto_filters.filters import AutocompleteFilter
class ArtistFilter(AutocompleteFilter):
title = 'Artist' # display title
field_name = 'artist' # name of the foreign key field
class ArtistAdmin(admin.ModelAdmin):
search_fields = ['name'] # this is required for django's autocomplete functionality
# ...
class AlbumAdmin(admin.ModelAdmin):
list_filter = [ArtistFilter]
"""
defining this class is required for AutocompleteFilter
it's a bug and I am working on it.
"""
class Media:
pass
# ...

Django author Form not saving to database

models.py
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.CharField(max_length=100, unique=True)
post_pic = models.ImageField(upload_to ='media/post_pics/', default =None )
body = models.TextField()
posted = models.DateTimeField(db_index=True, auto_now_add=True)
#author = must be logged in, populate from login details
forms.py
class postForm(forms.Form):
title = forms.CharField(max_length=100)
slug = forms.CharField(max_length=100)
post_pic = forms.ImageField()
body = forms.CharField(widget=SummernoteWidget())
views.py
def write_detail(request):
template_name = 'blog/write.html'
if request.method == 'POST':
post_form = postForm(request.POST)
if post_form.is_valid():
new_post = Blog(title=title,slug=slug,post_pic=post_pic,body=body)
new_post.save()
return HttpResponseRedirect(blog.get_absolute_url())
else:
post_form = postForm()
return render(request, template_name, {'post_form': post_form})
write.html
{% extends 'blog/base.html' %}
{% load static %}
{% block back-img %}'{% static 'blog/assets/img/intro.jpg' %}'{% endblock back-img %}
{% block titdes %}Write{% endblock titdes %}
{% block title %}Write{% endblock title %}
{% block pagedes %}A django powered community blog{% endblock pagedes %}
{% block body%}
<form method = "POST">
{{ post_form.as_p }}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Publish</button>
</form>
{% endblock %}
I have set up this form so that authors can write articles to the blog without accessing the admin panel and I believe it should work but it isn't saving to the database.
I have tried to work on the views over and over but don't know what else to do. Please don't delete my question just ask any question that can help you help me.
in your forms.py
try
from .models import Blog
class postForm(forms.Form):
title = forms.CharField(max_length=100)
slug = forms.CharField(max_length=100)
post_pic = forms.ImageField()
body = forms.CharField(widget=SummernoteWidget())
class Meta:
model = Blog
fields = ('title', 'slug', 'post_pic', 'body')
PS. Iam new to Django, i hope this help you.
It looks like you just need to save the form, but you're creating a new Blog object with values that we can't see defined anywhere.
new_post = Blog(title=title,slug=slug,post_pic=post_pic,body=body)
title, slug, etc don't get defined.
What you should do, is change it to a ModelForm so that django does all the hard work;
class postForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'slug', 'post_pic', 'body')
widgets = {
'body': SummernoteWidget(),
}
Then in your view you just need to do;
def write_detail(request):
template_name = 'blog/write.html'
if request.method == 'POST':
post_form = postForm(request.POST)
if post_form.is_valid():
post_form.save()
return HttpResponseRedirect(blog.get_absolute_url())
else:
# GET request
post_form = postForm()
return render(request, template_name, {'post_form': post_form})
The summernote docs for forms (and modelforms) is here
Don't forget, that when using a widget like this that comes with media, you need to add the form's media to the template.
You can access it in the HTML using either {{ form.media }} to get all CSS and JS, or individually as {{ form.media.js }} and {{ form.media.css }}
You can see how they do it in the summernote app playground
class postForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'slug', 'post_pic','body')
widgets = {
'body':SummernoteWidget(),
}
Sorry guys you can actually use django summer note with a model form. I used it before but the editor was not appearing so I changed it to the one I previously posted but after reading another answer on stack overflow. I found out that I didn't add this code below to my HTML files or just inside my base.html
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.3/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.3/summernote.js"></script>
Thanks guys

Can't delete an object in delete_view, in Django

I'm trying to create a delete view for my product form, my problem is with the submit button, it doesn't delete my object, it just redirects me to previous page.
This a Windows 7 machine, Python 3.7.1, Anaconda 2018.12
I've tried eliminating the line: if request.method == "POST"
And without that line the object is eliminated, so I think the problem is with the if statement or the POST method, but couldn't solve it
views.py:
from django.shortcuts import render, get_object_or_404, redirect
from .forms import ProductForm, RawProductForm
from .models import Product
def product_delete_view(request, id):
obj = get_object_or_404(Product, id=id)
if request.method == "POST":
obj.delete()
return redirect('../')
context = {
"object": obj
}
return render(request, "products\\product_delete.html", context)
product_delete.html:
{% extends 'base.html' %}
{% block try %}
<form action='.' method='POST'>{% csrf_token %}
<h1>Do you want to delete the product "{{ object.title }}"?</h1>
<p>
<input type="submit" value="Yes" />
Cancel
</p>
</form>
{% endblock %}
The idea is that when I click "Yes", the object disappears, but instead I am redirected to the page of the actual object I wanted to delete

Cannot load Haystack custom form

I want to build a custom search form. Below is my code. My app is called "viewer". I keep getting a "NameError at /viewer/search/...name 'CustomSearchForm' is not defined". Please help. I know it is a simple error somewhere.
From viewer/urls.py:
from django.conf.urls import *
from viewer import views, forms
from haystack.views import SearchView
urlpatterns = patterns('',
#viewer urls
...
url(r'^search/$', SearchView(form_class=CustomSearchForm), name='haystack_search')
)
From viewer/forms.py:
from django import forms
from haystack.forms import ModelSearchForm
from haystack.query import SearchQuerySet
class CustomSearchForm(ModelSearchForm):
...
Here is the solution I found, using a different approach:
urls.py:
url(r'^search/', 'viewer.views.search'),
views.py:
def search(request):
from .forms import CustomSearchForm
form = CustomSearchForm(request.GET)
searchresults = form.search()
return render(request, 'viewer/search.html', {'form' : form})
in viewer/search.html:
{% extends 'base.html' %}
{% block content %}
<form type="get" action=".">
{{form}}
<button type="submit">Search</button>
</form>
{% endblock %}
Had the same problem but with "NameError at /viewer/search/...name 'SearchForm' is not defined" trying to follow the guide here:
http://django-haystack.readthedocs.io/en/v2.6.0/views_and_forms.html
Just upgrading to Django 1.11.0 did the trick for me. Maybe it would work for you too.

Resources