How to create model objects via ModelForm ForeignKey? - django-models

I have a model for Classroom and Student as shown below
class Classroom(models.Model):
COURSE_NAME = (
('MA8', 'Math 8'),
('SC10', 'Science 10'),
('PH11', 'Physics 11'),
('PH12', 'Physics 12'),
)
BLOCK_NUMBER = (
('11', 'Block 1-1'),
('12', 'Block 1-2'),
('13', 'Block 1-3'),
('14', 'Block 1-4'),
('21', 'Block 2-1'),
('22', 'Block 2-2'),
('23', 'Block 2-3'),
('24', 'Block 2-4'),
)
class_list = models.TextField()
course_name = models.CharField(max_length=20, choices=COURSE_NAME)
course_block = models.CharField(max_length=10, choices=BLOCK_NUMBER)
class Student(models.Model):
classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE)
nickname = models.CharField(default='JohnS', max_length=31)
attend = models.BooleanField(default=True)
I created a form for Classroom.class_list and TextField is where the user copy/pastes a list of names. I want to then parse the class_list and save each individual name as nickname. I first tried the following but this doesn't seem to save the Student objects.
forms.py
class ClassroomForm(ModelForm):
class Meta:
model = Classroom
fields = ['course_name', 'course_block','class_list']
views.py
class ClassroomCreateView(CreateView):
model = Classroom
form_class = ClassroomForm
def form_valid(self, form):
classroom = form.save(commit=False)
s = Student()
for line in classroom.class_list:
s.nickname = line
s.save()
classroom.save()
return super(ClassroomCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('classroom:submitted')
I also tried creating StudentForm which allows a user to choose course_name and course_block (which corresponds to a particular class_list). The form or view would then create the individual Student objects and display them. I read about ModelChoiceField but I can't figure out how to implement this.
How and where do I (auto) create Students objects from a ForeignKey field?

I solved my question with the help of this answer. Here is the modified code I used for models.py. My view is just a standard CreateView from the ModelForm.
class Classroom(models.Model):
... dictionary stuff ..
class_list = models.TextField()
course_name = models.CharField(max_length=20, choices=COURSE_NAME)
course_block = models.CharField(max_length=10, choices=BLOCK_NUMBER)
group_size = models.IntegerField(default=3)
def __str__(self):
return self.get_course_block_display()
def save(self, *args, **kwargs):
super(Classroom, self).save(*args, **kwargs)
# overrides the default save function to parse the class list
studentList = []
studentList = self.class_list.split('\n')
for line in studentList:
line = line.strip('\r')
s = Student.objects.create(nickname = line, classroom = self)

Related

Django - Query from a sub-table

I have an application that has a dropdown menu among other things.
The menu is created based on the requirements. I wrote a query that checks the statuses and calculates how many requirements are in a given status. Then he builds a menu out of it. However, I have a problem because sometimes a requisition has been created but no items have been added to it. In that case, my menu shows this as one of the items. This is not what he expects. I would like the query to return and count only those requirements in a given status that have children.
Below I paste the model code and inquiries.
class D_DemandStatus(ModelBaseClass):
status = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=50)
created_user = models.ForeignKey(User, on_delete=models.PROTECT)
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.created_user = user
self.modified_by = user
super(D_DemandStatus, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Demand status'
verbose_name_plural = 'Demands status'
class Demand(models.Model):
name = models.CharField(max_length=500)
status = models.ForeignKey(D_DemandStatus, default=3, on_delete=models.PROTECT, )
insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False)
insert_date = models.DateTimeField(default=datetime.datetime.now, editable=False)
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.insert_user = user
self.status = D_DemandStatus.objects.get(status='PREPARED')
self.modified_by = user
super(Demand, self).save(*args, **kwargs)
def __str__(self):
return self.name
def submitt(self, *args, **kwargs):
if self.pk :
dict_status = D_DemandStatus.objects.get(status='WAITING')
print(dict_status)
self.demanddetails_set.filter(demand_id = self.pk).update(status=dict_status)
self.status = dict_status
self.save()
def status_actualize(self, *args, **kwargs):
if self.pk :
dict_status = D_DemandStatus.objects.get(status='ORDERED')
items_status = DemandDetails.objects.filter(demand=self.pk).values('status').distinct()
if len(items_status) == 1 and items_status[0]['status'] == dict_status.id :
self.status = D_DemandStatus.objects.get(status='ORDERED')
#elif len(items_status) > 1 :
# self.status = D_DemandStatus.objects.get(status='INPROGRESS')
self.save()
class Meta:
verbose_name = 'Demand'
verbose_name_plural = 'Demands'
class DemandDetails(models.Model):
demand = models.ForeignKey(Demand, on_delete=models.CASCADE, related_name='items')
component = models.ForeignKey(Component, on_delete=models.CASCADE)
order_item = models.ForeignKey(OrderItem, null=True, on_delete=models.PROTECT, editable=False, related_name='demand_details_item')
quantity = models.IntegerField(default=1)
comment = models.CharField(max_length=150, blank=True)
status = models.ForeignKey(D_DemandStatus, default=3, on_delete=models.PROTECT, )
insert_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False)
insert_date = models.DateTimeField(auto_now_add=True)
def quantityUpdate(self, val):
if self.pk :
self.quantity = val
self.save()
def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.pk:
user = None
if not self.pk:
self.insert_user = user
self.status = D_DemandStatus.objects.get(status='PREPARED')
if not self.pk:
try:
super(DemandDetails, self).save(*args, **kwargs)
except IntegrityError as e:
obj = DemandDetails.objects.get(demand_id=self.demand_id, component_id=self.component_id)
obj.quantity = obj.quantity + 1
obj.save()
else:
super(DemandDetails, self).save(*args, **kwargs)
def __str__(self):
return self.demand.name
class Meta:
verbose_name = 'Demand detail'
verbose_name_plural = 'Demand details'
constraints = [
models.UniqueConstraint(fields=['demand_id', 'component_id'], name='epm - DemandDetail (demand, component)' )
]
The query that works now looks like this:
demand_list = Demand.objects.values('status__name', 'status__id', 'status__status').annotate(count=Count('status__name')).filter(Q(status__status='WAITING') | Q(status__status='PREPARED')).order_by('-status__name')
In this case, however, even if the demand is empty (no items added), it is counted as 1
So I have changed the code a little, but it doesn't work as I would like, because it also counts the individual elements of the demand - which is obvious, because the query returns the subsequent rows that are counted.
demand_list = Demand.objects.values('status__name', 'status__id', 'status__status').annotate(count=Count('status__name'), piece=Count('demanddetails')).filter(Q(piece__gte=1)).filter(Q(status__status='WAITING') | Q(status__status='PREPARED')).order_by('-status__name')
I need to write the query in such a way that I get a list of statuses with numbers of demands only which have derived elements in DemandDetails. If a Demand exists but has no derived elements then it is not taken into account - rather it is counted as 0. This is important because in the extreme case there may be only one Demand which is empty and then I want to have information about it in the menu but with the number 0.
I hope I have managed to write clearly what I chaie.
Please help me to create a suitable query.
Regards

