several images on one app - python

i try to create news app on django 1.8. And I suppose several images in one news that i can to add from the backend. So this is my models.py
from django.db import models
class Category(models.Model):
category = models.CharField('Category', max_length=255)
slug = models.CharField(max_length=255)
def __unicode__(self):
return self.category
class Images(models.Model):
image = models.ImageField('Images', upload_to='media/img/news')
news = models.ForeignKey('News', blank=True, null=True)
class News(models.Model):
title = models.CharField(max_length=255)
category = models.ForeignKey('Category', blank=True, null=True)
teazer_image = models.ImageField(upload_to='media/img/news', blank=True)
pub_date = models.DateField(null=True)
slug = models.CharField(max_length=255)
short_content = models.TextField(max_length=2000, blank=True)
content = models.TextField(max_length=10000)
image = models.ForeignKey('Images', blank=True, null=True)
meta = models.CharField(max_length=255, blank=True)
description = models.TextField(max_length=10000, blank=True)
def __unicode__(self):
return self.title
Admin.py
from django.contrib import admin
from news.models import News, Category, Images
from django.shortcuts import get_object_or_404
class ImagesInline(admin.TabularInline):
model = Images
class NewsAdmin(admin.ModelAdmin):
inlines = [
ImagesInline,
]
admin.site.register(News, NewsAdmin)
admin.site.register(Images)
admin.site.register(Category)
But I do not understand how to create views and template. Can you help me with it?

Related

Django Filters not querying data

I'm trying to filter API responses through a web search. After typing a search query it doesn't filter the result. I'm also using pagination. How to solve this do I need to make changes in my filter or View.
search query
http://127.0.0.1:8000/course-api/subjectlist/?search="ICT"/
after giving this search query still it returns all of the elements through the response.
Subject model
class Subject(models.Model):
def upload_location(instance, filename):
return "subject_images/%s/%s" % (instance.subject_name, filename)
subject_name = models.CharField(max_length=200, null=True)
subject_cover = models.ImageField(null=True, blank=True, upload_to=upload_location,default="subject_images/default.png")
description = models.CharField(max_length=500, null=True, blank=True)
author = models.ForeignKey(TeacherProfile,on_delete=models.CASCADE,null=True,default=None)
subject_type = models.CharField(max_length=100, null=True, blank=True)
class_type = models.CharField(max_length=10, null=True, blank=True)
short_description = models.CharField(max_length=300,blank=True,null=True)
created_at = models.DateTimeField(default=now)
filters.py
import django_filters
from ..models import Subject
class SubjectFilter(django_filters.FilterSet):
class Meta:
model = Subject
fields = ['subject_name']
Views.py
#api_view(['GET'])
def SubjectList(request):
paginator = PageNumberPagination()
paginator.page_size=5
subjects =SubjectFilter ( request.GET, queryset= Subject.objects.all())
result_page = paginator.paginate_queryset(subjects.queryset,request)
serializer = SubjectViewSerializer(result_page,many=True)
return paginator.get_paginated_response(serializer.data)

Server Error 500 when trying to add instance of a model on Django

I have a website working perfectly in Django for me, I can add and delete instances of models as I want. However, if someone else tries to add an instance with the exact same admin account, the page shows "Server Error 500".
I am using the default SQLite settings for django.
models.py:
from django.db import models
from datetime import datetime
# Create your models here.
class Receita(models.Model):
titulo_receita = models.CharField(max_length=200);
resumo_receita = models.CharField(max_length=255, default='')
tempo_receita = models.CharField(max_length=200, default='');
rendimento_receita = models.CharField(max_length=200, default='');
imagem_preview = models.ImageField(upload_to='uploads/%Y/%m/%d/', default='static/default_image.png')
conteudo_receita = models.TextField();
data_receita = models.DateTimeField('Data publicação', default=datetime.now());
def __str__(self):
return self.titulo_receita;
class Produto(models.Model):
nome = models.CharField(max_length=200);
desc = models.TextField()
# desc = models.CharField(max_length=255, default='');
imagem = models.ImageField(upload_to='uploads/%Y/%m/%d/', default='static/default_image.png')
info1 = models.CharField(max_length=255, default='', blank=True)
cod1 = models.CharField(max_length=255, default='', blank=True)
info2 = models.CharField(max_length=255, default='', blank=True)
cod2 = models.CharField(max_length=255, default='', blank=True)
info3 = models.CharField(max_length=255, default='', blank=True)
cod3 = models.CharField(max_length=255, default='', blank=True)
def __str__(self):
return self.nome;
admin.py:
from django.contrib import admin
from .models import Receita
from .models import Produto
from tinymce.widgets import TinyMCE
from django.db import models
# Register your models here.
class ReceitaAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': TinyMCE()}
}
admin.site.register(Receita, ReceitaAdmin)
admin.site.register(Produto)

Django App Not Working After Deployment to heroku

