Django does not retrieve anything from database when using interactive shell - django

I don't understand what could be the problem of this kind of error. I have 4 apps in my Django project. Each app contains multiple models. I am able to retrieve data from all models expect 1 in the python interactive shell.
Also, in my Form, it gets displayed but when i run the same query from the interactive shell it does not display anything.
I fail to understand what could be the problem, it does not gives any errors as well...
Any help on this would be great!
Updated:
The model contains the following fields:
class Report(models.Model):
rid = models.CharField(blank=True, null=True)
period = models.CharFiedl(blank=True, null=True)
name = models.CharField(blank=True, null=True)
....
....
I was running the following queries:
Report.objects.all() - which returns null
Report.objects.count() - which also return 0
I added a few entries with the help of the admin interface...and checked the same via phpMyadmin...and the interactive shell does not display anything...
But I have a form which is working when i display just the name...
forms.py
class ReportForm(forms.ModelForm):
class Meta:
model = Report
views.py
def display(request):
return render_to_response('view.html', {'Report' : Report.objects.all()})
view.html
{% if Report.count > 0 %}
{% for entries in Report %}
{{entries.name}}
{% endfor %}
{% else %}
<p> No Entries </p>
{% endif %}

Related

Query Multiple Tables in Django and geta consolidated result

I am building a Blog application in Django and currently stuck at Querying the Data. I am creating a Post and then uploading multiple images to that post.
This is my Blog Post Model.
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
title = models.CharField(max_length=255)
description = models.CharField(max_length=1000,null=True)
Tags = models.CharField(max_length = 255,null=True,blank=True)
Created_date = models.DateTimeField(auto_now_add=True)
Updated_date = models.DateTimeField(auto_now=True)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
And this is my Images Model
class Images(models.Model):
Post = models.ForeignKey(Post,on_delete=models.CASCADE)
image = models.ImageField(upload_to='media/')
Now using this implementation I have 2 tables in DB in which data is stored as expected.
In the first tables all the details related to Post are being stored and in the second Table ID, Post_Id, Image_URL is being stored. If I upload 3 images then three rows are being created.
Now I want to Query the data that is -> I want all the posts and I want all the Images according to the Posts.
I can get seprate queries for Post and Images but how can this be done in Django ORM?
How can I query The data?
You can use like this;
post = Post.objects.all().prefetch_related('images_set').get(pk=1)
images = post.images_set.all() # this will bring you all images related to
post
Assuming you have a view that populates a context variable named posts with a queryset like Post.objects.all() your template could look something like this simplified
{% for post in posts %}
{{ post.title }}
{{ post.category }}
{{ post.description }}
...
{% for image in post.images_set.all %}
{{ image.image.url }}
{% endfor %}
{% endfor %}
Every time you iterate over post.images_set.all you will execute another query, you should use prefetch_related so that you don't perform a query each time and the data is cached
posts = Post.objects.prefetch_related('images_set')

How do I create user specific page with Django?

so I've just started studying Django, and ran into a problem.
I'm trying to create a user-specific page, in which if user logs in and inputs his/her info, the info is displayed on the screen, dynamically of course.
So let me show you the codes I wrote.
Here's models.py
class UserInfo(models.Model):
authuser = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'userinfo', null=True,
default=None)
name = models.CharField(max_length=50)
introduction = models.CharField(max_length=100)
And here's views.py
#login_required(login_url="/register")
def main(response):
thisUser = # I have no idea on which code to write here.
return render(response, 'main.html', {'thisUser' : thisUser})
And here's the html file, main.html
{% extends 'base.html' %}
{% block content %}
{{thisUser.name}}
{{thisUser.introduction}}
{% endblock %}
So this is what I've done so far. I have completed all the registration/login/logouts, as well as the forms for letting users input their info(name, introduction). And the next step I'm trying to take is this user specific page, but I have no idea on how to create it.
I would very much appreciate your help. Thanks. :)
First You user OneToOneField in Your UserInfo model as i give
class UserInfo(models.Model):
authuser = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'userinfo', null=True,
default=None)
name = models.CharField(max_length=50)
introduction = models.CharField(max_length=100)
Then makemigrations and then migrate
I think you done login/singup with user model
after login what ever page you render that write only the give line
#in you html file
{% extends 'base.html' %}
{% block content %}
Name : {{ request.user.userinfo.name }}
Introduction : {{ request.user.userinfo.introduction }}
{% endblock %}
If you face problem with extends user of onetoone field i give link refer it
User extends for profile or info
Sing up with profile
Login of user
if still you have problem let me know..!
better to change user field to onetoone field
thisUser = UserInfo.objects.get(authuser=request.user)
(also change def main(response) to def main(request)/same in render also)
request.user will give you current login user object
you can do same in template example:
<h1>Name: {{request.user.name}}</h1>

