I've created a model of analysis types and then I created a table that groups several analyses into one group:
class AnalysisType(models.Model):
a_name = models.CharField(max_length=16,primary_key=True)
a_measur = models.CharField(max_length=16)
a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
# analysis_group = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1)
def __str__(self):
return f"{self.a_name} - {self.a_measur}"
class AnalysysGroup(models.Model):
group_name = models.CharField(max_length=32)
analysis = models.ManyToManyField(AnalysisType, blank=True)
def __str__(self):
return f"{self.group_name}"
I want to have the option to multiply add values via the admin panel (I.E. I chose Analysis type then below appear fields to fill)
class PatientGroupAnalysis(models.Model):
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
analysis_date = models.DateTimeField()
analysis_type = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1)
# amalysis_data = ???
def __str__(self):
return f"{self.patient}: {self.analysis_date} - {self.analysis_type} - {self.analysis_data}"
I tried to use analysis_data = analysis.type.objects.all() and etc. but that's the wrong way.
Try this:
Admin panel with StackedInline
from django.contrib import admin
from .models import AnalysisType, PatientGroupAnalysis
# Register your models here.
class PatientGroupAnalysisInline(admin.StackedInline):
model = PatientGroupAnalysis
#admin.register(AnalysisType)
class AnalysisTypeAdmin(admin.ModelAdmin):
list_display = ["id", "a_name", "a_measur", "a_ref_min", "a_ref_max"]
search_fields = ("id", "a_name")
inlines = [PatientGroupAnalysisInline]
Related
I'm doing a cookbook app, which help users find meal thay can do with their ingridients. I'm using Django RestFramework, and i need to return list of avaliable meals that user can do, but don't know how to do search by ingridients
My models.py:
#models.py
class Meal(models.Model):
name = models.CharField(max_length=250)
description = models.TextField(blank=True, null=True)
recipe = models.TextField()
is_published = models.BooleanField(default=False)
category = ForeignKey('Category', on_delete=models.CASCADE, null=True)
user = ForeignKey(User, verbose_name='User', on_delete= models.CASCADE)
difficulty = ForeignKey('Difficulty', on_delete=models.PROTECT, null=True)
ingridients = models.ManyToManyField('Ingridient')
class Ingridient(models.Model):
name = models.CharField(max_length=100, db_index=True)
ico = models.ImageField(upload_to="photos/%Y/%m/%d/", blank=True, null=True)
category = ForeignKey('CategoryIngridients', on_delete=models.CASCADE, null=True)
def __str__(self):
return self.name
class CookBookUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
ingridients = models.ManyToManyField('Ingridient')
serializer.py
class MealSerializer(serializers.ModelSerializer):
class Meta:
model = Meal
fields = "__all__"
views.py
class CraftWithUsersIngridientsListAPIView(generics.ListAPIView):
serializer_class = MealSerializer
def get_queryset(self):
return Meal.objects.filter(ingridients=CookBookUser.objects.filter(user_id = self.request.user.id).ingridients)
CraftWithUsersIngridientsListAPIView isn't working and I get AttributeError 'QuerySet' object has no attribute 'ingridients', can someone help fix this?
I tried building different serializer but it doesn't help
class CraftWithUsersIngridientsListAPIView(generics.ListAPIView):
serializer_class = MealSerializer
def get_queryset(self):
user_ingredients = CookBookUser.objects.get(user=self.request.user).ingredients.all()
return Meal.objects.filter(ingredients__in=user_ingredients)
This way, you first get the CookBookUser instance for the current user, then get all of their ingredients, and finally, filter the Meal objects that contain those ingredients. The __in query lookup is used to check if the meal ingredients are in the user's ingredients.
I'm trying to make a Django model, with Django Rest Framework. I want this to allow me to load one or more images in the same input.
MODELS:
from django.db import models
from datetime import datetime
from apps.category.models import Category
from django.conf import settings
class Product(models.Model):
code = models.CharField(max_length=255, null=True)
name = models.CharField(max_length=255)
image = models.ImageField(upload_to='photos/%Y/%m/', blank = True, null=True, default='')
description = models.TextField()
caracteristicas = models.JSONField(default=dict)
price = models.DecimalField(max_digits=6, decimal_places=2)
compare_price = models.DecimalField(max_digits=6, decimal_places=2)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
quantity = models.IntegerField(default=0)
sold = models.IntegerField(default=0)
date_created = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.name
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name = 'images')
image = models.ImageField(upload_to='photos/%Y/%m/', default="", null=True, blank=True)
SERIALIZER:
from rest_framework import serializers
from .models import Product, ProductImage
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = ["id", "product", "image"]
class ProductSerializer(serializers.ModelSerializer):
images = ProductImageSerializer(many=True, read_only=True)
uploaded_images = serializers.ListField(
child = serializers.ImageField(max_length = 1000000, allow_empty_file = False, use_url = False),
write_only=True
)
class Meta:
model = Product
fields = [
'id',
'code',
'name',
'description',
'caracteristicas',
'price',
'compare_price',
'category',
'quantity',
'sold',
'date_created',
'images',
'uploaded_images'
]
def create(self, validated_data):
uploaded_images = validated_data.pop("uploaded_images")
product = Product.objects.create(**validated_data)
for image in uploaded_images:
newproduct_image = ProductImage.objects.create(product=product, image=image)
return product
I would simply like how to make the following input field allow me to load more than one image:
Imagen de referencia input
thank you very much
You didn't post your admin.py but my guess is that you also need to register your ProductImage model as an inlines since you already use a One2Many relationship between Product and ProductImage:
In your admin.py:
class ProductImageAdmin(admin.StackedInline):
model = ProductImage
class ProductAdmin(admin.ModelAdmin):
inlines = [ProductImageAdmin]
class Meta:
model = Product
admin.site.register(ProductImage)
admin.site.register(Product, ProductAdmin)
You can also check this SO answer out for more details.
Hope that helps :)
I'm building a simple Lead Generator using Django Rest Framework.
I'm trying to show a list of "assigned facilities" inside a lead using django's many to many fields. But all it will show inside the API is the id of each of the facilities associated to the many to many field. How do I access more than just the name using DRF? I basically need to show the name, a description and a picture of the facility from each facility record.
serializers.py
class LeadUpdateSerializer(serializers.ModelSerializer):
is_owner = serializers.SerializerMethodField()
class Meta:
model = Lead
fields = (
"id",
"first_name",
"last_name",
"PrimaryAddress",
"assigned_facilities",
)
read_only_fields = ("id", "is_owner")
def get_is_owner(self, obj):
user = self.context["request"].user
return obj.agent == user
models.py
class Facility(models.Model):
UUID = models.CharField(max_length=150, null=True, blank=True)
Name = models.CharField(max_length=150, null=True, blank=False)
mainimage = models.ImageField(null=True, blank=True)
FacilityDescription = models.TextField(max_length=1000, null=True, blank=True)
def __str__(self):
return self.Name
class Lead(models.Model):
assigned_facilities = models.ManyToManyField(Facility, related_name='assigned_facilities')
created_at = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=40, null=True, blank=True)
last_name = models.CharField(max_length=40, null=True, blank=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
We can like below:
class FacilitySerializer(serializers.ModelSerializer)
class Meta:
fields = (
"id",
"Name",
"mainimage",
"FacilityDescription",
)
class LeadUpdateSerializer(serializers.ModelSerializer):
assigned_facilities = FacilitySerializer(many=True)
is_owner = serializers.SerializerMethodField()
class Meta:
model = Lead
fields = (
"id",
"first_name",
"last_name",
"PrimaryAddress",
"assigned_facilities",
)
read_only_fields = ("id", "is_owner")
def get_is_owner(self, obj):
user = self.context["request"].user
return obj.agent == user
please I want to select the list of cycles by Program_de_bourse, know that in my actual form I can select all the cycles , but I just want to select the cycles linked to Program_de_bourse my foreign key Program_de_bourse = id of Program_de_bourse
the model.py
class Cycle(models.Model):
Programme_de_bourse = models.ForeignKey(Programme_de_bourse, on_delete=models.SET_NULL, null=True)
Objet_programme = models.CharField(
max_length=30,
choices=objet_CHOICES, verbose_name='Cycle'
)
def __str__(self):
return self.Objet_programme
..
class Discipline(models.Model):
Discipline = models.ForeignKey(Disc, on_delete=models.CASCADE, related_name='Discipline_cycle')
Cycle = models.ForeignKey(Cycle, on_delete=models.SET_NULL, null=True)
Programme_de_bourse = models.ForeignKey(Programme_de_bourse, on_delete=models.SET_NULL, null=True,
related_name='Programme_de_bourse_id')
def __str__(self):
return str(self.Discipline)
my admin.py
class Programme_de_bourseAdmin(ExportActionMixin, admin.ModelAdmin):
fieldsets = [
('Programme', {'fields': ['Programme']}),
#'classes': ['collapse']
#
]
list_display = ["Programme",]
inlines = [CycleInline, DisciplineInline, ConditionInline, EtablissementInline, DocumentInline]
class DisciplineInline(ExportActionMixin, admin.TabularInline):
)
model = Discipline
enter image description here
try this
you can create a form for class DisciplineInline and add a filter over there
this might work with some changes
class DisciplineForm(forms.ModelForm):
Programme_de_bourse = forms.ModelChoiceField(queryset='....') # your filter
class Meta:
model = Discipline
fields = ('....')
class DisciplineInline(ExportActionMixin, admin.TabularInline):
model = Discipline
form = DisciplineForm
this is work for me to get cycle by Program_de_bourse_id = 7, now i want replace 7 with real id of Program_de_bourse, so how a can get the id of Program_de_bourse from my function Program_de_bourseAdminrer
class DisciplineForm(forms.ModelForm):
cycle = forms.ModelChoiceField(queryset=Cycle.objects.filter(Programme_de_bourse=7))
class Meta:
model = Discipline
fields = ('cycle','Discipline')
I've been stuck on this for a few days (new to django) and can't figure out how to update skills for a specific user model using a ManyToManyField, while simultaneously updating a skill model containing a list of skills. Currently when I enter a value in my SkillForm, it updates the skill model properly and creates a dropdown list of skills for a given CustomUser in the admin. However, I can't figure out how to assign a SPECIFIC skill to a particular user. Any help is appreciated.
models.py:
class Skill(models.Model):
name = models.CharField(max_length =50, null=True, default='')
def __str__(self):
return self.name
class CustomUserManager(UserManager):
pass
class CustomUser(AbstractUser):
objects = CustomUserManager()
skills = models.ManyToManyField(Skill, null=True, blank=True)
position = models.CharField(max_length =50, null=True, default='')
bio = models.CharField(max_length=300, null=True, default='')
admin.py:
class SkillsInline(admin.StackedInline):
model = CustomUser.skills.through
class SkillAdmin(admin.ModelAdmin):
inlines = [SkillsInline ,]
UserAdmin.fieldsets += ('Custom fields set', {'fields': ('position', 'bio', )}),
class CustomUserAdmin(UserAdmin):
model = CustomUser
add_form = CustomUserCreationForm
form = EditProfile
inlines = [SkillsInline ,]
admin.site.register(CustomUser, CustomUserAdmin)
forms.py:
class SkillForm(forms.ModelForm):
name = forms.CharField()
class Meta:
model = Skill
fields =('name' ,)
def clean(self):
cleaned_data = super().clean()
name = cleaned_data.get('name')
I see somes problem here :
class CustomUser(AbstractUser):
objects = CustomUserManager()
skills = models.ManyToManyField(Skill, null=True, blank=True)
position = models.CharField(max_length =50, null=True, default='')
bio = models.CharField(max_length=300, null=True, default='')
When you define an AbstractUser` class, it's mean for Django Authentification purpose, see the doc here., dont do that because it's better to have an unique entry (each user have an unique entry, so you can login each one).
In your system you dont have unique CustomUser, here is a solution IMO:
class User(AbstractUser):
email = models.EmailField(_('email'), unique=True)
class UserAction(models.Model):
objects = CustomUserManager()
user = models.ForeignKey(User, verbose_name="User")
skills = models.ManyToManyField(Skill, null=True, blank=True)
position = models.CharField(max_length =50, null=True, default='')
bio = models.CharField(max_length=300, null=True, default='')
class Skill(models.Model):
name = models.CharField(max_length =50, null=True, default='')
def __str__(self):
return self.name
You now have an unique User, a list of UserAction that have a related Skill
user = User.objects.create(email='my#email.com')
skill = Skill.objects.create(name="shadow step")
user_action = UserAction.objects.create(user=user, skill=skill, position='HERE', bio='10')
Is that what you needed ?