I'm trying to create a profile for clinics where I can show doctors under each specialization. I want to show the specialization with most doctors to least doctors.
For instance:
Dentists:
Names of all dentists (7)
Pediatricians
Names of pediatricians (4)
OB/GYN
Names of all obgyns (2)
models.py
class Doctor(models.Model):
name = models.CharField(max_length=1300)
specialization = models.ForeignKey(Specialization, related_name = "doctor_specialization")
sub_specialization = models.ForeignKey(Specialization, related_name = "doctor_subSpecialization", null = True, blank = True)
clinic = models.ForeignKey(Clinic)
class Clinic(models.Model):
name = models.CharField(max_length=500)
slug = models.CharField(max_length=200, blank = True, null = True, unique = True)
contact_no = models.IntegerField()
class Specialization(models.Model):
name = models.CharField(max_length=30)
views.py
def clinicProfile(request, slug):
clinic = get_object_or_404(Clinic, slug=slug)
doctors = Doctor.objects.all().order_by('-netlikes')
d.update({'clinic': clinic, 'doctors': doctors, })
return render(request, 'm1/clinicprofile.html', d)
It's simple.Instead of using ('-netlikes') just use ('netlikes') and it should work. Your function should look like this.
def clinicProfile(request, slug):
clinic = get_object_or_404(Clinic, slug=slug)
doctors = Doctor.objects.all().order_by('netlikes')
You need backward annotation, and it will look like:
from django.db.models import Count, Min, Sum, Avg
specialization = Specialization.objects.annotate(Count('doctor'))
Related
error: 'Questions' object is not iterable
models.py code:
class Questions(models.Model):
title = models.CharField(max_length = 150)
slug = models.SlugField(max_length = 10, unique = True)
body = models.TextField()
category = models.ManyToManyField(Category, related_name = "questions")
author = models.ForeignKey(User, on_delete = models.CASCADE)
created = models.DateTimeField(auto_now_add = True)
picture = models.ImageField(upload_to = "questions/%Y/%m/%d", null = True, blank = True)
status = models.BooleanField(default = True)
def get_absolute_url(self):
return reverse("questions:ques_detail", args = [self.slug, self.id])
views.py code:
def QuestionDetail(request, question, pk):
question = get_object_or_404(Questions, slug = question, id = pk)
return render(request, "questions/ques_detail.html", {"questions": question})
urls.py code:
urlpatterns = [
path('<slug:question>/<int:pk>', QuestionDetail, name = "questiondetail")
I guess there is a misunderstanding somewhere.
Indeed what do you want to achieve ?
If you want to retrieve a single instance your code looks good but it does not make any sense to iterate on an instance.
If you want to retrieve a QuerySet, then you would have to create another view. For exemple :
def questions(request):
questions = get_list_or_404(Questions)
return render(request, "questions/ques_detail.html", {"questions": questions})
Also you should take care of naming your function and variable in a pythonic way.
Some docs might be found here
I don't know how to actually write the logic but I want to check user inputs especially price form field against Product model (price property).
I have model the django form as below:
class SalesForm(forms.ModelForm):
class Meta:
model = Sales
fields = ['product', 'customer', 'quantity', 'price']
Here is the Product Model
class Product(models.Model):
name = models.CharField(max_length=100, null=True)
category = models.CharField(max_length=100, choices=CATEGORY, null=True)
cost = models.PositiveIntegerField(null=True)
price = models.PositiveIntegerField(null=True)
quantity = models.PositiveIntegerField(null=True)
Here is what I am trying to do logically in views.py
def user_add_sales(request):
sales = Sales.objects.all().order_by('-salesdate')[:5]
if request.method == 'POST':
sales_form = SalesForm(request.POST)
if sales_form.is_valid:
sales_price = sales_form.cleaned_data('price')
try:
user_input = Product.objects.get(price = sales_price)
sales_form.save()
messages.success(request, 'Sales Added Successfully')
return redirect('dashboard-user-sales')
except user_input.DoesNotExist:
sales_form = SalesForm()
else:
sales_form = SalesForm()
context = {
'sales' : sales,
'sales_form' : sales_form,
}
return render(request, 'dashboard/user_sales.html', context)
When Try running the code, says 'SalesForm' object has no attribute 'cleaned_data'. Someone should please help me on how I can check whether what the user enters in price field of the SalesForm is not less than the price set for that product in Product Model.
The form is validated by the sales_form.is_valid() method, not by an attribute, the if condition is thus:
if sales_form.is_valid():
# …
# …
In your form, you can check if the given price is at least the price in the related attribute with:
class SalesForm(forms.ModelForm):
# …
def clean(self, *args, **kwargs):
data = super().clean(*args, **kwargs)
if data['price'] < data['product'].price:
raise ValidationError('The price of the sale is below the price of the product')
return data
I'm creating a site to register students. So basically it is divided into 3 parts
1. A student register model which take the name, fathername, etc of student.
2. A student fee model which use foreignkey to get register student.
3. ModelForm for showing student fee model to enter data.
Now the problem if I want to fill a student fee of class 1 it shows all the student of other classes, but I want the student filter according to their classes and their name show and in front of them editable fee and pending fee form.
By some reach I got to know about ModelForm instance I wrote code for automatically add register students to student fee.
def student_fee(request):
# add a selection field to a variable for filtering student_class below this.
students = StudentRegister.objects.filter(student_class="1")
....
for x in students:
if not StudentFee.objects.filter(student=x):
StudentFee.objects.create(student=x, fee=0, pending_fee=0)
But for instance I have to know primary key of every student I can loop through them but it only get the last element.
models.py
class StudentRegister(models.Model):
student_image = models.ImageField(upload_to="register_student", blank=True)
student_class = models.CharField(max_length=2, choices=STUDENT_CLASS, default="1")
mobile_number = models.CharField(max_length=50)
student_name = models.CharField(max_length=50)
father_name = models.CharField(max_length=50)
mother_name = models.CharField(max_length=50)
address = models.CharField(max_length=200)
student_fee = models.CharField(max_length=10, default="0")
Date_Of_Birth = models.DateField(auto_now=False)
admission_fee = models.CharField(max_length=10)
Admission_date = models.DateField(auto_now=False)
adhaar_no = models.CharField(max_length=100)
def __str__(self):
return "%s class: %s" % (self.student_name, self.student_class)
class StudentFee(models.Model):
student = models.ForeignKey(StudentRegister, on_delete=models.CASCADE)
fee = models.CharField(max_length=20)
pending_fee = models.CharField(max_length=20)
def __str__(self):
return "%s " % (self.student)
forms.py
class StudentFeeForm(forms.ModelForm):
class Meta:
model = StudentFee
fields = '__all__'
views.py(its messy sorry)
def student_fee(request):
# add a selection field to a variable for filtering student_class below this.
students = StudentRegister.objects.filter(student_class="1")
real = StudentFee.objects.all()
# student_form = StudentFeeForm(request.POST or None)
student_form = StudentFeeForm(request.POST)#, instance=students)
# print(dir(students))
q = (students.get(pk=1))
global list_student_pk
list_student_pk = []
for x in students:
list_student_pk.append(x.pk)
student_get_instance = StudentFeeForm(instance=q)
# print(student_get_instance)
# This thing done don't touch----------------------------------
for x in students:
if not StudentFee.objects.filter(student=x):
StudentFee.objects.create(student=x, fee=0, pending_fee=0)
if request.method == "POST":
if student_form.is_valid():
pass # this thing will done after the form problem solved.
# till here ==========================================================
return render(request, "student_fee_home.html", {"students": students, "real":real, "student_form":student_form, "list_student_pk":list_student_pk, "student_get_instance":student_get_instance})
I want that modelforms filter according to class.
Then the student fee model which already having register student(student name, fee, pending fee) can edit. So that it shows the student name and right in front of him a editable fee form and a pending fee form.
It is working right now like this showing all student of all classes, but I want that students name will show instead of selection field. In my knowledge only option to display names of student display names direct from models then use a form to take input of fee and pending fee then create it in models.
djang0-filter will help you for filtering
pip install django-filter
Model.py
class Dispatcher(models.Model):
_safedelete_policy = SOFT_DELETE
Individual = 'Individual'
Company = 'Company'
TYPES = [
(Individual, 'Individual'),
(Company, 'Company')
]
type = models.CharField(max_length=255,
choices=TYPES,
default=Individual)
Views.py
class DispatcherViewSet(viewsets.ModelViewSet):
queryset = Dispatcher.objects.all()
serializer_class = DispatcherSerializer
filter_backends = (DjangoFilterBackend,)
filterset_fields = ['type']
Hello Guys I am working on a restaurant project which allow user to select food item and book an order but i am getting this error as i try to book an order
"Django Cannot assign "'Pizza'": "Order.Food_Name" must be a "Foods" instance."
I am using drop down menu to select food items i am using django version 2.1.5 . Please Help
views.py
def place_order(request):
name = request.POST["user"]
food_items = request.POST['food_item']
qty = request.POST['qty']
rating = request.POST['ratings']
price = Foods.Food_Price
order = Order(Date=datetime.date, Name_of_Person=name,Food_Name=food_items, Qty=qty, Total=price, Ratings=rating)
order.save()
return render(request, "index.html")
model.py
from django.db import models
class Foods(models.Model):
Food_Number = models.IntegerField(null=False,)
Food_Name = models.CharField(max_length=30, primary_key=True, null=False)
Food_Qty = models.CharField(max_length=10)
Food_Price = models.IntegerField()
def __str__(self):
return f"{self.Food_Number} - {self.Food_Name} {self.Food_Price}"
class Order(models.Model):
Order_id = models.AutoField(null=False, primary_key=True)
Date = models.DateField()
Name_of_Person = models.CharField(null=False, max_length=40)
Food_Name = models.ForeignKey(Foods, on_delete=models.CASCADE)
Qty = models.CharField(max_length=10)
Total = models.IntegerField()
Ratings = models.IntegerField()
def __str__(self):
return f"{self.Order_id} - {self.Name_of_Person} |{self.Food_Name} |{self.Total}"
What can i do solve this error
Problem is in your Order model Food_Name is foreign-key field. So you need to assign model-instance which is Food in this case to this field. But you are assigning food_items = request.POST['food_item'] which is suppose to be food_name string i guess. That is why this error raise. I don't think your model is properly design. Food_Name is not an unique id field in Food model rather in your Order table you would like to have Food not Food_name.
In a Django Modelform (Product_definition), i want to have a dropdown(Merchant name) which will show users only if the their designation in User form is "Merchant".
is it possible that I could get the list of users for the dropdown based on this condition .Please note that i don't require it to be a foreign key as connecting the models is not required.
This is the form which contains the Designation :
from django.contrib.auth.models import User
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete = models.CASCADE)
#extra UserAttribute
MERCHANT = 'MR'
FABRIC = 'FR'
WASHING = 'WS'
PRINT = 'PR'
PLANNER = 'PL'
DESIGNATION_CHOICES =(
(PLANNER,'Planner'),
(MERCHANT,'Merchant'),
(FABRIC,'Fabric'),
(WASHING,'Washing'),
(PRINT,'Printing'),
)
Designation =models.CharField(
max_length = 20,
choices = DESIGNATION_CHOICES,
default= 'PLANNER'
)
def __str__(self):
return self.user.username
and this is the form with Merchant Name where I want the names of all merchants to appear.
class Product_definition(models.Model):
Order_number = models.CharField(max_length=25,unique = True, blank = True, null = True)
style_name = models.CharField(max_length=15, blank = True, null = True)
color = models.CharField(max_length=15, blank = True, null = True)
Order_qty = models.PositiveIntegerField()
SMV = models.FloatField()
MERCHANT = models.ForeignKey(UserProfileInfo,on_delete= models.CASCADE,default='Select')
def __str__(self):
return self.Order_number
I have created a foreign key for now but I don't require it and it doesn't list the names of only the merchant in the drop down.
I think you can do it like this using ModelChoiceField:
class ProductForm(forms.ModelForm): # please use CamelCase when defining Class Names
MERCHANT = forms.ModelChoiceField(queryset=UserProfileInfo.objects.filter(Designation=UserProfileInfo.MARCHENT)) # Please use sname_case when naming attributes
class Meta:
model = Product_definition # Please use CamelCase when defining model class name
fields = '__all__'