django models filefield upload - django

I want to create a song list for eg "movie name Titanic and it contains all its songs" but I don't know to add more than one song in a movie, can some one help me here?
Here is what I am doing
views.py
from django.shortcuts import render_to_response
from .models import Songs
def Songs(request):
songs = Songs.objects.all()
return render_to_response('profile_page.html',{'songs':songs})
models.py
from django.db import models
class Movie(models.Model):
name= models.CharField(max_length = 100)
class Songs(models.Model):
movie = models.ForeignKey(Movie, default= 1)
song_title = models.CharField(max_length=20)
song_poster = models.FileField()
song_list = models.FileField()
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^',views.Songs),
]

create a model called Movie
class Movie(models.Model):
name= models.CharField(max_length = 100)
// other fields as needed
class Songs(models.Model):
movie = models.ForeignKey(Movie)
song_title = models.CharField(max_length=20)
song_poster = models.FileField()
song_list = models.FileField()
then add songs according to movie and query according to movie id

Related

Django blog post views count adds two instead of one

I built this blog with django and everything is working except the blog post view count. On the page it adds 1 as instructed but adds 2 in django admin. Please let me know what I am doing wrongly
Models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
User = get_user_model()
from ckeditor_uploader.fields import RichTextUploadingField
class Subscribe(models.Model):
email = models.EmailField()
class Comments(models.Model):
name = models.CharField('Name', max_length=120)
post_id = models.IntegerField(null=True)
email = models.EmailField()
website = models.URLField(max_length=200)
comment = models.TextField(blank=True)
date_created = models.DateTimeField(blank=True,null=True)
def publish(self):
self.date_created=timezone.localtime(timezone.now())
self.save()
class Category(models.Model):
name = models.CharField('Name', max_length=120)
slug = models.SlugField(default="", null=False)
def __str__(self):
return self.name
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
about = RichTextUploadingField()
image = models.ImageField(upload_to='images/', null=True)
slug = models.SlugField(default="", null=False)
views = models.IntegerField(default=0)
def __str__(self):
return self.user.username
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
class Post(models.Model):
title = models.CharField('Post Title', max_length=120)
date = models.DateTimeField()
status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft')
category = models.ForeignKey(Category,on_delete = models.SET_NULL, blank = True, null = True,)
author = models.ForeignKey(User,on_delete = models.SET_NULL, blank = True, null = True,)
details = RichTextUploadingField()
slug = models.SlugField(default="", null=False)
image = models.ImageField(upload_to='images/', null=True)
post_views = models.IntegerField(default=0)
class Meta:
ordering = ['-date']
def __str__(self):
return self.title
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
Views.py
from django.shortcuts import render
from .models import Post
from .models import Comments
from .models import Category
from .models import Author
from .models import Subscribe
from django.http import JsonResponse
from django.utils import timezone
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Count
# DEFINING CONTEXTS DETAILS
posts = Post.objects.filter(status="published")
recentPosts = Post.objects.filter(status="published").order_by("-id")[:3]
sidebarPosts = Post.objects.filter(status="published").order_by("-id")[:5]
morePosts = Post.objects.filter(status="published").order_by("-id")[:2]
popularPosts = Post.objects.order_by("-post_views")[:3]
categoryList = Category.objects.annotate(nblog=Count('post')).values()
# VIEW FOR POST DETAILS PAGE
def details(request, slug):
thisPost = Post.objects.filter(slug=slug).first()
thisPost.post_views+=1
thisPost.save()
id = thisPost.id
author = thisPost.author
category = thisPost.category
postCategory = Category.objects.filter(name = category).first()
authorDetail = Author.objects.filter(user = author).first()
allComments = Comments.objects.filter(post_id = id).order_by("-date_created").values()
commentCount = len(Comments.objects.filter(post_id = id))
context = {
'details' : thisPost,
'postCategory' : postCategory,
'allComments' : allComments,
'count' : commentCount,
'authorDetail' : authorDetail,
'sidebarPosts' : sidebarPosts,
'morePosts' : morePosts,
'recentPosts' : recentPosts,
'popularPosts' : popularPosts,
'categoryList' : categoryList
}
return render(request,'markedia/details.html', context)
Urls
from django.urls import path
from markedia_blog import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name="index"),
path('index', views.index, name="index"),
path('contact', views.contact, name="contact"),
path('details/<slug:slug>', views.details, name="details"),
path('comment', views.comment, name="comment"),
path('subscribe', views.subscribe, name="subscribe"),
path('blog', views.blog, name="blog"),
path('author/<slug:slug>', views.author, name="author"),
path('category/<slug:slug>', views.category, name="category"),
path('search', views.search, name="search"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
ADMIN PAGE
Default = 0
Admin page
TEMPLATE PAGE
Post views is equal to 1 on template page
Post views is equal to 1 on template page
ADMIN PAGE AFTER VIEWING TEMPLATES PAGE
Post views is equal to 2 instead of 1
Post views is equal to 2 instead of 1
Could you tell me what i'm doing wrong??
Template page post views shows 1 but admin page shows 2

Django - How to make multiple objects dynamic in the same page

Problem statement: Unable to make multiple elements dynamic in the same index page. Can you suggest me how to do it? I have almost 5 elements to be made dynamic in the same page.
I am using the following code
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index_a, name='index'),
path('', views.index_b, name = 'lunch')
]
views.py
from django.shortcuts import render
from . models import breakfast, lunch
# Create your views here.
def index_a(request):
brkfstn = breakfast.objects.all()
return render(request, "index.html",{'brkfstn':brkfstn})
def index_b(request):
lunchn = lunch.objects.all()
return render(request, "index.html",{'lunchn':lunchn})
models.py
from django.db import models
# Create your models here.
class breakfast(models.Model):
name = models.CharField(max_length=100)
ingrdnt = models.TextField()
image = models.ImageField(upload_to='images')
price = models.IntegerField()
discount = models.BooleanField(default=False)
offer_price = models.IntegerField()
class lunch(models.Model):
name = models.CharField(max_length=100)
ingrdnt = models.TextField()
image = models.ImageField(upload_to='images')
price = models.IntegerField()
discount = models.BooleanField(default=False)
offer_price = models.IntegerField()
Got my mistake.
Can add more elements in the dictionary in views.py
So updated my views.py as below:
from django.shortcuts import render
from . models import breakfast, lunch
# Create your views here.
def index_a(request):
brkfstn = breakfast.objects.all()
lunchn = lunch.objects.all()
return render(request, "index.html",{'brkfstn':brkfstn, 'lunchn':lunchn'})

Django Admin Model Schema

New to django, and loving it so far. I have a django admin, schema design question. I have a app that has a customer, product and order table. The customer has an order sheet of products, pre-built by admin, and saved in the CustomerProduct table. When the customer logs in they can only view their order sheet, update quantities, and that's it. They won't have access to products table or other customers order sheets. Three parts where im stuck right now,
The order table should have a many-to-many relationship with the customer_products table.
Order history needs to be saved in a separate table somehow, so if a user's order sheets changes, we still have record of their past orders. I need to construct a view for a user that will display just their order sheet. /admin/onlineordering/ordersheet.
How can I set this url up and limit access to a authenticated user. User A can only see User A's CustomerProduct (Order Sheet)
Below is the apps models.py and the admin.py
onlineordering/models.py
from django.conf import settings
from django.db import models
from datetime import datetime
class Customer(models.Model):
customer = models.ForeignKey(settings.AUTH_USER_MODEL, limit_choices_to={'groups__name': "customers"})
customer_product = models.ManyToManyField('Product', through='CustomerProduct')
company_name = models.CharField(max_length=255)
address1 = models.CharField(max_length=255)
address2 = models.CharField(max_length=255)
city = models.CharField(max_length=255)
state = models.CharField(max_length=255)
zip_code = models.CharField(max_length=255)
def __unicode__(self):
return self.company_name
class CustomerProduct(models.Model):
customer = models.ForeignKey('Customer')
product = models.ForeignKey('Product')
class Product(models.Model):
item = models.CharField(max_length=255)
description = models.CharField(max_length=255)
def __unicode__(self):
return self.description
class Order(models.Model):
customer_product_order = models.ManyToManyField('CustomerProduct', through='CustomerProductOrder')
purchase_order_number = models.CharField(max_length=10)
person_placing_order = models.CharField(max_length=255)
requested_delivery_date = models.DateField(blank=True, null=True)
class CustomerProductOrder(models.Model):
order = models.ForeignKey('Order')
customer_product = models.ForeignKey('CustomerProduct')
quantity = models.IntegerField(default=0)
onlineordering/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Order,Customer,Product
UserAdmin.add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'first_name', 'last_name', 'groups')}
),
)
class CustomerProductInline(admin.StackedInline):
model = Customer.customer_product.through
extra = 0
class ProductAdmin(admin.ModelAdmin):
inlines = [
CustomerProductInline,
]
class CustomerAdmin(admin.ModelAdmin):
inlines = [
CustomerProductInline,
]
exclude = ('customer_product',)
admin.site.register(Order)
admin.site.register(Customer,CustomerAdmin)
admin.site.register(Product)
Update
/onlineordering/views.py
from django.http import HttpResponse
def ordersheet(request):
return HttpResponse("Hello, world.")
/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/onlineordering/ordersheet', include(admin.site.urls)),
]