How to make required filling in a form field with a many-to-many relationship in django admin

I have a Recipes model with an ingredients field with a many-to-many relationship. I have an intermediate Ingredient amount model associated with the ingredients field via through. I want to prohibit the creation of a recipe in django admin without ingredients. I'm trying to solve this problem by creating my own class inherited from BaseInlineFormSet and redefining the clean() method. It doesn't work out yet, I need help, what am I doing wrong?
admin.py
class IngredientsAmountInlineFormset(BaseInlineFormSet):
def clean_ingredients(self):
if len(self.cleaned_data['ingredients']) < 1:
return 'Укажите хотя бы один ингредиент в рецепте'
return self.cleaned_data['ingredients']
class IngredientsAmountInline(admin.TabularInline):
model = IngredientsAmount
formset = IngredientsAmountInlineFormset
extra = 0
#admin.register(Recipes)
class RecipesAdmin(admin.ModelAdmin):
list_display = ('name', 'author', 'favorites_count',)
list_filter = ('name', 'author', 'tags',)
search_fields = ('name', 'author', 'tags',)
empty_value_display = '-пусто-'
inlines = (IngredientsAmountInline,)
models.py
class Ingredients(models.Model):
name = models.CharField(max_length=200, unique=True)
measurement_unit = models.CharField(max_length=200)
...
class Recipes(models.Model):
...
ingredients = models.ManyToManyField(Ingredients,
through='IngredientsAmount',
related_name='recipes',
verbose_name='Ингредиенты',
)
...
class IngredientsAmount(models.Model):
ingredients = models.ForeignKey(Ingredients,
on_delete=models.CASCADE,
related_name='amount',
verbose_name='Ингредиенты',
)
recipes = models.ForeignKey(Recipes,
on_delete=models.CASCADE,
related_name='amount',
verbose_name='Рецепты', )
amount = models.IntegerField()
obiviously clean should raise ValidationException:
class IngredientsAmountInlineFormset(BaseInlineFormSet):
def clean_ingredients(self):
value = self.cleaned_data['ingredients']
if value:
return value
raise ValidationError(_('Укажите хотя бы один ингредиент в рецепте'))
by the way:
Try don't use the direct text message:
'Укажите хотя бы один ингредиент в рецепте'
Wrap your text in gettext/gettext_lazy, like this:
from django.utils.translation import gettext_lazy as _
_('Укажите хотя бы один ингредиент в рецепте')
It help you in future collect those messages together, and translate it if you need.

