Django smart selects - django

I try to chain material and categorie with django smart select but it does not work
What is wrong in my code ?
class Demande_Expertise(models.Model):
user = models.ForeignKey(User)
material = models.ForeignKey("Material")
categorie = ChainedForeignKey("material.Category",
chained_field="material",
chained_model_field="name",
show_all=False,
auto_choose=True)
droits_acces = models.CharField(_('val_champ'), max_length=150, choices = DROITS)
groupe = models.ForeignKey(Group, blank = True, null= True, default = None)
etat = models.CharField(_('val_champ'), max_length=150, choices = ETAT, default = '2')
class Category(models.Model):
name = models.CharField(_('name'), max_length=50)
slug = models.SlugField()
class Material(models.Model):
name = models.CharField(_('name'), max_length=50)
description = models.TextField(_('description'), blank=True)
slug = models.SlugField()
category = ChainedForeignKey(Category, verbose_name=_('category'),
chained_field="name",
chained_model_field="name",
show_all=False,
auto_choose=True)
created = models.DateField(_("creation date"), auto_now_add=True)

Try Django Clever Selects
https://github.com/PragmaticMates/django-clever-selects
I use it in my Django 1.6 project

Your structure is incorrect I am giving you an example that works
class Continent(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Country(models.Model):
continent= models.ForeignKey(Continent)
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class City(models.Model):
continent= models.ForeignKey(Continent)
country= ChainedForeignKey(Country, chained_field="continent", chained_model_field="continent", show_all=False, auto_choose=True, sort=True)
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Neighborhood(models.Model):
continent= models.ForeignKey(Continent)
country= ChainedForeignKey(Country, chained_field="continent", chained_model_field="continent", show_all=False, auto_choose=True, sort=True)
name = models.CharField(max_length=255)
city= ChainedForeignKey(City, chained_field="country", chained_model_field="country", show_all=False, auto_choose=True, sort=True)
name = models.CharField(max_length=255)
def __str__(self):
return self.name

Related

How can i make a Query through Many-To-Many-Relationship

I want to display the trainer for a course date. A course can have several dates and a different trainer can be used on each date. A trainer can have a different role on each course date. (Instructor, helper...)
How do I make the correct query? Are the models correct for this?
Models:
class Course_dates(models.Model):
date = models.DateField()
start = models.TimeField()
end = models.TimeField()
def __str__(self):
return str(self.id)
"""return self.date.strftime("%d.%m.%Y")"""
class Course(models.Model):
course_number = models.CharField(max_length=24, blank=True)
course_location = models.ForeignKey(Course_location, on_delete=models.CASCADE)
course_dates = models.ManyToManyField('Course_dates', through="Course_Course_dates")
def __str__(self):
return self.course_number
class Trainer_Course_Course_date_role(models.Model):
trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE)
role = models.CharField(max_length=24, blank=True)
def __str__(self):
return str(self.id)
class Course_Course_dates(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
course_dates = models.ForeignKey(Course_dates, on_delete=models.CASCADE)
trainer = models.ForeignKey(Trainer_Course_Course_date_role, on_delete=models.CASCADE, null=True)
def __str__(self):
return str(self.id)
class Trainer(models.Model):
salutation = models.CharField(max_length=8,choices=GENDER_CHOICES)
last_names = models.CharField(max_length=56)
first_names = models.CharField(max_length=56)
date_of_birth = models.DateField()
address = models.ForeignKey(Address, on_delete=models.CASCADE)
email = models.EmailField()
phone = models.CharField(max_length=56, blank=True)
mobile = models.CharField(max_length=56, blank=True)
def __str__(self):
return self.last_names
View:
def course(request):
courses = Course.objects.all()
course_list = []
for course in courses:
sorted_date_list = course.course_dates.all().order_by('date')
course_list.append({'course': course, 'sorted_date_list': sorted_date_list })
context = { 'course_list': course_list, }
return render(request, 'kursverwaltung_tenant/course.html', context)

Django Why is one field created when I apply migrations?

There are models, why after python manage.py makemigrations is created only by 1 field in migrations, how to fix it? I tried doing manage.py migrate --fake zero, and doing the migrations again, but nothing.The app is registered in settings.
from django.db import models
from django.urls import reverse
class Category(models.Model):
image = models.ImageField(default='default.png', upload_to='category_image'),
title = models.CharField(max_length=50, db_index = True),
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('category_detail_url', kwargs={'title': self.title})
class Provider(models.Model):
name = models.CharField(max_length=50, db_index = True),
phone_number = models.CharField(max_length=12, db_index = True),
address = models.CharField(max_length=50, db_index = True),
def __str__(self):
return self.name
class Product(models.Model):
title = models.CharField(max_length=50, db_index = True),
receipt_date = models.DateTimeField(auto_now_add=True, blank=True),
quantity_stock = models.IntegerField(),
quantity_store = models.IntegerField(),
purchase_price = models.IntegerField(),
image = models.ImageField(default='default.png', upload_to='product_image'),
provider = models.ForeignKey(Provider, null = True ,related_name='to_provider',on_delete=models.CASCADE),
category = models.ForeignKey(Category, null = True ,related_name='to_category',on_delete=models.CASCADE),
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('product_detail_url', kwargs={'title': self.title})
class Sale(models.Model):
product = models.ForeignKey(Product, related_name='to_product',on_delete=models.CASCADE),
date_of_sale = models.DateTimeField(auto_now_add=True, blank=True),
quantity_goods_sold = models.IntegerField(),
retail_price = models.IntegerField(),
def __str__(self):
return self.id
Your fields should not end with a comma (,). If you add a trailing comma, it will wrap the field in a singleton tuple, and thus Django is then not able to detect the field:
from django.db import models
from django.urls import reverse
class Category(models.Model):
image = models.ImageField(default='default.png', upload_to='category_image')
title = models.CharField(max_length=50, db_index = True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('category_detail_url', kwargs={'title': self.title})
class Provider(models.Model):
name = models.CharField(max_length=50, db_index=True)
phone_number = models.CharField(max_length=12, db_index=True)
address = models.CharField(max_length=50, db_index=True)
def __str__(self):
return self.name
class Product(models.Model):
title = models.CharField(max_length=50, db_index = True)
receipt_date = models.DateTimeField(auto_now_add=True, blank=True)
quantity_stock = models.IntegerField()
quantity_store = models.IntegerField()
purchase_price = models.IntegerField()
image = models.ImageField(default='default.png', upload_to='product_image')
provider = models.ForeignKey(
Provider,
null=True,
related_name='products',
on_delete=models.CASCADE
)
category = models.ForeignKey(
Category,
null=True,
related_name='products',
on_delete=models.CASCADE
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('product_detail_url', kwargs={'title': self.title})
class Sale(models.Model):
product = models.ForeignKey(
Product,
related_name='sales',
on_delete=models.CASCADE
)
date_of_sale = models.DateTimeField(auto_now_add=True, blank=True)
quantity_goods_sold = models.IntegerField()
retail_price = models.IntegerField()
def __str__(self):
return self.id

'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'

'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'.
i am getting error on 'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'. any help, would be appreciated.
'DemoAppProductUpdateDestroySerializer' object has no attribute
'get_image'
models.py
class Product(models.Model):
title = models.CharField(max_length=30)
slug= models.SlugField(blank=True, null=True)
sku = models.CharField(max_length=30)
description = models.TextField(max_length=200, null=True, blank=True)
instruction = models.TextField(max_length=200, null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits= 10,)
discount_price= models.DecimalField(decimal_places=2, max_digits= 10, null=True, blank=True)
brand = models.ForeignKey("Brand", null=True, blank=True, on_delete=models.CASCADE)
waist = models.ForeignKey("Waist", null=True, blank=True, on_delete=models.CASCADE)
occasion = models.ForeignKey("Occasion", null=True, blank=True, on_delete=models.CASCADE)
style = models.ForeignKey("Style", null=True, blank=True, on_delete=models.CASCADE)
neck = models.ForeignKey("Neck", null=True, blank=True, on_delete=models.CASCADE)
fit = models.ForeignKey("Fit", null=True, blank=True, on_delete=models.CASCADE)
pattern_type = models.ForeignKey("Pattern_Type", null=True, blank=True, on_delete=models.CASCADE)
color = models.ForeignKey("Color", null=True, blank=True, on_delete=models.CASCADE)
size = models.ManyToManyField("Size", null=True, blank=True)
sleeve = models.ForeignKey("Sleeve_Length", null=True, blank=True, on_delete=models.CASCADE)
material = models.ForeignKey("Material", null=True, blank=True, on_delete=models.CASCADE)
category = models.ManyToManyField('Category', )
default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE)
created_on = models.DateTimeField(default=timezone.now)
updated_on = models.DateTimeField(null=True, blank=True)
status = models.BooleanField(default=True)
class Meta:
ordering = ["-id"]
def __str__(self): #def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk": self.pk})
def get_image_url(self):
img = self.productimage_set.first()
if img:
return img.image.url
return img #None
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(pre_save_post_receiver, sender=Product)
def image_upload_to(instance, filename):
title = instance.product.title
slug = slugify(title)
basename, file_extension = filename.split(".")
new_filename = "%s-%s.%s" %(slug, instance.id, file_extension)
return "products/%s/%s" %(slug, new_filename)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
image = models.ImageField(upload_to=image_upload_to)
created_on = models.DateTimeField(default=timezone.now)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.product.title
views.py
class ProductUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
model = Product
queryset = Product.objects.all()
serializer_class = DemoAppProductUpdateDestroySerializer
permission_classes = [IsAdminUser]
authentication_classes = [BasicAuthentication]
serializers.py
class DemoAppProductUpdateDestroySerializer(serializers.ModelSerializer):
image = serializers.SerializerMethodField()
class Meta:
model = Product
fields=[
"id",
"title",
"slug",
"sku",
"price",
"discount_price",
"image",
]
def get_image(self, obj):
return obj.productimage_set.first().image.url

how to save multiple model-forms (which are in 1:1) simultaneously in a view (Django)

how to save multiple model-forms (lAWYER AND CATEGORY) (which are in 1:1) simultaneously in a view (Django)
class Lawyer(models.Model):
category = models.ForeignKey(Category, related_name='lawyer', on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, related_name='profiles', on_delete=models.CASCADE)
name = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
class Category(models.Model):
profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE)
category_name = models.CharField(max_length=10, db_index=True,choices=CATEGORY_CHOICES)
slug = models.SlugField(max_length=150, unique=True, db_index=True)
city = models.CharField(max_length=20)
IN VIEWS.PY
def lawyer_list(request, category_slug=None):
if request.method == 'POST':
cat_form = CategoryForm(request.POST)
if cat_form.is_valid():
cat_obj = cat_form.save(commit=False)
cat_obj.profile = request.user.profile
cat_obj.save()
lawyer_form = LawyerForm(request.POST)
if lawyer_form.is_valid():
lawyer_form = lawyer_form.save(commit=False)
lawyer_form.profile = request.user.profile
lawyer_form.category = cat_obj
lawyer_form.save()
ALSO HAVE TWO FORMS
1) class LawyerForm(forms.ModelForm)
2)class CATEGORYForm(forms.ModelForm)
IN VIEWS I DONT WANT TO MAKE TWO OBJECT
Forms.py
enter code here
CATEGORY_CHOICES = (('CRIMINAL', 'Criminal'),('EMPLOYMENT', 'Employment'),
('CORPORATE', 'Corporate'),)
class CategoryForm(forms.ModelForm):
category_name = forms.CharField(max_length=3,
widget=forms.Select(choices=CATEGORY_CHOICES),)
class Meta:
model = Category
fields = ('category_name','city',)
class LawyerForm(forms.ModelForm):
class Meta:
model = Lawyer
fields = ('name','description','charge','available',)
class Lawyer(models.Model):
category = models.ForeignKey(Category, related_name='lawyer', on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, related_name='profiles', on_delete=models.CASCADE)
name = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
class Category(models.Model):
profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE)
category_name = models.CharField(max_length=10, db_index=True,choices=CATEGORY_CHOICES)
slug = models.SlugField(max_length=150, unique=True, db_index=True)
city = models.CharField(max_length=20)
def save(self, *args, **kwargs):
lawyer=Lawyer(*args,**kwargs)
lawyer.category=self
lawyer.save()
super(Category, self).save(*args, **kwargs)
in views
def lawyer_list(request, category_slug=None):
if request.method == 'POST':
cat_form = CategoryForm(request.POST)
if cat_form.is_valid():
cat_obj = cat_form.save(commit=False)
cat_obj.profile = request.user.profile
cat_obj.save()