django not add auto increment primary key id when save an article

I hava an article app installed in django admin site,when i finish editing one article,I click the save button,but an error page:
article/models.py
# blog category models
class Category(models.Model):
id = models.IntegerField(primary_key=True,help_text='primary key')
name = models.CharField(max_length=50,help_text='category name')
description = models.TextField(default='',help_text='category description')
createtime = models.DateTimeField(auto_now_add=True)
modifytime = models.DateTimeField(auto_now=True)
categories = models.Manager()
class Meta:
db_table = 'article_category'
def __str__(self):
return self.name
#blog article models
class Article(models.Model):
STATUS = (
(0,'on'),
(1,'off')
)
id = models.IntegerField(primary_key=True,help_text='primary key')
category = models.ForeignKey(Category,help_text='foreigner key reference Category')
title = models.CharField(max_length=100,help_text='article title')
content = models.TextField(help_text='article content')
like = models.IntegerField(default=0,help_text='like numbers')
secretcode = models.CharField(max_length=512,help_text='who has the code can scan')
status = models.IntegerField(choices=STATUS,help_text='status of the article')
createtime = models.DateTimeField(auto_now_add=True,help_text='time that first created')
modifytime = models.DateTimeField(auto_now=True,help_text='time when modified')
articles = models.Manager()
class Meta:
db_table = 'article'
article/widgets.py
from pagedown.widgets import AdminPagedownWidget
from django import forms
from .models import Article
class ArticleModelForm(forms.ModelForm):
content = forms.CharField(widget=AdminPagedownWidget())
class Meta:
model = Article
fields = ('title','category', 'content', 'secretcode', 'status')
article/admin.py
from django.contrib import admin
from .widgets import ArticleModelForm
from .models import Article,ArticleImage,Category
class MMBArticleAdmin(admin.ModelAdmin):
form = ArticleModelForm
admin.site.register(Article,MMBArticleAdmin)
admin.site.register(Category)
admin.site.register(ArticleImage)
the page in the admin site looks likeļ¼š
and then I click save ,the error page show up like above!why did this happen?and how to fix it?
You've overridden the default automatic field with a manual non-autoincrementing ID. Don't do that. Remove your id fields altogether.