Django Post request for many to many field ValueError

I am working on a post request in which the user chooses from a list of tags and makes combinations of tags. The combination of tags should then be posted. Nothing should get changed in the Tag table.
These are the models:
models.py
class Tag(models.Model):
name = models.CharField(max_length=256)
language = models.CharField(max_length=256)
objects = models.Manager()
def __str__(self):
"""Return a human readable representation of the model instance."""
return self.name or ''
#property
def tags(self):
tags = self.tagging.values('tag')
return tags.values('tag_id', 'tag__name', 'tag__language')
class Combination(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True)
resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True)
tag_id = models.ManyToManyField(Tag, null=True)
created = models.DateTimeField(editable=False)
score = models.PositiveIntegerField(default=0)
objects = models.Manager()
def __str__(self):
return str(self.tag_id) or ''
This is the serializer for Combination.
serializers.py
class CombinationSerializer(serializers.ModelSerializer):
tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
required=True,
source='resource',
write_only=False)
gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
required=False,
source='gameround',
write_only=False)
user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
required=False,
source='user',
write_only=False)
class Meta:
model = Combination
depth = 1
fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')
def create(self, validated_data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
score = 0
tag_data = validated_data.pop('tag_id', None)
combination = Combination(
user=user,
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
created=datetime.now(),
score=score
)
combination.save()
for tag_object in tag_data[0]:
combination.tag_id.add(tag_object)
return combination
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data
return rep
I have tried posting the following JSON object to the database:
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [{"id": 2014077506, "name": "corwn","language": "en"}]
}
I am getting a ValueError: Field 'id' expected a number but got 'name'.
How can I fix this issue?
you need to provide tag id for each tag not all tag data,
Try like this
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [2014077506,2014077507]
}

How do i access another column from related table other than the foreign key, when creating an API view