How To a autoselect Patient Name field when bed assign to patients in Django

How To assign bed to Patient Django?
when I try to assign bed to Patient at that time in bedconfig automatically select Patient Name
then wardconfig file open but Patient name is blant, it must be autoselected Patient name
view this image When click on assign bed
but Patient name is blant, it must be autoselected Patient name
models.py Patient model
class Patient(Auditable):
aadhar_no = models.CharField(max_length=12, blank=True,unique=True)
fullname = models.CharField(max_length=50)
firstname = models.CharField(max_length=30)
middlename = models.CharField(max_length=30)
lastname = models.CharField(max_length=30)
CATEGORY_GENDER= (('Male', 'Male'), ('Female', 'Female'))
gender = models.CharField(max_length=6, choices=CATEGORY_GENDER)
CATEGORY_BG= (('Not known','Not known'),('A+', 'A+'), ('A-', 'A-'),('B+', 'B+'),('B-', 'B-'),('AB+', 'AB+'),('AB-','AB-'),('O+','O+'), ('O-','O-'))
blood_group = models.CharField(max_length=10, choices=CATEGORY_BG)
dob = models.DateField() #Date of birth
photo = models.ImageField(upload_to="Patient/", null=True, blank=True)
education = models.CharField(max_length=15, null=True, blank=True)
CATEGORY_OCC= (('Service', 'Service'), ('Retired', 'Retired'),('Housewife', 'Housewife'), ('Business','Business'),('other','other'))
occupation = models.CharField(max_length=15, choices=CATEGORY_OCC,null=True, blank=True) #service, retired, Housewife, Business, others
current_address = models.TextField()
mobile_number = models.CharField(max_length=12)
mobile_number2 = models.CharField(max_length=12, null=True, blank=True)
phone_number = models.CharField(max_length=12, null=True, blank=True)
email = models.CharField(max_length=30, null=True, blank=True)
country = models.ForeignKey(Country , null=True, blank=True, )
state = models.ForeignKey(State , null=True, blank=True)
district = models.ForeignKey(District , null=True, blank=True)
city = models.ForeignKey(City ,null=True, blank=True)
recreational_drugs= models.BooleanField(default=False) #alocohol, smoking,coffine etc.
current_insurance = models.BooleanField(default=False)
#family = models.ForeignKey(Family) # Family
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self): # __unicode__ on Python 2
# return self.fullname
return str(self.fullname)
class Meta:
verbose_name_plural = "Patient"
models.py WardConfog
class WardConfig(Auditable):
bed = models.ForeignKey(Bed)
ward = models.ForeignKey(Ward)
patient=models.ForeignKey(Patient)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#def __str__(self): # __unicode__ on Python 2
#return self.name
class Meta:
verbose_name_plural = "Wardconfig"
Views.py PatientCreate(CreateView)
class PatientCreate(CreateView):
model = Patient
form_class = PatientForm
def get_success_url(self):
return reverse_lazy( 'patient')
def form_valid(self,PatientForm):
PatientForm.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, PatientForm):
return self.render_to_response(self.get_context_data(form=PatientForm))
Views.py
class WardConfig(Auditable):
bed = models.ForeignKey(Bed)
ward = models.ForeignKey(Ward)
patient=models.ForeignKey(Patient)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#def __str__(self): # __unicode__ on Python 2
#return self.name
class Meta:
verbose_name_plural = "Wardconfig"
please Guys Help me how auto select Patient Name IN Wardconfig when assign bed
Sorry for English
You can give the view you are using to add a WardConfig record a get_initial method. This assumes you are passing a patient_id kwarg in the URL:
def get_initial(self):
patient = get_object_or_404(Patient, pk=self.kwargs.get('patient_id'))
return {
'patient': patient,
}