why django model instance naming object itself - django

I don`t know this the right title to ask. And i have not enough reputation to post image.
models.py
class Artist(models.Model):
artist_name = models.CharField(max_length=100)
class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.ForeignKey(Artist)
And i registered models to admin
in the admin page i added artist name no issue. Then in the album section in the drop down it`s showing like album object instead of what i given the artist name. what is that for ?

Django doesn't know you want to use artist_name as a string representation of the Artist object. You need to add a __unicode__ (or __str__ on Python 3) method to your Artist model:
def __unicode__(self):
return self.artist_name

Even better if you want to be in sync with python 2 and 3:
At the top of your models:
from __future__ import unicode_literals
then before your class:
#python_2_unicode_compatible
class YourClass(models.Model):
And then:
def __str__(self):
return '%s' % self.title

Related

Django Streaming

I just started with django and I want to make a spotify clone. I want to make it so then when you click on an album it shows the songs for that album.
this is my models.py
from django.db import models
class album(models.Model):
title = models.CharField(max_length=50)
artist = models.IntegerField()
genre = models.CharField(max_length=20)
id = models.AutoField(primary_key=True)
artwork = models.CharField(max_length=1000)
class artist(models.Model):
name = models.CharField(max_length=50)
id = models.AutoField(primary_key=True)
class song(models.Model):
name = models.CharField(max_length=60)
artist = models.IntegerField()
album = models.IntegerField()
id = models.AutoField(primary_key=True)
This is my views.py
from django.shortcuts import render
from .models import album, song
def home(request):
context = {
'albums': album.objects.all(),
}
return render(request, 'main/index.html', context)
For that particular album for which the button is clicked, or all albums, please clarify your question.
Well, it cane achieved through frontend using dropdowns and much more components, or simply redirecting to another page which will show relevant albums.
Through django, if you need to see all albums so you are doing correct.
But if you see a particular album by clicking, so you have to pass that album's id or name or you can pass anything which is unique.
urls.py
path('particular-album/<int:id>/,views.particular_album,name='particular')
Html file
{% for album in albums %}
see particular album
Views.py
def particular_album(req,id):
one_album=album.objects.get(id=id)
return render(req,"main/particular.html",{'one':one_album})
Then in your template file without running the loop you can get all the properties of this object.
If there are more than one objects, so you can use album.objects.filter(field_name=variable) same as like one object, but it gives you more than one, and the variable you have to pass must not be associated with unique constraint.So, it gives you all objects which belong to particular category.Then, you have to run loop in your template file.

Django multiple pictures one product

I have the following problem: I'm programming a webshop and every product has multiple pictures. So this is a one-to-many relation, where the foreign key is in the picture model. However, if i register the models "product" and "picture" to the admin site the user obviously needs to add a product then navigate to the pictures and add a picture and referencing a product within the picture creation process. Instead of this i want the user to be able to create a product and then add multiple pictures in the dropdown menu inside the same subpage inside admin-pannel. How can i accomplish this behaviour? It should look exact like it would with a many-to-many relation. But i don't want to use ManyToManyField sience i already tried it and then it lead to logical issues.
models.py:
class Picture(models.Model):
picture = models.ImageField(upload_to='shop/static/shop/images/')
product = models.ForeignKey(Product, on_delete=models.CASCADE)
def __str__(self):
return self.picture.url
class Product(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
admin.py
admin.site.register(Picture)
admin.site.register(Product)
models.py
class Picture(models.Model):
picture = models.ImageField(upload_to='shop/static/shop/images/')
def __str__(self):
return self.picture.url
class Product(models.Model):
name = models.CharField(max_length=200)
picture = models.ForeignKey(Picture, on_delete=models.CASCADE)
def __str__(self):
return self.name
admin.py
class PictureInline(modeladmin.StackedInline):
model = Picture
class ProductAdmin(admin.ModelAdmin):
inlines = [PictureInline]
admin.site.register(Product, ProductAdmin)
#NOTE: dont register you Picture model because you have put inline in product so from here you can directly put you pictures in the product.
class Picture(models.Model):
picture = models.ImageField(upload_to='shop/static/shop/images/')
def __str__(self):
return self.picture.url
class Product(models.Model):
name = models.CharField(max_length=200)
product = models.ManyToManyField(Picture, blank=True,related_name="product_img")
def __str__(self):
return self.name
Try using this instead.

How to change table object name in django?

I have a table named Product. Every time I create a object using the table django automatically names it as Product object(1), Product object(2) and so forth.
Instead of Project object(1) I want to name it something creative. In my Product Table I have a field called Product Name. Whatever I insert into this field I want that to be the name of the object. If I insert Pen, it should simply show Pen not Product object(1) or anything like that.
I am attaching a picture so you guys can understand my problem clearly.
You need to override model's __str__ method:
class Product(models.Model):
title = models.CharField()
def __str__(self):
return self.title
You should define a __str__ method for your model.
class Product(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
If you need to support Python 2, then use the python_2_unicode_compatible decorator. If you are only supporting Python 2, you can define __unicode__ instead.
from django.utils.encoding import python_2_unicode_compatible
#python_2_unicode_compatible # only if you need to support Python 2
class Product(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
See the docs for the __str__ method for more info.

Django-CMS - CMS section of admin disappears when I specify a model

I'm trying to duplicate the example in 2.4 in the Django-CMS docs (http://docs.django-cms.org/en/2.3.5/extending_cms/custom_plugins.html). However, whenever I specify the model in cms_plugins.py under class HelloPlugin, the entire CMS section in the admin disappears. Any idea what's causing this?
models.py
from django.db import models
class MyModel(models.Model):
title = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return self.title
from cms.models.pluginmodel import CMSPlugin
class HelloPlugin(CMSPlugin):
ad = models.ForeignKey('core.MyModel', related_name='plugins')
def __unicode__(self):
return self.ad.title
cms_plugins.py
class HelloPlugin(CMSPluginBase):
model = MyModel
name = _("MyModel Plugin")
render_template = "myplugin.html"
def render(self, context, instance, placeholder):
context['instance'] = instance
return context
plugin_pool.register_plugin(HelloPlugin)
Small, but significant mistake. I was importing the model, and not the plugin.

django ForeignKey model filter in admin-area?

Hi I need really very very simple example. First my models:
#This my student models
from django.db import models
SEX_CHOICES= (
('M', 'Male'),
('F', 'Female'),
)
class Students(models.Model):
student_name = models.CharField(max_length=50)
student_sex = models.CharField(max_length=8, choices=SEX_CHOICES)
student_city = models.Charfield(max_length=50)
student_bio = models.TextField()
def __unicode__(self):
return self.student_name
O.K. Let see my ClassRooms Model.
#This my ClassRooms models
from django.db import models
from myproject.students.models import *
class ClassRooms(models.Model):
class_number= models.CharField(max_length=50)
class_student_cities = models.ForeignKey(Students)
class_year = models.DateField()
def __unicode__(self):
return self.class_number
How can i show in the class_student_cities area the Students.student_city datas? I guess that about django-admin area. When i do it withclass_student_cities = models.ForeignKey(Students) i just see in that area the Students.student_name data (ex: John Smith). I want to see JUST Students.student_cities data (ex: NewYork). Can you give me a little example?
Should i use something like that:
class_student_cities = models.ForeignKey(Students.student_cities)
Many Thanks!
Try redifinition unicode method.
def __unicode__(self):
return self.student_city
So you'll see in the field student city.
Well, I tried to remake your application to set data with forms class. Something like this in admin.py in your application:
from django.contrib import admin
from django import forms
from myapp.models import *
class ClassRoomsAdminForm(forms.ModelForm):
class Meta:
model = ClassRoom
def __init__(self, *arg, **kwargs):
super(ClassRoomsAdminForm, self).__init__(*arg, **kwargs)
self.fields[' class_student_cities'].choices = [(csc.id,csc.student_city) for csc in Students.objects.all()
class ClassRoomsAdmin(admin.ModelAdmin):
form = ClassRoomsAdminForm
admin.site.register(ClassRooms,ClassRoomsAdmin)
Maybe you'll need to fix something, but I hope it will work. You will set init function to your forms, so in admin panel you set all choices to everything you keep in your Students model. csc.id you'll need to make this object iterable (cities aren't unique) and then you can choose everything from Students model to set in the field.