If user found in a post it returns the username from User database as permalink in the post from models in Django

This is my class models.py I have tried the .split method but keep getting an error that Charfield can not iteriet. I'm trying to make it so that when I call posts in a template if there is a username starting with # it will have the username link to that users profile.
class Status1(models.Model):
post = models.CharField(max_length=333)
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now=True)
You use the below statement for your purpose:
{% if val|slice:":1" == '#' %}
#Doing stuff
{% endif %}

Django Filter Query by Foreign Key

I'm struggling getting the right query for my project. Here is an example or my model :
from django.db import models
class Pictures(models.Model):
name = models.CharField(max_length=100)
bild = models.FileField(upload_to='article_pictures/')
articel = models.ForeignKey('articles', on_delete=models.CASCADE)
def __str__(self):
return self.name
class Articles(models.Model):
name = models.CharField(max_length=100)
text = models.TextField(max_length=2000)
published = models.BooleanField(default=False)
def __str__(self):
return self.name
how do I get the published artikles from the artikles class including the pictures (if there is one, or more)?
Thank you for your help
I don't think there is any exact query for this, but you can use prefetch_related to pre-load data from database. For example:
articles = Artikles.objects.filter(published=True).prefetch_related('pictures_set')
for article in articles:
article.pictures_set.all() # will not hit database
All published articles:
Articles.objects.filter(published=True)
A single published Article(Example):
article = Articles.objects.filter(published=True).first()
# and it's pictures
for picture in article.pictures_set.all():
print(picture)
Note: models have singular names, so you should rename Articles to Article and Pictures to Picture.
The related Pictures of an article article can be obtained with:
my_article.picture_set.all()
this is a queryset that contains all the related pictures.
We can obtain the Articles that are publised, and then fetch the related Pictures in two extra queries with:
articles = Article.objects.filter(published=True).prefetch_related('picture_set')
So in a template you can then render it like:
{% for article in articles %}
{{ article.name }}
{% for picture in article.picture_set.all %}
{{ picture.name }}
{% endfor %}
{% endfor %}

List of Articles form FeinCMS Content Typs

my mission is to get a list of articles. This article come form a simple FeinCMS ContentType.
class Article(models.Model):
image = models.ForeignKey(MediaFile, blank=True, null=True, help_text=_('Image'), related_name='+',)
content = models.TextField(blank=True, help_text=_('HTML Content'))
style = models.CharField(
_('template'),max_length=10, choices=(
('default', _('col-sm-7 Image left and col-sm-5 Content ')),
('fiftyfifty', _('50 Image left and 50 Content ')),
('around', _('small Image left and Content around')),
),
default='default')
class Meta:
abstract = True
verbose_name = u'Article'
verbose_name_plural = u'Articles'
def render(self, **kwargs):
return render_to_string('content/articles/%s.html' % self.style,{'content': self,})
I would like to use that in different subpages.
Now it would be great to get a list of all articels on the main page (my projects -> list of project1, project2, project3, ).
Something like: Article.objects.all()
Template:
{% for entry in article %}
{% if content.parent_id == entry.parent_id %} #only projects
<p>{{ entry.content|truncatechars:180 }}</p>
{% endif %}
{% endfor %}
but i get a error "type object 'Articels' has no attribute 'objects'...
Do you have a smart idea? It would be grade to use Feincms ContentType.
FeinCMS content types are abstract, that means there is no data and no database table associated with them. Therefore, there's no objects manager and no way to query.
When doing Page.create_content_type(), FeinCMS takes the content type and the corresponding Page class and creates a (non-abstract) model which contains the actual data. In order to access that new, concrete model, you need to use content_type_for. In other words, you're looking for:
from feincms.module.page.models import Page
PageArticle = Page.content_type_for(Article)
articles = PageArticle.objects.all()