My model:
class HospitalDoctor(models.Model):
hospital = models.ForeignKey(Hospital)
full_name = models.CharField(max_length=100, unique=True)
expertization = models.CharField(max_length=50)
nmc_no = models.CharField(max_length=20)
timings = models.ManyToManyField('Timing', related_name='shift_timing')
appointment = models.IntegerField(default=0)
def __unicode__(self):
return self.full_name
class Timing(models.Model):
hospital = models.ForeignKey(Hospital)
doctor = models.ForeignKey(HospitalDoctor)
day = models.CharField(max_length=20)
mng_start = models.IntegerField()
mng_end = models.IntegerField()
eve_start = models.IntegerField()
eve_end = models.IntegerField()
def __unicode__(self):
return self.day
and I have created form for this:
class HospitalDoctorInfoForm(forms.ModelForm):
class Meta:
model = HospitalDoctor
fields = ('hospital','full_name', 'expertization', 'nmc_no')
class TimingForm(forms.ModelForm)
class Meta:
model = Timing
fields = ('day','mng_start', 'mng_end', 'eve_start', 'eve_end')
I want to save the two form at once. The TimingForm contains the schedule of a doctor for 1 week so I need 7 forms for 7 days and the day should be set as per week initially like Sunday, Monday....DoctorInfoForm contains the information about doctor.
I tried using CreateView but I need to use form_class there?
How can I make it possible? Any suggestion.
It is just simple in django.
if HospitalDoctorinfoform.is_valid() and Timingform.is_valid():
#Dosomething
HospitalDocinfoform.save()
Timingform.save()
BIngo!!
Related
My models
User
class User(AbstractUser):
is_student = models.BooleanField(default=False)
....
purchased = models.ManyToManyField(Course, blank=True)
Course
class Course(models.Model):
title = models.CharField(max_length=1000)
.....
price = models.FloatField()
My Views
class StudentPurchasedcourse(ListView):
model = Course
template_name = 'tutspack/purchasedcourse.html'
context_object_name = 'course'
def get_queryset(self):
queruset = Course.objects.filter(pk=self.request.user.purchased.all()).order_by('title')
return queruset
My Urls.py
path('purchased_course/', views.StudentPurchasedcourse.as_view(), name='purchased-course'),
I want to return all the courses That student have purchased on the studentViewpage.
You should use reverse relation for such query. Start with adding related_name to purchased field of User:
class User(AbstractUser):
...
purchased = models.ManyToManyField(Course, blank=True, related_name="buyers")
Then you can easily use that name in making queries based on relations:
Course.objects.filter(buyers=self.request.user).order_by('title')
More about queries
My problem is like so,
I am using django-tables2 and I want to list some people on my page but these people should go through some queries. These queries will change according to information from other models.if the query is ok, this person will be in my table.
# My models
class AgeGroup(models.Model):
age_group = models.CharField(choices=age_choices, max_length=5)
class SolvedExam(models.Model):
age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='solved_exam_age_group')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='solved_exam')
class Person(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person')
age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='person_age_group')
*
*
*
class Exam(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person')
age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='exam_age_group')
*
*
*
# my view
class PersonList(SingleTableMixin, FilterView):
table_class = PersonTable
model = Person
queryset = Person.objects.all()
paginate_by = 10
template_name = 'person/person-list.html'
filterset_class = PersonFilter
def get_queryset(self):
super(Ogrenciler, self).get_queryset()
return Person.objects.filter( **some query** )
raise Http404
I want to list the students if there are exams which is not finished in the person's age group. Thank you very much!
Where is the information about the examns, and the examns that where not passed? Typically I would expect an fields like Exman_id, class name, boolean passed etc.
In my app i need to store invoices (Invoice) of known products (Product) to calculate points for each seller (User). I'm trying to create form to insert basic invoice data plus inline form with sold products info. To handle it i create model like this:
class Product(models.Model):
group = models.CharField(max_length = 200, blank = False)
mark = models.CharField(max_length = 200, blank = True)
points = models.IntegerField(blank = False)
class Invoice(models.Model):
price = models.FloatField(blank=False)
file = models.FileField(blank=False)
product = models.ManyToManyField(Product, through='Sold')
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField()
date_created = models.DateField(auto_now_add=True)
date_updated = models.DateField(auto_now=True)
class Sold(models.Model):
invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
I tried to manage it via django-admin and it work fine with admin.py:
class ProductTabular(admin.TabularInline):
model = Invoice.product.through
class InvoiceAdmin(admin.ModelAdmin):
inlines = [ProductTabular]
exclude = ('product', )
class Meta:
model = Invoice
admin.site.register(Invoice, InvoiceAdmin)
but i'm unable to create such form in own templates. Please, can you help me with views.py and template to get same result as for the django-admin?
I tried via invoce form with inlineformset_factory for the Sold model, but i can't figure out how to save it. Thanks for any help!
I have two classes
class Drink(models.Model):
name = models.CharField(max_length=100, blank=False, default='')
brand = models.TextField()
percentage = models.IntegerField()
class Drinking(models.Model):
amount = models.IntegerField(blank=False)
drinks = models.ForeignKey(Drink, related_name='drinks',blank = True,null=True)
and want to add a list of drinks to the Drinking model via a REST POST.
In the serializer I have the following:
class DrinkingSerializer(serializers.ModelSerializer):
drinks = serializers.PrimaryKeyRelatedField(many=True, read_only=False ,queryset=Drink.objects.all())
class Meta:
model = Drinking
fields = ('pk','drinks','amount')
def create(self, validated_data):
return Drinking.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.amount = validated_data.get('amount', instance.amount)
instance.save()
return instance
When I try to POST an Drinking Object:
{
"drinks": [2],
"amount": 5
}
I get the Error, that Drinkings.drinks must be Drink instance. My guess is that I have to change the queryset to only get the primary key of the drinks but I don't know how.
UPDATE
I did a small change in the logic, so every Drinking class can only have one Drink and one amount. This works now with the following Serializer:
class DrinkingSerializer(serializers.ModelSerializer):
drink = serializers.PrimaryKeyRelatedField(many=False, read_only=False, queryset=Drink.objects.all())
Are you sure that Drink object with id 2 exists?
Also, try making request without brackets: "drinks": 2 - in my DRF Api nothing else is needed.
I think the field drinks in your Drinking model should be in the Drink model.
class Drinking(models.Model):
amount = models.IntegerField(blank=False)
class Drink(models.Model):
name = models.CharField(max_length=100, blank=False, default='')
brand = models.TextField()
percentage = models.IntegerField()
drinks = models.ForeignKey(Drinking, related_name='drinks',blank = True,null=True)
Then, using these models your serializer should look like this:
class DrinkingSerializer(serializers.ModelSerializer):
drinks = serializers.PrimaryKeyRelatedField(many=True, read_only=False ,queryset=Drink.objects.all())
class Meta:
model = Drinking
fields = ('pk','drinks','amount')
I hope this helps.
i have these models:
#model.py
class Subject(models.Model):
name = models.CharField("Name",max_length=50, blank=True)
...
...
class Activity(models.Model):
label = models.CharField("Act. name",max_length=150)
price = models.DecimalField("price", max_digits=10, decimal_places=2,default=0)
count = models.IntegerField("Count", default=0)
def __unicode__(self):
return u"%s" % (self.label)
class Meta:
verbose_name_plural = "Activities"
class Invoice(models.Model):
subject = models.ForeignKey(Subject)
date = models.DateField(default=date.today())
activities = models.ManyToManyField(Activity)
....
....
while creating a new Invoice instance on admin, i can select the many to many fields 'activities', but i'd like to have an additional counter (eg. an IntegerField) as an Invoice field to count and save the quantity of each activity added to my Invoice instance. Is this possible?
thanks,
Luke
You could have a field on the model and override the save method
class Invoice(models.Model):
subject = models.ForeignKey(Subject)
date = models.DateField(default=date.today())
activities = models.ManyToManyField(Activity)
activity_count = models.PositiveIntegerField(default=0)
def save(self):
self.activity_count = self.activities.count()
super(Invoice, self).save()