I am making a Blog where I want for the home page to show only the first 100 characters of each post.
My point is to make better use of space. If a person want to read a post, that person can just click to read it.
I have some ideas on how to do it, but I think they won`t work or are inefficient:
To create a subclass on blog models.py where I would inherit the Post class, save the first hundred characters of each content to a list and make a loop to save each list on the database;
To place a instruction on blog views.py 'FirstPageView' class where it would only exhibit the first hundred characters.
The 'Post' and 'FirstPageView' mentioned classes are as follows:
on 'blog/views.py':
from django.views.generic import ListView
class FirstPageView(ListView):
model = Post
template_name = 'Blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 6
on 'blog/models.py':
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
So what would be the most efficient way to make those previews?
You can use built-in template tags:
{{ posts.content|truncatechars:100 }}
Related
i want to create a tag field like youtube give tage field while uploading a vedio this is what i tried in in my blog form
my models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
# Create your models here.
class Blog(models.Model):
author = models.OneToOneField(User, on_delete=models.CASCADE,)
title = models.CharField(max_length=200,blank=False,)
thumbnail = models.ImageField(upload_to='blogs_thumbnail',default='blogdefa.png')
tags = models.CharField(max_length=500, blank=False, default='Blog')
data = models.TextField(blank=False,)
published_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True,editable=False)
def __str__(self):
return self.title
any idea how to do it i don,t know how to do it
my forms.py
from django import forms
from django.forms import ModelForm, Textarea
from django.contrib.auth.models import User
from .models import Blog, comment, report
forms here
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = '__all__'
widgets = {'data': Textarea(attrs={'cols': 80, 'rows': 20, 'placeholder':'Write Here'}),
'title':forms.TextInput(attrs={'placeholder':'Your Blog Title Here'}),
'tags': forms.TextInput(attrs={'placeholder':'Please enter you content related tags'}),
}
exclude = ['author','published_date','update_at']
all i want is user can create his own tag for blogs like in youtube and not like stackoverflow where you have use to choose you tag
please help
currently it look like this
which is not cool
First thing is that tags work. So to get them working you should relate it to your post.
So you should create a Tag model and use a ManytoManyRelated field to relate tags because you need to get to the post/result at the end using tags.
from django.db import models
from django_extensions.db.fields import AutoSlugField
from django.db.models import CharField, TextField, DateField, EmailField, ManyToManyField
class Tag(models.Model):
name = CharField(max_length=31, unique=True, default="tag-django")
slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"])
def __str__(self):
return self.name
class YourPost(models.Model):
name = CharField(max_length=31, db_index=True)
slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"])
description = TextField()
date_founded = DateField(auto_now_add=True)
contact = EmailField()
tags = ManyToManyField(Tag, related_name="tags")
class Meta:
get_latest_by = ["date_founded"]
def __str__(self):
return self.name
Go on from here.
Create serializers, Viewsets. Relate your tags to your post.
I'm having trouble with this query.
Users application
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
current_story = models.PositiveSmallIntegerField(null=True)
return f'{self.user.username} Profile'
To avoid confusion, the 'current_story' will eventually be a foreign key for the Books.story model (excluded here) once I learn how to do use a foreign key across apps.
Books application
models.py
class character(models.Model):
fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE)
fk_story = models.ForeignKey(story, default='1', on_delete=models.CASCADE)
name = models.CharField(max_length=100, default='', null=True)
def __str__(self):
return self.name
class Meta:
ordering = ('name', )
views.py
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from users.models import Profile
from .models import (character)
class listof_characters(LoginRequiredMixin, ListView):
model = character
template_name = '/list_characters.html'
context_object_name = 'characters'
ordering = ['name']
def get_queryset(self):
?
This is where i'm stuck. I need character.fk_story = User.profile.current_story.
I don't how to phrase this query, I've tried several different things based on other answers and I've tried User.current_story, User.userprofile.current_story as well.
I just need to filter the list of characters by current user's 'current_story' value.
Try to use this:
fk_story = Profile.objects.filter(owner=request.user).order_by('current_story')
Do what Lars said but use self.request.user instead of request.user
UPDATE
urls.py
urlpatterns = [
# other urls
path('characters/<int:pk>/', views.CharactersView.as_view(), name='characters'),
]
views.py
class CharactersView(LoginRequiredMixin, DetailView)
model = story
template_name = '/list_characters.html'
def get_queryset(self):
story = story.objects.get(pk=self.kwargs['pk']) # you need to pass a pk of the story you need the characters for in your url
characters = character.objects.filter(fk_story=story)
return characters
(here i replaced ListView with DetailView so we can query by the story model)
then in your template:
{% for character in characters %}
{{ character.name }}
{% endfor %}
P.S. Always start your Model names and ClassBasedViews with uppercase letters for better readability
def get_queryset(self):
profile = Profile.objects.get(user=self.request.user)
# or better use
# profile = get_object_or_404(Profile, user=self.request.user)
queryset = character.objects.filter(fk_story =profile.current_story)
return queryset
In order for this to work, you also need to change your Profile model.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
current_story = models.ForeignKey(story, on_delete=models.CASCADE)
return f'{self.user.username} Profile'
Note here I am jusing foreignkey rather than integerfield.
I was wondering how I do count the number of poll in my question model using set_count
and I also want to display it in a template please show me using the code thanks
class Question(models.Model):
question_text = models.CharField(max_length=10)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
title = models.CharField(max_length=10)
site_url = models.URLField()
website_type = models.CharField(max_length=100)
budget = models.CharField(max_length=100)
duration = models.CharField(max_length=100)
description = models.TextField()
I want the show the total of question
This is what you write in your views.py:
First, to count it, you have to import the model itself
If models.py and views.py both belong to same app:
from .models import Question
If they belong to different apps:
from <appname>.models import Question
I'll assume they belong to the same app, in views.py:
from django.shortcuts import render
from .models import Question
def index(request):
number_of_questions = Question.objects.count()
context = {
'number_of_questions':number_of_questions,
}
return render(request, '<appname>/index.hmtl>', context)
On the first line of the function it just counts the number of questions with .count() method which comes with django. On the second line we define context that we want to use in template, in this case 'number_of_questions':number_of_questions, so in the html template to display this number we'll use {{ number_of_question }}, have we defined it like so: 'questions':number_of_questions, then in the template we would use {{ questions }}, the end result will be that it shows number_of_questions.
In index.html (Or whatever you named the template):
<p>number of questions:</p>
<p>{{ number_of_questions }}
If you have trouble understanding anything I suggest you read through these:
Django documentation on templating
Some information about python dictionaries
EDIT:
I also highly recommend reading this:
Django documentation about making queries to the database
My objective is to display a readable list of Articles that belong to my user named 'Admin'
In other words, give me all articles that Admin owns. In my sample data I have Admin owning 1 article.
Problem: When I return the object, its a completely unreadable and unhelpful representation of this object. I'm thinking of adding a unicode() method to my model here but I don't know how!!
Model.py:
from django.db import models
from django.contrib.auth.models import User
class Article (models.Model):
question = models.CharField(max_length=255, unique=True, blank=False)
keywords = models.TextField(max_length=500, blank=True, null=True)
def __unicode__(self):
return self.question
class ArticleUserOwnership (models.Model):
article = models.ManyToManyField(Article)
user = models.ManyToManyField(User)
-- you can see here I'm hooking into the admin user table
Views.py:
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from GeorgiaArticleManager.models import Article, ArticleUserOwnership
from django.shortcuts import render
def myarticles(request):
if request.user.is_authenticated():
# articles of admin with id= 1
my_articles = ArticleUserOwnership.objects.filter(user=1)
context = {'my_articles': my_articles}
return render(request, 'template/myview.html', context)
myview.html:
ul
{% for ArticleUserOwnership in my_articles %}
li{{ ArticleUserOwnership }}/li
{% endfor %}
/ul
In summary of above:
ArticleUserOwnership.objects.filter(user=1) returns me an object that when I display it on myview.html, I just get 'ArticleUserOwnership object'. I'm sure this is the correct returned object but, I'd like to see returned Article.question. For example Admin owns 'test title 1' and I'd like to see this article question field displayed properly.
my_articles = ArticleUserOwnership.objects.filter(user=1)
gives you a list of ArticleUserOwnership instances. If you want of list of articles try this instead:
auo = ArticleUserOwnership.objects.get(user=1) # could raise DoesNotExist
my_articles = auo.article.all() # you should rename this field 'articles'
However, that ArticleUserOwnership model doesn't really make sense, my guess is that what you're really trying to do is this:
from django.db import models
from django.contrib.auth.models import User
class Article (models.Model):
question = models.CharField(max_length=255, unique=True, blank=False)
keywords = models.TextField(max_length=500, blank=True, null=True)
owners = models.ManyToManyField(User, related_name='owned_articles')
def __unicode__(self):
return self.question
You would then access your data like so:
my_articles = user.owned_articles.all()
See the documentation for examples of how to use ManyToManyFields.
try this:
class ArticleUserOwnership (models.Model):
article = models.ManyToManyField(Article)
user = models.ManyToManyField(User)
def __unicode__(self):
return self.article
OR
def __unicode__(self):
return self.article.question
Sorry i'm a beginner in django and python..i create a project and i've a models.py like this:
from django.db import models
class Shoes(models.Model):
type = models.CharField(max_length=30)
start_date = models.DateTimeField()
number = models.IntegerField()
def __unicode__(self):
return str(self.id)
class Meta:
verbose_name_plural = "Shoes"
class Bottom(models.Model):
type = models.CharField(max_length=30)
finish = models.BooleanField()
size = models.IntegerField()
def __unicode__(self):
return str(self.id)
class Meta:
verbose_name_plural = "Bottoms"
class Relation(models.Model):
shoes = models.OneToOneField(Shoes)
bottom = models.ForeignKey(Bottom)
class Meta:
verbose_name_plural = "Relations"
I want to serialize theese classes in json..sorry i need to understand where and how write the specific code to do it..
I wrote already a file views.py and a file.html to view a web page with table of theese objects, but now because i need to write a jquery function that allow to update the web page automatically when i add a new object, I think that we need to serialize the data in json before doing so.
Thanks and bear with me if I said something idiotic because i'm a really beginner in this field..
You want to serialize classes? You want to serialize objects! :) In order to serialize Django objects you can use built-in mechanisms. Read this:
https://docs.djangoproject.com/en/dev/topics/serialization/
For example you can do this like this:
from django.core import serializers
from django.http import HttpResponse
def someView(request):
shoes_from_db = Shoes.objects.all()
json = serializers.serialize(
'json', shoes_from_db, fields=('type','start_date', 'number')
)
return HttpResponse(json, content_type="application/json")