class Article(models.Model):
Title = models.CharField(max_length = 255)
writing = models.TextField()
category = models.CharField(max_length = 225)
published = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
slug = models.SlugField(blank=True, editable=False)
def save(self):
self.slug = slugify(self.Title)
super().save()
def get_absolute_url(self):
url_slug = {'slug':self.slug}
return reverse('artikel:ArticleDetail', kwargs = url_slug)
def __str__(self):
return "{}.{}".format(self.id, self.Title)
i want to build a simple website using django where it could post some articles by form. The problem is how could i post multiple category in one article ? this is form.py below.
from .models import Article
from django.forms import ModelForm
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = [
'title',
'writing',
'category',
]
You can a ManyToManyField to link your post to multiple categories, for example:
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
def __str__(self):
return self.name
class Article(models.Model):
title = models.CharField(max_length=255)
writing = models.TextField()
category = models.ManyToManyField(Category)
published = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
slug = models.SlugField(blank=True, editable=False)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save()
def get_absolute_url(self):
return reverse('artikel:ArticleDetail', kwargs={'slug': self.slug})
def __str__(self):
return '{}.{}'.format(self.id, self.title)
That being said, there already are some packages for this. django-taggit [GitHub] for example, you can install this with:
pip3 install django-taggit
and include 'taggit' to the INSTALLED_APPS list [Django-doc]:
# settings.py
INSTALLED_APPS = [
# …,
'taggit',
# …
]
Then in your models, you can add a TaggableManager to the model:
from django.db import models
from taggit.managers import TaggableManager
class Article(models.Model):
title = models.CharField(max_length=255)
writing = models.TextField()
categories = TaggableManager()
published = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
slug = models.SlugField(blank=True, editable=False)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save()
def get_absolute_url(self):
return reverse('artikel:ArticleDetail', kwargs={'slug': self.slug})
def __str__(self):
return '{}.{}'.format(self.id, self.title)
As the documentation specifies, it comes with a form field that allows one to write space-separated and comma-separated tags.
Related
I have two models:
class Post(models.Model):
title= models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
postimage = models.ImageField(null= True, blank= True, upload_to="images/")
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 + " | "+ str(self.author)
def get_absolute_url(self):
return reverse('article_deatil', args=(str(self.id)))
class AboutMe(models.Model):
title1= models.CharField(max_length=255, default="About Me")
body = models.TextField()
skill1= models.CharField(max_length=255)
skill1body = models.TextField()
skill2= models.CharField(max_length=255)
skill2body = models.TextField()
skill3= models.CharField(max_length=255)
skill3body = models.TextField()
edu1=models.CharField(max_length=255)
edu1body = models.TextField()
edu2=models.CharField(max_length=255)
edu2body = models.TextField()
edu3=models.CharField(max_length=255)
edu3body = models.TextField()
def __str__(self):
return self.title1
I want to show both of them in my home.html
class HomeView(ListView):
model = Post
template_name = 'home.html'
queryset = Post.objects.order_by('-published_date')[:3]
url.py
urlpatterns = [
path('',HomeView.as_view(), name="home"),
path('',PostViewList.as_view(), name="postlist"),
]
I'm new to django and not sure how to show case two model in one template. I did put the post.body and other tags in my html but it not showing the About me part.
Assuming that you want one more queryset of AboutMe model like Post model.
You should simply use get_context_data() in the following way:
class HomeView(ListView):
model = Post
template_name = 'home.html'
queryset = Post.objects.order_by('-published_date')[:3]
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['about_me_records'] = AboutMe.objects.all()
return context
Now, you have one more queryset about_me_records to use in the template and iterate over.
I would like to list out the comments on my Post Detail page and wanted to see how I can connect a view to the specific comments for a given post?
Models.py
class Post(models.Model):
owner = models.ForeignKey(
Profile, null=True, blank=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200)
body = models.TextField()
Post_image = models.ImageField(
null=True, blank=True, default='default.jpeg')
create_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post', kwargs={'pk': self.pk})
class Meta:
ordering = ['-create_date']
class Comment(models.Model):
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
text = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
Views.py
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comment_list'] = Post.comment_set.all()
return context
You can access the detail object of the DetailView with self.object:
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comment_list'] = self.object.comment_set.order_by('create_date')
return context
I'm new in Django and can't find a solution for my problem.
How to make a dynamic URL tree in Django like - site.com/{categoryName}/{itemName}/
Now I have this URL tree:
site.com/item/{itemSlug}/
site.com/category/{itemCategorySlug}/
But I need:
site.com/{itemCategorySlug}/{itemSlug}/
How can I crate this URL tree without installing 3rd party plugins?
Models
from django.db import models
from django.shortcuts import reverse
from services.slug.generator import generate_slug
class Category(models.Model):
name = models.CharField(max_length=400, unique=True)
description = models.TextField(max_length=1000, unique=True)
slug = models.SlugField(max_length=500, unique=True, blank=True)
seo_title = models.CharField(max_length=180, unique=True)
seo_description = models.TextField(max_length=280, unique=True)
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_absolute_url(self):
return reverse('progress_category_url', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if not self.id:
self.slug = generate_slug(self.name)
super().save(*args, **kwargs)
def __str__(self):
return self.name
class Progress(models.Model):
name = models.CharField(max_length=400, unique=True)
description = models.TextField(max_length=1000, unique=True)
slug = models.SlugField(max_length=500, unique=True, blank=True)
seo_title = models.CharField(max_length=180, unique=True)
seo_description = models.TextField(max_length=280, unique=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
tags = models.ManyToManyField(Tag)
date = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=False)
is_verified = models.BooleanField(default=False)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=True, null=True)
promo_image = models.ImageField(upload_to='progress/promo_images/', null=True, blank=True)
class Meta:
verbose_name = 'progress'
verbose_name_plural = 'progresses'
def get_absolute_url(self):
return reverse('progress_url', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if not self.id:
self.slug = generate_slug(self.name)
super().save(*args, **kwargs)
def __str__(self):
return self.name
Views
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Progress, Category
class ProgressView(DetailView):
model = Progress
template_name = 'progresses/detail_tpl.html'
class CategoryView(ListView):
model = Category
template_name = 'progresses/list_tpl.html'
URLs
from django.urls import path
from .views import ProgressView, CategoryView
urlpatterns = [
path('progress/<slug:slug>/', ProgressView.as_view(), name='progress_url'),
path('category/<slug:slug>/', CategoryView.as_view(), name='progress_category_url'),
]
So in my case I need to create something like that:
urlpatterns = [
path('<slug:category_slug>/<slug:progress_slug>/', ProgressView.as_view(), name='progress_url'),
]
How can I do this?
I have 4 categories on my site. How can I write one class PageViews(ListView) for four same pages with different posts. And same question, how to write class DeteilViews(DetailView) for each posts? My models below.
class Category(models.Model):
category = models.CharField(max_length=50)
slug = models.CharField(max_length=60, unique=True)
class Topic(models.Model):
topic = models.CharField(max_length=50)
slug = models.CharField(max_length=60, unique=True)
category = models.ManyToManyField(Category)
class Page(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
datetime = models.DateTimeField()
title = models.CharField(max_length=60)
slug = models.CharField(max_length=250, unique=True)
short_text = models.CharField(max_length=255)
text = models.TextField()
image = models.ImageField(upload_to='media/news_img')
img_source = models.CharField(max_length=255)
page_source = models.CharField(max_length=60)
parsing_date = models.DateTimeField(auto_now=True)
objects = models.Manager()
def get_absolute_url(self):
return reverse('news:detail', args=[self.category.slug, self.topic.slug, self.slug])
class Comment(models.Model):
page = models.ForeignKey(Page, on_delete=models.CASCADE)
comment = models.TextField()
author = models.CharField(max_length=55)
datetime = models.DateTimeField()
I tried write, but failed...
For example:
class DetailView(DetailView):
template_name = 'post.html'
model = Page
def guery_set(self):
return self.request.GET.get('slug')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['posts'] = Page.objects.filter(slug=slug)
return context
And:
class PageView(ListView, SingleObjectMixin):
template_name = 'page_body.html'
paginate_by = 8
def get(self, request, *args, **kwargs):
self.object = self.get_object(
queryset=Category.objects.all())
return super().get(request, *args, **kwargs)
def get_queryset(self):
return Page.objects.filter(category=self.object)
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(**kwargs)
pages = ????
context['posts'] = pages[:8]
return context
I have a little problem with display subcategories belongs only in specific categories. For example: I have a categories: Business, Factory, Health ... and after I can add subcategories for example Own Company in category Business. In this case if I choose category Business I need to have only visible subcategories belongs to this category. How to make it?
This is my code.
models.py
from django.db import models
from slugify import slugify
class Kategoria(models.Model):
name = models.CharField(max_length=50, unique=True, verbose_name='Nazwa kategorii')
slug = models.SlugField(verbose_name='Adres SEO')
class Meta:
verbose_name_plural = 'Kategorie'
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Kategoria, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Subkategoria(models.Model):
category = models.ForeignKey('Kategoria', related_name='subkategoria', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Kategoria główna')
name = models.CharField(max_length=50)
class Meta:
verbose_name_plural = 'Subkategorie'
def __str__(self):
return self.name
class Strona(models.Model):
name = models.CharField(max_length=250, verbose_name='Nazwa strony')
slug = models.SlugField(verbose_name='Adres SEO')
www = models.CharField(max_length=200, verbose_name='Adres strony', unique=True)
content = models.TextField(verbose_name='Opis')
category = models.ForeignKey('Kategoria', verbose_name='Kategoria', on_delete=models.CASCADE)
subcategory = models.ForeignKey('Subkategoria', verbose_name='Subkategoria', on_delete=models.CASCADE)
publish = models.DateField(auto_now=False, auto_now_add=False)
class Meta:
verbose_name_plural = 'Strony'
def __str__(self):
return self.name