I have multiple models and i want to display them all on one page in django admin.
Some of these have no relationship(fk,onetoone,mm).
how i can achieve that?
class Category(models.Model):
name = models.CharField(max_length=100)
class Industry(models.Model):
name = models.CharField(max_length=100)
class SampleImages(models.Model):
image = models.ImageField(upload_to='images/tile_images')
category = models.ManyToManyField(Category)
industry = models.ManyToManyField(Industry)
class SampleColor(models.Model):
image = models.ImageField(upload_to='images/tile_color')
name = models.CharField(max_length=25)
class OrderDetail(models.Model):
name_in_logo = models.CharField( max_length=150)
slogan = models.CharField(max_length=20)
describe_website_and_audience = models.TextField()
Related
In models.py:
ingredient_name = models.CharField(primary_key=True, max_length=50)
category = models.CharField(max_length=50)
stock = models.IntegerField()
unit = models.CharField(max_length=10)
def __str__(this):
return this.ingredient_name
class Recipe(models.Model):
recipe_name = models.CharField(primary_key=True, max_length=50)
ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient')
sales_price = models.IntegerField()
def __str__(this):
return this.recipe_name
class RecipeIngredient(models.Model):
recipe_name = models.ForeignKey('Recipe', models.CASCADE)
ingredient_name = models.ForeignKey('Ingredient', models.CASCADE)
quantity = models.IntegerField()
In forms.py:
class RecipeFormCreate(ModelForm):
class Meta:
model = Recipe
fields = ('recipe_name', 'ingredients', 'sales_price')
The created form looks like this:
Form generated by RecipeFormCreate, with the "Ingredients" field having a list of items that can be selected
Is there a way to allow the end user of this product to set the ingredient's quantity (a field added by the RecipeIngredient model) within the RecipeFormCreate form?
My models:
class Ingredient(models.Model):
BASE_UNIT_CHOICES = [("g", "Grams"), ("ml", "Mililiters")]
CURRENCY_CHOICES = [("USD", "US Dollars"), ("EUR", "Euro")]
ingredient_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
base_unit = models.CharField(max_length=2, choices=BASE_UNIT_CHOICES)
cost_per_base_unit = models.FloatField()
currency = models.CharField(
max_length=3, choices=CURRENCY_CHOICES, default="EUR")
def __str__(self):
return self.name
class RecipeIngredient(models.Model):
quantity = models.FloatField()
ingredient_id = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
def __str__(self):
return f"{self.quantity} / {self.ingredient_id}"
class Recipe(models.Model):
recipe_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
ingredients = models.ManyToManyField(RecipeIngredient)
date_created = models.DateTimeField('Date Created')
def __str__(self):
return f"{self.name}, {self.ingredients}"
When I use the admin page, it has this + button that allows me to create new ingredient/quantity combinations
like this
But when I try to use it from a form in my code it looks like
this
Here is my form code:
class AddRecipeForm(forms.ModelForm):
class Meta:
model = Recipe
fields = ['name', 'ingredients', 'date_created']
You should write the 'widgets' for each field in you Form that need configuration.
Check the documentation 'Widgets in forms', or even, you can define your own Widgets.
I want get college data using general_info foreign key. without making nested serializer of college_set in GeneralInfo serializer. Is there any alternative in django rest framework or is not possible? I have tried above below line of code but its not working. is there any other way?
college = serializers.CharField(source='general_info.college_set', read_only=True)
models.py
from django.db import models
class GeneralInfo(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
address = models.CharField(max_length=30)
class Student(models.Model):
general_info = models.ForeignKey(to=GeneralInfo, on_delete=models.PROTECT)
course = models.CharField(max_length=30)
marks = models.CharField(max_length=30)
class College(models.Model):
general_info = models.OneToOneField(to=GeneralInfo, on_delete=models.PROTECT)
name = models.CharField(max_length=30)
address = models.CharField(max_length=30)
picture = models.ImageField(null=True, blank=True, upload_to='users/')
serializer.py
from rest_framework import serializers
class MySerializer(serializers.ModelSerializer):
name = serializers.CharField(source='general_info.first_name', read_only=True)
college = serializers.CharField(source='general_info.college_set', read_only=True)
class Meta:
model = Student
fields = ('name', 'college')
I am having an issue with 2 Foreign Key assignments in my django model. See models.py below:
from django.db import models
from django.contrib.auth.models import User
class userData(models.Model):
user = models.ForeignKey(User)
house = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=True, null=True)
street = models.CharField(max_length=150)
state = models.CharField(max_length=100)
postcode = models.CharField(max_length=20)
country = models.CharField(max_length=100)
telephone = models.CharField(max_length=20)
subscription = models.IntegerField(default=0)
active = models.IntegerField(default=0)
class area(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class country(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class city(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class foodType(models.Model):
food_type_name = models.CharField(max_length=100)
class restaurant(models.Model):
restaurant_name = models.CharField(max_length=100)
food_type = models.ForeignKey(foodType)
area = models.ForeignKey(area)
country = models.ForeignKey(country)
city = models.ForeignKey(city)
date_added = models.DateField()
main_image = models.ImageField(blank=True, null=True)
website = models.URLField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
featured = models.IntegerField(default=0)
class restaurantFeature(models.Model):
feature_name = models.CharField(max_length=100)
restaurant_id = models.ForeignKey(restaurant)
Django Foreign Key not working correctly
The image shows the Country and City, not showing correctly, like the FoodType and Area does. Theses show with the + buttons for adding, the mysql database is showing the key next to the fields. I have also tried renaming country and City adding Location after, thinking it could be something with these names.
Appreciate any help with this one.
You're having this issue because you need to reference ALL the models inside the admin.py. Django admin doesn't know what you're referencing.
I have been trying to design a rest API using Django Rest Framework for creating mobile application. I could design an API for Store list which shows store owner(merchant) information, store information, category of store and Product but product image is not displayed. Why my code is not showing product image? Could anyone please provide me an idea or advice why it is not working?
My code
my models.py
class Store(models.Model):
merchant = models.ForeignKey(Merchant)
name_of_store = models.CharField(max_length=100)
store_off_day = MultiSelectField(choices=DAY, max_length=7, default='Sat')
store_categories = models.ManyToManyField('StoreCategory',blank=True)
class Meta:
verbose_name = 'Store'
class Product(models.Model):
store = models.ForeignKey(Store)
name_of_product = models.CharField(max_length=120)
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=20)
# categories = models.ManyToManyField('Category',blank=True)
class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField(upload_to='products/images/')
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
class StoreCategory(models.Model):
product = models.ForeignKey(Product,null=True, on_delete=models.CASCADE,related_name="store_category")
store_category = models.CharField(choices=STORE_CATEGORIES, default='GROCERY', max_length=10)
Serializers.py
class ProductImageSerializer(ModelSerializer):
class Meta:
model = ProductImage
fields = ('id','image', )
class ProductSerializers(ModelSerializer):
image = ProductImageSerializer(many=True,read_only=True)
class Meta:
model = Product
fields=('id','image','name_of_product','description','price','active',)
class StoreCategorySerializer(ModelSerializer):
product = ProductSerializers(read_only=True)
class Meta:
model = StoreCategory
class StoreSerializer(ModelSerializer):
# url = HyperlinkedIdentityField(view_name='stores_detail_api')
store_categories = StoreCategorySerializer(many=True)
merchant = MerchantSerializer(read_only=True)
class Meta:
model = Store
fields=("id",
# "url",
"merchant",
"store_categories",
"name_of_store",
"store_contact_number",
"store_off_day",
)
My API
In your models.py create:
import os
Remove Product foreign key from your ProductImage model:
class ProductImage(models.Model):
image = models.ImageField(upload_to='products/images/')
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
#property
def imagename(self):
return str(os.path.basename(self.image.name))
Add image foreign key to your Product instead
class Product(models.Model):
image = models.ForeignKey(ProductImage,blank=True,null=True)
store = models.ForeignKey(Store)
name_of_product = models.CharField(max_length=120)
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=20)
# categories = models.ManyToManyField('Category',blank=True)
and then in your serializers.py
class ProductImageSerializer(ModelSerializer):
class Meta:
model = ProductImage
fields = ('id','imagename', )
class ProductSerializers(ModelSerializer):
image = ProductImageSerializer(many=False,read_only=True) #only one image used
class Meta:
model = Product
fields=('id','image','name_of_product','description','price','active',)
So this way you'll get the actual image name and location.