The App is A Blog Post App That is Working fine Locally But After I Deployed It To Heroku, The App Cannot run. I did more Than a week trying to fix it through the views and models with no success.
This Is The Error When Trying To Open The App
views.py
from django.shortcuts import render,get_object_or_404, get_list_or_404
from posts.models import Post, Category
# Create your views here.
import datetime
def index(request):
now = datetime.datetime.now()
big_slider_list = Post.objects.filter(category__name='Big_Slider')
news_box_list = Post.objects.filter(category__name='People')
cote_divoire_list = Post.objects.filter(category__name="Côte d'Ivoire").exclude(position=1)
block1_big = Post.objects.filter(position=1)
culture_list = Post.objects.filter(category__name="Culture").exclude(position=2)
block2_big = Post.objects.filter(position=2)
sport_list = Post.objects.filter(category__name="Sports").exclude(position=3)
block3_big = Post.objects.filter(position=3)
infrast_et_devel_list = Post.objects.filter(category__name="Infrastructures Et Dévelopements")
context = {
'now': now,
'big_slider_list': big_slider_list[:10],
'news_box_list': news_box_list[:4],
'cote_divoire_list': cote_divoire_list[:4],
'block1_big': block1_big[0],
'culture_list': culture_list[:3],
'block2_big': block2_big[0],
'sport_list': sport_list[:3],
'block3_big': block3_big[0],
'infrast_et_devel_list': infrast_et_devel_list[:3],
}
return render(request, 'home/index.html', context)
models.py :
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
# Create your models here.
User = get_user_model()
STATUS = (
(0, "Draft"),
(1, "Publish")
)
POSITIONS = [
(0, ' '),
(1, 'BIG_BLOCK_1'),
(2, 'BIG_BLOCK_2'),
(3, 'BIG_BLOCK_3'),
(4, 'BIG_BLOCK_4'),
]
class Author(models.Model):
name = models.CharField(max_length=50)
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(null=True, blank=True)
email = models.EmailField(unique=True)
active = models.BooleanField(default=False)
created_on = models.DateTimeField(auto_now_add=True)
last_logged_in = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
class Category(models.Model):
country = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE,)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('posts:post_by_category', args=[self.slug])
class Tag(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE,)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('posts:post_by_tag', args=[self.slug])
class Post(models.Model):
status = models.IntegerField(choices=STATUS, default=0)
position = models.IntegerField(choices=POSITIONS, default=0)
title = models.CharField(max_length=300)
short_title = models.CharField(max_length=200)
display_image = models.ImageField(null=True, blank=True)
post_image = models.ImageField(null=True, blank=True)
content = models.TextField(max_length=8000)
slug = models.SlugField(max_length=300, unique=True)
updated_on = models.DateTimeField(auto_now=True, auto_now_add=False)
created_on = models.DateTimeField(auto_now=False, auto_now_add=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE,)
category = models.ForeignKey(Category, on_delete=models.CASCADE,)
tags = models.ManyToManyField(Tag,)
comment_count = models.IntegerField(default=0)
class Meta:
ordering = ['-created_on']
verbose_name = "All Post"
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('posts:post_detail', kwargs={'slug': self.slug})
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
It's something to do with the migrations. Your local DB has all the migrations applied, while your Database on Heroku doesn't have the post field. Maybe you added/edited the field later so your two DBs are out of sync. Since this seems to be a new project without data it would be easier for you to heroku reset your heroku database and push the local db to heroku. Here are the instructions: https://devcenter.heroku.com/articles/heroku-postgres-import-export

How to show how many records in django databes I have?

I have a little problem. In my models.py file I have two classes:
class Categories and class Websites.
In Categories by the admin panel I added many records of categories. How to show in html file for example : how many webstites were added in the category 'Company' or in the another categories?
Here is my models.py
from django.db import models
from django.utils import timezone
class Kategorie(models.Model):
glowna = models.CharField(max_length=150, verbose_name='Kategoria')
class Meta:
verbose_name='Kategoria'
verbose_name_plural='Kategorie'
def __str__(self):
return self.glowna
class Witryna(models.Model):
nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony')
adres_www = models.CharField(max_length=70, verbose_name='Adres www')
slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url')
email = models.CharField(max_length=100, verbose_name='Adres e-mail')
text = models.TextField(max_length=3000, verbose_name='Opis strony')
kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria')
data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')
class Meta:
verbose_name='Strona www'
verbose_name_plural = 'Strony www'
def publikacja(self):
self.data_publikacji=timezone.now()
self.save()
def __str__(self):
return self.nazwa

No reverse match django class based views

I m new to Django and I am learning it through a project but m stuck with this error which says that NoReverseMatch at /product/create/
here is my models.py file
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
# Create your models here.
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='category_created')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null= True,blank=True)
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail',
args=[self.slug])
This is my views.py but I m not sure if there is something wrong with my views
from django.views.generic import *
from django.core.urlresolvers import reverse_lazy
from .models import Category, Product
class CategoryList(ListView):
model = Category
class CategoryDetail(DetailView):
model = Category
class ProductList(ListView):
model = Product
class ProductDetail(DetailView):
model = Product
class ProductCreate(CreateView):
model = Product
fields = ["category", 'name', 'image', 'description', 'price', 'stock','available', 'negiotiable']
class ProductUpdate(UpdateView):
model = Product
fields = ['name', 'image', 'description', 'price', 'stock','available', 'negiotiable']
class ProductDelete(DeleteView):
model = Product
success_url = reverse_lazy('product_list')
I can't tell if this is the problem without the traceback or urls.py but I'm guessing you need to auto-generate the slug field by overriding the save method in the Product model. Instructions here: http://fazle.me/auto-generating-unique-slug-in-django/
Or you could try this:
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null= True,blank=True)
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail', args=[self.slug])
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Product, self).save(*args, **kwargs)
Note that this way you will have to change db_index to unique for the name field.

Categories