How to change table object name in django? - 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.

Related

What type of database field for a multiple choice Search filter with DRF?

What type of Database field is the most efficent one for a drf based search filter? I'm trying to build a search feature where i can search by a specific set of features. You could compare it to an hotel search were you filter by Amenities that you want.
Are many to many fields the best choice for this?
I would suggest many to many fields:
from django.db import models
class Category(models.Model):
title = models.CharField(max_length=30)
def __str__(self):
return self.title
class Article(models.Model):
name = models.CharField(max_length=100)
categories = models.ManyToManyField(Category)
class Meta:
ordering = ['name']
def __str__(self):
return self.name

How to store multiple objects as a list in Django model fields? [duplicate]

I want to store some additional information in that, automatically created, ManyToMany join-table. How would I do that in Django?
In my case I have two tables: "Employees" and "Projects". What I want to store is how much each of the employees receives per hour of work in each of the projects, since those values are not the same. So, how would I do that?
What occurred to me was to, instead of the method "ManyToManyField", create explicitly a third class/table to store those new informations and to set its relationship with "Employees" and "Projects" using the "ForeignKey" method. I'm pretty sure it will work, but is this the best approach?
Here is example of what you want to achieve:
http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
In case link ever breaks:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self): # __unicode__ on Python 2
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self): # __unicode__ on Python 2
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)

Use an app's model's object fields as form ChoiceField in another app

I have two apps,menu and table
This is a model in app menu
class Item(models.Model):
name = models.CharField(verbose_name="Item Name", max_length=200, db_index=True)
And in app table, I have a form.py as following:
from django import forms
class TableForm(forms.Form):
item = forms.ChoiceField(choices= xxx)
I would like to use the list of all object names in the model Item as a choicelist in the form. The objects of Item could be created both by admin and elsewhere in my project during runtime and updated in the database. Could someone advise? Thanks.
It is better to use a ModelChoiceField [Django-doc]. If you override the __str__(…) method, the method that tells how the textual representation of an object looks like, we can work with a
class Item(models.Model):
name = models.CharField(
verbose_name='Item Name',
max_length=200,
db_index=True
)
def __str__(self):
return self.name
Then the form looks like:
from django import forms
from menu.models import Item
class TableForm(forms.Form):
item = forms.ModelChoiceField(queryset=Item.objects.all())
It might be a good idea to make the name of an Item unique, such that no two Items are given the same name, this could result in confusion, since if two items are named Apple, then the question is "What is the right apple?":
class Item(models.Model):
name = models.CharField(
verbose_name='Item Name',
max_length=200,
db_index=True,
unique=True # ← mark the name as unique
)
# …

why django model instance naming object itself

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

Django ModelForm ValueError

I have a Django Model
class Category(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
def __unicode__(self):
return self.name
class MPTTMeta:
order_insertion_by = ['name']
and ModelForm
class UploadForm(ModelForm):
file = forms.FileField()
category = mpttform.TreeNodeMultipleChoiceField(queryset=Category.objects.filter(lft=F('rght')-1))
class Meta:
model = UploadedFile
However, I'm having problem with this category field in UploadForm which is supposed to be Category instance (as definied in Model), but my queryset return list of Category objects which I use in template to show all leaf categories.If I select any category on the form and submit it, I get this error(in case I select cat5) 'Cannot assign [Category: cat5]: "UploadedFile.category" must be a "Category" instance.'
So I understand why this error is happening, but I'd like to use ModelForm because of save() method, but don't see how I can fix this.Any suggestions?
Django is telling you that you must initiate a category instance in order to iterate over the categories. So the category instance takes params from the url, url params with regex in your urls.py . So you need to capture the param and make it the category instance in the view.
*See class based generic views for which views automatically give you the params context variable.
I think
category = mpttform.TreeNodeMultipleChoiceField(queryset=Category.objects.filter(lft=F('rght')-1))
Works for a m2m relation and I guess category is a ForeignKey in the model Uploaded File. If so, you should use
category = mpttform.TreeNodeChoiceField(queryset=Category.objects.filter(lft=F('rght')-1))