Im using django for a web app and i am creating REST API views. Is there a way i can access two tables in one view? If not, how can can i retrieve a non-foreign key column from a related record. The below code is retrieving a vase record based on a URL parameter. I want to access the artistName which is stored in artist table (a one-to-many with Vase table), not artist_id which is stored in Vase
class FilterVases(generics.ListAPIView):
serializer_class = VaseSerializer
def get_queryset(self):
queryset = Vase.objects.all()
artist_id = self.request.query_params.get('artist_id')
if artist_id is not None:
queryset = queryset.filter(artist_id=artist_id)
vaseID = self.request.query_params.get('vaseID')
if vaseID is not None:
queryset = queryset.filter(vaseID=vaseID)
return queryset
edited to add
This is models for Artist and Vase:
class Artist(models.Model) :
artistID = models.CharField(max_length=10)
artistName = models.CharField(max_length=100)
class Vase(models.Model):
vaseID = models.CharField(max_length=10)
vaseRef = models.CharField(max_length=255,blank=True,null=True)
inscription = models.CharField(max_length=255,blank=True,null=True)
fabric = models.CharField(max_length=100, blank=True,null=True)
subject = models.CharField(max_length=255,blank=True,null=True)
technique = models.CharField(max_length=100,blank=True,null=True)
height = models.FloatField(max_length=100,blank=True,null=True)
diameter = models.FloatField(max_length=100,blank=True,null=True)
shape = models.ForeignKey(Shape, on_delete=models.CASCADE)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
provenance = models.ForeignKey(Provenance, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
In the Vase model add this:
def artist_name(self):
return self.artist.artistName
Hence, it will look like:
class Vase(models.Model):
vaseID = models.CharField(max_length=10)
vaseRef = models.CharField(max_length=255,blank=True,null=True)
inscription = models.CharField(max_length=255,blank=True,null=True)
fabric = models.CharField(max_length=100, blank=True,null=True)
subject = models.CharField(max_length=255,blank=True,null=True)
technique = models.CharField(max_length=100,blank=True,null=True)
height = models.FloatField(max_length=100,blank=True,null=True)
diameter = models.FloatField(max_length=100,blank=True,null=True)
shape = models.ForeignKey(Shape, on_delete=models.CASCADE)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
provenance = models.ForeignKey(Provenance, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
def artist_name(self):
return self.artist.artistName
In the VaseSerializer add the 'artist_name' to the fields Meta.
If you want to add this custom fields to all Vase Model fields, refer to this topic Django Rest framework, how to include '__all__' fields and a related field in ModelSerializer ?
class VaseSerializer(serializers.ModelSerializer):
class Meta:
model = models.Vase
fields = '__all__'
extra_fields = ['artist_name']
def get_field_names(self, declared_fields, info):
expanded_fields = super(VaseSerializer, self).get_field_names(
declared_fields, info)
if getattr(self.Meta, 'extra_fields', None):
return expanded_fields + self.Meta.extra_fields
else:
return expanded_fields
Below should your view:
class FilterVases(generics.ListAPIView):
serializer_class = VaseSerializer
def get_queryset(self):
queryset = Vase.objects.all()
query_artist = self.request.query_params.get('artist_name')
if query_artist is not None:
try:
artist = Artist.objects.get(artistName=query_artist)
queryset = queryset.filter(artist=artist)
except:
pass
vaseID = self.request.query_params.get('vaseID')
if vaseID is not None:
queryset = queryset.filter(vaseID=vaseID)
return queryset

how to filter foreign key in django form without passing foreign key value?

I have created two models in my django project AddStudent and Fee Entry as shown below.
models.py
class AddStudent(models.Model):
enrollment_no = models.BigIntegerField(primary_key=True)
student_name = models.CharField(max_length=500,null=True)
gender = models.CharField(max_length=1,choices=GENDER_CHOICES)
course = models.ForeignKey(CourseMaster, on_delete=models.DO_NOTHING, null=True)
category= models.ForeignKey(CatMaster, on_delete=models.DO_NOTHING, null=True)
admission_year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
college = models.ForeignKey(CollegeMaster, on_delete=models.DO_NOTHING, null=True)
branch = models.ForeignKey(BranchMaster,on_delete=models.DO_NOTHING, null=True)
current_semester = models.IntegerField(null=True)
address = models.CharField(max_length=1000,null=True)
city = models.CharField(max_length=100,null=True)
district = models.CharField(max_length=100,null=True)
state = models.CharField(max_length=100,null=True)
student_contact = models.BigIntegerField()
parent_contact = models.BigIntegerField()
def get_absolute_url(self):
return reverse('add_student:index')
def __str__(self):
return str(self.enrollment_no) + ' - ' + self.student_name
class FeeEntry(models.Model):
student = models.ForeignKey(AddStudent,on_delete=models.DO_NOTHING)
fee_detail = models.ForeignKey(FeeMaster,on_delete=models.DO_NOTHING)
fee_sem = models.IntegerField(null=True)
payment_date = models.DateField(("Date"), default=datetime.date.today)
pay_method = models.BooleanField(choices=BOOL_CHOICES)
cheque_no = models.CharField(max_length = 100, null=True, blank=True)
bank_name = models.CharField(max_length = 200, null=True, blank=True)
def __str__(self):
return str(self.id) + ' - ' + str(self.student) + ' - ' + self.student.student_name
Now when user search particular student for example student id = 1 than student profile page will open and there is another button addfee. My problem is when user click on add fee all 500 student list is appear in dropdown list. i want to create fee for searched student only.
forms.py
from django import forms
from .models import FeeEntry, AddStudent
from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin
class FeeForm(PopRequestMixin, CreateUpdateAjaxMixin, forms.ModelForm):
class Meta:
model = FeeEntry
fields = ['student', 'fee_detail', 'fee_sem', 'payment_date', 'pay_method','cheque_no','bank_name']
above is my forms.py file where field 'student' will generate all 500 student list. I want only selected student for example enrollment_no=1 when user is on enrollment_no 1's page.
views.py
class FeeCreateView(PassRequestMixin, SuccessMessageMixin,
generic.CreateView):
template_name = 'add_student/create_fee.html'
form_class = FeeForm
success_message = 'Success: Book was created.'
success_url = reverse_lazy('add_student:detail')
urls.py
path('create/<int:pk>', views.FeeCreateView.as_view(), name='create_fee'),
Can anyone tell me what changes are required in this code? or can you share link of similar example like this?
The FeeForm does not know which student you want to relate it with. Because of that, it is showing you a dropdown asking which student you want to assign to the FeeEntry instance.
Remove 'student' from the form and send the form to the view. when the user submits the form, use the form_valid (form.is_valid if you are using FBV) method to assign the student to the fee_entry instance.
def form_valid(self, form):
fee_entry = form.save(commit=False)
fee_entry.student = AddStudent.objects.get(id=self.kwargs['student_id'])
fee_entry.save()
Also make sure to send the student_id in the url. You can even send it as a POST parameter(check out how to retrieve parameter from a POST request) using a hidden field in the form.

Resources