no data is retrieved after query - django

I am trying to fetch specific records from the database table based on user input but getting no data in the objj. Can anybody specify the error? objects.all() is also returning no data.
views.py
from django.views.generic import TemplateView, ListView, DetailView
from ssr.models import dinucleotides
from ssr.forms import InputForm
# Create your views here.
def homepage(request):
return render(request,'index.html')
def searchpage(request):
if(request.method == 'POST'):
fm=InputForm(request.POST)
if fm.is_valid():
print('form validated')
Motiff = fm.cleaned_data['Motiff']
obj1=dinucleotides.objects.filter( SSRtype=Motiff)
objj={'obj1':obj1 }
return render(request,'result.html', objj)
else:
fm=InputForm()
return render(request,'search.html',{'form':fm})```
# models.py
from django.db import models
class dinucleotides(models.Model):
ID = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
Chromosome = models.CharField(db_column='Chromosome', max_length=100, blank=True, null=True) # Field name made lowercase.
SSRtype = models.CharField(db_column='SSRtype', max_length=100, blank=True, null=True) # Field name made lowercase.
Sequence = models.CharField(db_column='SSRsequence', max_length=10000, blank=True, null=True) # Field name made lowercase.
Size = models.IntegerField(db_column='Size', blank=True, null=True) # Field name made lowercase.
Start = models.IntegerField(db_column='Start', blank=True, null=True) # Field name made lowercase.
End = models.IntegerField(db_column='End', blank=True, null=True) # Field name made lowercase.
def __str__(self):
return self.dinucleotides

Notice how the modules are connected:
from .forms import InputForm
from .models import dinucleotides
Also in the model I return just the string 'dinucleotides'. Wherever there is a prefix like "bboard/result.html" replace "bboard" with your application name. I checked everything is working. Try my code and compare with yours.
In the result.html template, the objj dictionary displays the fields of the filtered rows from the database on the page.
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('search/', searchpage),
]
forms.py
from django import forms
class InputForm(forms.Form):
Motiff = forms.CharField()
models.py
from django.db import models
class dinucleotides(models.Model):
ID = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
Chromosome = models.CharField(db_column='Chromosome', max_length=100, blank=True, null=True) # Field name made lowercase.
SSRtype = models.CharField(db_column='SSRtype', max_length=100, blank=True, null=True) # Field name made lowercase.
Sequence = models.CharField(db_column='SSRsequence', max_length=10000, blank=True, null=True) # Field name made lowercase.
Size = models.IntegerField(db_column='Size', blank=True, null=True) # Field name made lowercase.
Start = models.IntegerField(db_column='Start', blank=True, null=True) # Field name made lowercase.
End = models.IntegerField(db_column='End', blank=True, null=True) # Field name made lowercase.
def __str__(self):
return 'dinucleotides'
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import InputForm
from .models import dinucleotides
def searchpage(request):
if request.method == "POST":
fm = InputForm(request.POST)
if fm.is_valid():
Motiff = fm.cleaned_data["Motiff"]
obj1 = dinucleotides.objects.filter(SSRtype=Motiff)
objj = {'obj1': obj1}
return render(request, "bboard/result.html", objj)
else:
return HttpResponse("Invalid data")
else:
fm = InputForm()
return render(request, "bboard/search.html", {"form": fm})
search.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
</head>
<body>
<form method="POST" novalidate>
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" value="Send">
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
{% for aaa in obj1 %}
<h4>{{ aaa.ID}}</h4>
<p>{{ aaa.Chromosome }}</p>
<p>{{ aaa.SSRtype }}</p>
<p>{{ aaa.Sequence }}</p>
<p>{{ aaa.Size }}</p>
<p>{{ aaa.Start }}</p>
<p>{{ aaa.End }}</p>
{% endfor %}
</body>
</html>

Related

Getting Image in django teplate from ManyToMany field

It is returning an error : Not Found: /post-detail/6/images/wallpaper002.jpg. I have tried to show image through {{ post_detail.img.all.first.url }} but I could show image in the template, it returns None value.
news.html
'''
<div class="text-center">
<img class="detail_picture img-thumbnail" src="{{ post_detail.img.all.first }}">
</div>
'''
models.py
'''
class Pictures(TimestampedModel):
img = models.ImageField(upload_to='images')
def __str__(self):
return str(self.img)
class Post(TimestampedModel):
title = models.CharField(max_length=128)
lang = models.IntegerField(choices=LANGUAGES, default=1)
short_description = models.CharField(max_length=255, blank=True, null=True)
description = models.TextField(blank=True, null=True)
category = models.ManyToManyField(PostCategoies, blank=True)
img = models.ManyToManyField(Pictures, blank=True)
icon = models.CharField(max_length=128, blank=True, null=True, help_text="Example: fa fa-info")
is_active = models.BooleanField(default=True)
def __str__(self):
return self.title
'''
views.py
'''
from django.shortcuts import render, redirect
from django.contrib import messages
from django.views import View
from .models import Post, Pictures
from django.views.generic import DetailView
from . import models
from django.shortcuts import get_object_or_404
class HomePageView(View):
def get(self, request):
posts = Post.objects.all()[:4]
context = {'posts': posts}
return render(request, 'index.html', context)
class PostDetailView(DetailView):
context_object_name = "post_detail"
model = models.Post
template_name = 'news.html'
'''
urls.py
'''
app_name = 'posts'
urlpatterns = [
path('', HomePageView.as_view(), name=""),
path('post-detail/<int:pk>/', PostDetailView.as_view(), name="post_detail")
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
'''
You are accessing the instance of a Pictures class with your current code. You need to then access the img property:
<div class="text-center">
<img class="detail_picture img-thumbnail" src="{{ post_detail.img.all.first.img.url }}">
</div>
I would also suggest that you protect against the case of not having an instance in the ManyToMany field
{% if post_detail.img.all.first %}
<div class="text-center">
<img class="detail_picture img-thumbnail" src="{{ post_detail.img.all.first.img.url }}">
</div>
{% endif %}
I'd also suggest looking into prefetch_related and/or Subquery as a way to more efficiently fetch these related details. It will help you prevent N+1 queries. You can verify you're not running too many queries with the django debug toolbar.

Reverse Iterating over Foreign Key

I am trying the tutorial for Django on making a local library website with books.
One of the challenges is to make an author detail view which lists all the books that author has written. I am having trouble displaying any book information for the author.
Model.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.urls import reverse
import uuid
# Create your models here.
class Genre(models.Model):
"""
Model resprenting the book genre
"""
name=models.CharField(max_length=200, help_text="Enter a book genre")
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
summary = models.TextField(max_length=1000, help_text="Enter a brief description")
isbn = models.CharField('ISBN', max_length=13, help_text="13 character ISBN field")
genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('book-detail', args=[str(self.id)])
def display_genre(self):
return ', '.join([genre.name for genre in self.genre.all()[:3] ])
display_genre.short_description = 'Genre'
class BookInstance(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique book number")
book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)
imprint = models.CharField(max_length=200)
due_back = models.DateField(null=True, blank=True)
LOAN_STATUS = (
('d', 'Maintenance'),
('o', 'On loan'),
('a', 'Available'),
('r', 'Reserved'),
)
status = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='d', help_text="Book Availability")
class Meta:
ordering = ['due_back']
def __str__(self):
return ('%s (%s)' %(self.id, self.book.title))
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.CharField(max_length=10, null=True, blank=True)
date_of_death = models.CharField(max_length=10, null=True, blank=True)
def get_absolute_url(self):
return reverse('author-detail', args=[str(self.id)])
def __str__(self):
return ('%s, %s' % (self.last_name, self.first_name))
def display_books(self):
books = Book.objects.get(pk=self.id)
return books.book_set.all()
display_books.short_description = 'Books'
author_detail.html
Really lost here!
{% extends "base.html" %}
{% block content %}
<h1>Author: {{ author }}</h1>
<p><strong>Date of Birth:</strong> {{ author.date_of_birth }}</p>
<p><strong>Date of Death:</strong> {{ author.date_of_death }}</p>
<!--<p><strong>Books:</strong> {% for books in book.author.pk.all %} {{ book.author }}{% if not forloop.last %}, {% endif %}{% endfor %}</p> -->
<div style="margin-left:20px;margin-top:20px">
<h4>Books</h4>
{% for books in book.all %}
<p>{{ books }} Testing Vars {{ book.author_set }} Get copies from key {{ book.author.pk }} </p>
{% endfor %}
</div>
{% endblock %}
Views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.views import generic
# Create your views here.
from .models import Book, Author, BookInstance, Genre
def index(request):
num_books=Book.objects.all().count()
num_instances=BookInstance.objects.all().count()
#available books
num_instances_available=BookInstance.objects.filter(status__exact='a').count()
num_authors=Author.objects.count()
return render(request,
'index.html',
context={'num_books': num_books, 'num_instances': num_instances,
'num_instances_available' : num_instances_available, 'num_authors': num_authors},
)
class BookListView(generic.ListView):
model = Book
class BookDetailView(generic.DetailView):
model = Book
class AuthorListView(generic.ListView):
model = Author
class AuthorDetailView(generic.DetailView):
model = Author
Assuming author_detail.html is used in AuthorDetailView ListView, I'd suggest some changes in your template, maybe like this,
{% block content %}
<h1>Author: {{ object.first_name }} {{ object.last_name }}</h1>
<p><strong>Date of Birth:</strong> {{ object.date_of_birth }}</p>
<p><strong>Date of Death:</strong> {{ object.date_of_death }}</p>
<div style="margin-left:20px;margin-top:20px">
<h4>Books</h4>
{% for book in object.book_set.all %}
<p>{{ book.title }}</p>
{% endfor %}
</div>
{% endblock %}
Since, you haven't overridden the get_context_data() method of the ListView, the default context_variable_name would be object. You may need to refer the Author instance by object.

How to add categories at my django blog

I developed a django blog application using djangogirls.com tutorial. I am trying to add a blog category but I just can't do it!
I was searching google and stackoverflow.com like crazy , but , being a newbie in python/django I couldn't successfully add categories to my blog.
My models:
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
My views:
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
My urls:
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
My post_list.html:
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published_date }}
</div>
<h1>{{post.title }}</h1>
<p>{{ post.text|truncatewords:100}}</p>
</div>
{% endfor %}
{% endblock %}
My post_detail.html:
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaks }}</p>
</div>
{% endblock %}
Ok. If somebody can help me out , I need to create a category model for this blog model ,I would really appreciate it !
Thanks in advance!
I'd go with
class Category(models.Model):
title = models.CharField(max_length=255, verbose_name="Title")
...
class Post(models.Model):
category = models.ForeignKey(Category, verbose_name="Category")
title = models.CharField(max_length=255, verbose_name="Title")
text = models.TextField()
...
When you have a post like this:
post = Post.objects.first()
you can access it's category's title with post.category.title or when you have a category like this:
category = Category.objects.first()
you can get the posts under that category with category.post_set.all().
I have edited your code to show how I'd write if that was a project I am working on. Here it is:
models.py
from django.db import models
from django.utils import timezone
class Category(models.Model):
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at")
title = models.CharField(max_length=255, verbose_name="Title")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __str__(self):
return self.title
class Post(models.Model):
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at")
is_published = models.BooleanField(default=False, verbose_name="Is published?")
published_at = models.DateTimeField(null=True, blank=True, editable=False, verbose_name="Published at")
category = models.ForeignKey(Category, verbose_name="Category")
author = models.ForeignKey('auth.User', verbose_name="Author")
title = models.CharField(max_length=200, verbose_name="Title")
text = models.TextField(verbose_name="Text")
class Meta:
verbose_name = "Post"
verbose_name_plural = "Posts"
ordering = ['-created_at']
def publish(self):
self.is_published = True
self.published_at = timezone.now()
self.save()
def __str__(self):
return self.title
views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Category, Post
def category_list(request):
categories = Category.objects.all() # this will get all categories, you can do some filtering if you need (e.g. excluding categories without posts in it)
return render (request, 'blog/category_list.html', {'categories': categories}) # blog/category_list.html should be the template that categories are listed.
def category_detail(request, pk):
category = get_object_or_404(Category, pk=pk)
return render(request, 'blog/category_detail.html', {'category': category}) # in this template, you will have access to category and posts under that category by (category.post_set).
def post_list(request):
posts = Post.objects.filter(published_at__lte=timezone.now()).order_by('published_at')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
urls.py
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^category$', views.category_list, name='category_list'),
url(r'^category/(?P<pk>\d+)/$', views.category_detail, name='category_detail'),
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
I didn't write templates, they are up to you.
Actually this method (publish) is needed just for Django Girls tutorial, to play in shell https://tutorial.djangogirls.org/en/django_orm/
def publish(self):
self.is_published = True
self.published_at = timezone.now()
self.save()
As actions are managed by django admin, i would change
published_at = models.DateTimeField(null=True, blank=True, editable=False, verbose_name="Published at")
To
published_at = models.DateTimeField(null=True, blank=True, editable=True, default=timezone.now, verbose_name="Published at")
So when adding new post, it would set default time and you would be able to change it to whatever suits you.

solr and django-haystack search result nothing,,search_indexes.py?

every one I am trying the solr and django-haystack to make my search,,I can see there are 9 Docs in my solr,,,and in my db there are 9 data actually,,however,,when it comes to search form and search ,,I got no result ,,
I have to search designer
solr
models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.utils import timezone
.....
class ProductsTbl(models.Model):
model_number = models.CharField(max_length=255, blank=True, unique=True,error_messages={'unique':"這 model number 已經被註冊了 ."})
name = models.CharField(max_length=255, blank=True, null=True)
material = models.CharField(max_length=255,blank=True, null=True)
color = models.CharField(max_length=255, blank=True, null=True)
feature = models.TextField(blank=True, null=True)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
release = models.DateTimeField(blank=True, null=True)
twtime = models.DateTimeField(blank=True, null=True)
hktime = models.DateTimeField(blank=True, null=True)
shtime = models.DateTimeField(blank=True, null=True)
jptime = models.DateTimeField(blank=True, null=True)
suggest = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
cataloggroup = models.ManyToManyField(CatalogGroup)
place = models.ManyToManyField(Place)
scale = models.ManyToManyField(Scale)
slug = models.SlugField(unique=True)
user = models.ForeignKey(User, blank=True, null=True)
useredit = models.CharField(max_length=32, blank=True, null=True)
image = models.ImageField(upload_to=get_imagep_Product, blank=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
views.py
.....
from haystack.query import SearchQuerySet
.....
def post_search(request):
form = SearchForm()
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
results = SearchQuerySet().models(ProductsTbl).filter(content=cd['query']).load_all()
# count total results
total_results = results.count()
return render(request, 'search.html', {'form': form,
'cd': cd,
'results': results,
'total_results': total_results})
return render(request, 'search.html', {'form': form,})
settings.py
.......
INSTALLED_APPS = (
.....
'haystack',
.....
)
....
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8983/solr/designer'
},
}
I guess probably search_indexes.py not correct
search_indexes.py
import datetime
from haystack import indexes
from .models import ProductsTbl
class ProductsTblIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
author = indexes.CharField(model_attr='user')
# created = indexes.DateTimeField(model_attr='created')
def get_model(self):
return ProductsTbl
# def index_queryset(self, using=None):
# """Used when the entire index for model is updated."""
# return self.get_model().objects.filter(created__lte=datetime.datetime.now())
search/indexes/designer/productstbl_text.txt
{{ object.title }}
{{ object.user.get_full_name }}
{{ object.body }}
search.html
{% block title %}Search{% endblock %}
{% block content %}
{% if "query" in request.GET %}
<h1>Posts containing "{{ cd.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">
{{ form.as_p }}
<input type="submit" value="Search">
</form>
{% endif %}
{% endblock %}
after I run python manage.py rebuild_index
here is my data in mysql
there are 9 data ,,just like the solr shows 9 docs,,,
however, after I run the search form ,,,it shows no result
the solr console just shows

Creating forms from models

i'm moving my first steps into Django and i'm tryin' to follow the tutorial at this link: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
but i can't get a form. It just returns a white page!
Can someone explain if i'm missing something?
my models.py:
from django.db import models
from django.forms import ModelForm
class UserProfile(models.Model):
name = models.CharField(max_length=30)
surname = models.CharField(max_length=30)
email = models.EmailField()
tel = models.CharField(max_length=30, null=True, blank=True)
def __unicode__(self):
return '%s %s' % (self.surname, self.name)
class Ad(models.Model):
title = models.CharField(max_length=50)
descr = models.TextField()
city = models.CharField(max_length=30)
price = models.FloatField(null=True, blank=True)
img = models.ImageField(upload_to='./uploaded_imgs', null=True, blank=True)
dateIn = models.DateField(auto_now_add=True)
dateExp = models.DateField(auto_now_add=True)
codC = models.ForeignKey('Cat')
codU = models.ForeignKey('UserProfile')
def __unicode__(self):
return '%s - %s' % (self.title, self.dateIn)
class Cat(models.Model):
cat = models.CharField(max_length=35, primary_key=True)
def __unicode__(self):
return self.cat
my forms.py:
from django import forms
class newAdForm(forms.Form):
title = forms.CharField(max_length=50)
descr = forms.CharField(widget=forms.Textarea)
city = forms.CharField(max_length=30)
price = forms.FloatField(required=False)
img = forms.ImageField(required=False)
dateIn = forms.DateField(auto_now_add=True)
dateExp = forms.DateField(auto_now_add=True)
codC = forms.ModelChoiceField(Cat)
codU = forms.ModelChoiceField(UserProfile)
my views.py:
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.http import HttpResponse
from django import forms
from models import *
from django.forms import *
from django.forms.models import modelformset_factory
[...]
def newAd(request):
newAdFormSet = modelformset_factory(Ad)
if request.method == 'POST':
formset = newAdFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
return render_to_response('conf.html', {'state':'Your ad has been successfull created.'}, context_instance = RequestContext(request),)
else:
formset = newAdFormSet()
return render_to_response('ad_form.html', context_instance = RequestContext(request),)
my ad_form_auto.html template:
{% extends "base.html" %}
{% block title %}Ads insertion form{% endblock %}
{% block content %}
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form method="post" action="">
{{ formset }}
</form>
{% endblock %}
Thanks a lot! This community looks just awesome! :)
You're not passing the form to the template - at present your 'formset' variable containing the form isn't included in the datadict being passed to the view.
return render_to_response('ad_form.html', context_instance = RequestContext(request),)
Should include the data (see render_to_response() docs) here I've renamed the form in your data and to your template as 'form' for ease of nomenclature:
return render_to_response('ad_form.html',
{'form':formset},
context_instance=RequestContext(request))
Then, in your template (see forms in templates docs) replace {{formset}} with {{form.as_p}}. Also add a submit button to the form.
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>