Django admin returns TypeError

I am not able to login into admin panel in django app.
It returns error (listing here: http://dpaste.com/1437248/ ).
my admin.py:
from app.models import *
from django.contrib import admin
admin.site.register(Product, Product.Admin)
my models.py (partially):
class Product(BaseModel):
company = models.ForeignKey(Company, null=True, blank=True)
title = models.CharField(max_length=128)
description = models.TextField()
category = models.ForeignKey(ProductCategory, null=True, blank=True)
price = models.DecimalField(max_digits=5,decimal_places=2)
image = models.ImageField(upload_to=product_upload_to)
thumb = models.ImageField(upload_to=thumb_upload_to)
def save(self, force_update=False, force_insert=False, thumb_size=(120,120)):
image = Image.open(self.image)
image.thumbnail(thumb_size, Image.ANTIALIAS)
temp_handle = StringIO()
image.save(temp_handle, 'png')
temp_handle.seek(0) # rewind the file
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(),
content_type='image/png')
self.thumb.save(suf.name+'.png', suf, save=False)
super(Product, self).save(force_update, force_insert)
class Admin(admin.ModelAdmin):
list_display = ('title','price')
EDIT:
Now I am sure that this error isn't caused by admin.py/Admin class - I deleted content of admin.py and error is still present.
The model admin class shouldn't be inside your Product model. Define it in admin.py.
from app.models import *
from django.contrib import admin
class ProductAdmin(admin.ModelAdmin):
list_display = ('title','price')
admin.site.register(Product, ProductAdmin)