QuerySet Raised: Related Field got invalid lookup: icontains - django

Am learning Django and I used ForeignKey to link my models.
icontains work in field that are not ForeignKeys.
I want to filter the Items in my model to show me only fields that match the queryset.
But queryset raised: Related Field got invalid lookup: icontains
Please help. Below is My model and View
My Model
class Category(models.Model):
category = models.CharField(max_length=200, default='', blank=True, null=True)
def __unicode__(self):
return self.category
class StoreItems(models.Model):
item_name = models.CharField(max_length=200, default='', blank=True, null=True)
def __unicode__(self):
return self.item_name
class Supplier(models.Model):
supplier_name = models.CharField(max_length=200, default='', blank=True, null=True)
def __unicode__(self):
return self.supplier_name
class Unit(models.Model):
unit = models.CharField(max_length=200, default='', blank=True, null=True)
def __unicode__(self):
return self.unit
class Store(models.Model):
category = models.ForeignKey(Category, blank=True, null=True)
item_name = models.ForeignKey(StoreItems, blank=True, null=True)
quantity = models.IntegerField(default='', blank=True, null=False)
receive_amount = models.IntegerField(blank=True, null=True)
receive_by = models.CharField(max_length=120, default='', blank=True, null=False)
issue_amount = models.IntegerField(blank=True, null=True)
issue_by = models.CharField(max_length=120, default='', blank=True, null=True)
issue_to = models.CharField(max_length=120, default='', blank=True, null=True)
supplier_name = models.ForeignKey(Supplier, blank=True, null=True)
created_by = models.CharField(max_length=15, default='', blank=True, null=True)
unit = models.ForeignKey(Unit, blank=True, null=True)
reorder_level = models.IntegerField(default='0', blank=True, null=False)
export_to_CSV = models.BooleanField(default=False)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
My View
def store_list(request):
label = 'STORE'
title = 'Select the item you want to filter'
heading = 'SEARCH ITEMS'
if request.user.is_authenticated():
form = StoreSearchForm(request.POST or None)
context = {
"title": title,
"form": form,
"heading": heading,
}
if request.method == 'POST':
queryset = Store.objects.all().order_by('item_name').filter(category__icontains=form['category'].value(), item_name__icontains=form['item_name'].value())
context = {
"queryset": queryset,
"form": form,
}
return render(request, "store.html", context)

Yep, you can't directly use icontains on a foreign key but ...
Store.objects.all().order_by('item_name'
).filter(category__category__icontains=form['category'].value(), item_name__icontains=form['item_name'].value())
Your category model contains a field also called category. That can be accessed as category__category which means you can use a query such as the one given above.

Related

How to display one models data in another model django admin panel

I have two models: 1) SchoolProfile & 2) Content
I want to show content data in schoolprofile, But data should be display as per user foreignkey.
User foreignkey common for both the models.
School Profile Model
class SchoolProfile(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(User,on_delete=models.CASCADE,unique=True)
school_name = models.CharField(max_length=255)
school_logo=models.FileField(upload_to='media/', blank=True)
incharge_name = models.CharField(max_length=255, blank=True)
email = models.EmailField(max_length=255, blank=True)
phone_num = models.CharField(max_length=255, blank=True)
num_of_alu = models.CharField(max_length=255, blank=True)
num_of_student = models.CharField(max_length=255, blank=True)
num_of_cal_student = models.CharField(max_length=255, blank=True)
def __str__(self):
return self.school_name
Content Model
class Content(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(User,on_delete=models.CASCADE)
content_type = models.CharField(max_length=255, blank=True, null=True)
show=models.ForeignKey(Show,on_delete=models.CASCADE, blank=True, null=True)
sponsor_link=models.CharField(max_length=255, blank=True, null=True)
status=models.BooleanField(default=False, blank=True, null=True)
added_on=models.DateTimeField(auto_now_add=True)
content_file=models.FileField(upload_to='media/', blank=True, null=True)
title = models.CharField(max_length=255)
subtitle = models.CharField(max_length=255, blank=True, null=True)
description = models.CharField(max_length=500, blank=True, null=True)
draft = models.BooleanField(default=False)
publish_now = models.CharField(max_length=255, blank=True, null=True)
schedule_release = models.DateField(null=True, blank=True)
expiration = models.DateField(null=True, blank=True)
tag = models.ManyToManyField(Tag, null=True, blank=True)
topic = models.ManyToManyField(Topic, null=True, blank=True)
category = models.ManyToManyField(Categorie, null=True, blank=True)
def __str__(self):
return self.title
I have used Inline but it's show below error:
<class 'colorcast_app.admin.SchoolProfileInline'>: (admin.E202) 'colorcast_app.SchoolProfile' has no ForeignKey to 'colorcast_app.SchoolProfile'.
My admin.py
class SchoolProfileInline(InlineActionsMixin, admin.TabularInline):
model = SchoolProfile
inline_actions = []
def has_add_permission(self, request, obj=None):
return False
class SchoolProfileAdmin(InlineActionsModelAdminMixin,
admin.ModelAdmin):
inlines = [SchoolProfileInline]
list_display = ('school_name',)
admin.site.register(SchoolProfile, SchoolProfileAdmin)
Using the StackedInline to link two models is straight forward and a much clean practice, so basically this is my solution below:
class ContentInlineAdmin(admin.StackedInline):
model = Content
#admin.register(SchoolProfile)
class SchoolProfileAdmin(admin.ModelAdmin):
list_display = ('school_name',)
inlines = [ContentInlineAdmin]

Django class based view, save in another model after CreateView

I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would like to once I have saved my data in my Loan_assetCreateView(generic.CreateView) that is set the value in Asset.is_loaned to True. How can I do that?
My models.py:
class Asset(models.Model):
# Relationships
room = models.ForeignKey("asset_app.Room", on_delete=models.SET_NULL, blank=True, null=True)
model_hardware = models.ForeignKey("asset_app.Model_hardware", on_delete=models.SET_NULL, blank=True, null=True)
# Fields
name = models.CharField(max_length=30)
serial = models.CharField(max_length=30, unique=True, blank=True, null=True, default=None)
mac_address = models.CharField(max_length=30, null=True, blank=True)
purchased_date = models.DateField(null=True, blank=True)
may_be_loaned = models.BooleanField(default=False, blank=True, null=True)
is_loaned = models.BooleanField(default=False, blank=True, null=True)
missing = models.BooleanField(default=False, blank=True, null=True)
notes = HTMLField(default="")
ip = models.CharField(max_length=90, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Loan_asset(models.Model):
# Relationships
asset = models.ForeignKey("asset_app.Asset", on_delete=models.SET_NULL, blank=True, null=True)
loaner_type = models.ForeignKey("asset_app.Loaner_type", on_delete=models.SET_NULL, blank=True, null=True)
location = models.ForeignKey("asset_app.Locations", on_delete=models.SET_NULL, blank=True, null=True)
# Fields
loaner_name = models.CharField(max_length=60)
loaner_address = models.TextField(max_length=100, null=True, blank=True)
loaner_telephone_number = models.CharField(max_length=30)
loaner_email = models.EmailField()
loaner_quicklink = models.URLField(null=True, blank=True)
loan_date = models.DateField()
return_date = models.DateField()
notes = HTMLField(default="")
returned = models.BooleanField(default=False, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Meta:
pass
def __str__(self):
return str(self.loaner_name)
def get_absolute_url(self):
return reverse("asset_app_loan_asset_detail", args=(self.pk,))
def get_update_url(self):
return reverse("asset_app_loan_asset_update", args=(self.pk,))
my urls.py
`path("asset_app/loan_asset/create/", views.Loan_assetCreateView.as_view(), name="asset_app_loan_asset_create")`,
my views.py
class Loan_assetCreateView(generic.CreateView):
model = models.Loan_asset
form_class = forms.Loan_assetForm
Here are some options:
override form_valid method that's being called in post method implementation, so that after form will be validated (model instance saved), you'll be able to set the flag through foreign key/by creating Asset instance:
...
def form_valid(self, form):
self.object = form.save()
if self.object.asset:
self.object.asset.is_loaned = True
else:
self.object.asset = Asset.objects.create(is_loaned=True)
return HttpResponseRedirect(self.get_success_url())
use Django signals:
#receiver(post_save, sender=Loan_asset)
def create_transaction(sender, instance, created, **kwargs):
if created:
Asset.objects.create(is_loaned=True)
You can override the post method in your Loan_assetCreateView.
class Loan_assetCreateView(generic.CreateView):
model = models.Loan_asset
form_class = forms.Loan_assetForm
def post(request, *args, **kwargs):
response = super().post(request, *args. **kwargs)
# Do your thing
return response

Django, i can't put function form inside generic.UpdateView

I am making a app for one kindergarten in my city. I have kids model and payment model.
For updating kid I am using class based view generic UpdateView and for creating a payment i am using form and function view. I have not problems with payment form when I am using a different template but when I try to put it on the same template, payment form is not showing up and it's not working. Is it possible to have payment form on same template as UpdateView class ? I am using UpdateView class as profile page and I would like to have payment form on the same page. Please help. Thanks
models:
class Kids(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
city_birthday = models.CharField(max_length=100, blank=True, null=True)
custom_id = models.CharField(max_length=100 ,blank=True, null=True)
gender = models.CharField(max_length=100, choices=gender_choices, null=True, blank=True)
address = models.CharField(max_length=250, null=True, blank=True)
contact_phone = models.CharField(max_length=100, blank=True, null=True)
family_size = models.IntegerField(null=True, blank=True)
living_with = models.CharField(max_length=100, choices=living_choices, null=True, blank=True)
number_of_preschool_kids_in_family = models.IntegerField(null=True, blank=True)
kid_already_been_in_kindergarten = models.CharField(max_length=100, choices=preschool_choices,
null=True, blank=True ,default=False)
father_name = models.CharField(max_length=100, blank=True, null=True)
father_education_level = models.CharField(max_length=200, blank=True, null=True)
father_company = models.CharField(max_length=200, blank=True, null=True)
mother_name = models.CharField(max_length=100, blank=True, null=True)
mother_education_level = models.CharField(max_length=200, blank=True, null=True)
mother_company = models.CharField(max_length=200, blank=True, null=True)
parent_notes = models.CharField(max_length=500, blank=True, null=True)
program_choice = models.CharField(max_length=100, choices=kindergarten_program_choice, null=True,
blank=True)
def __str__(self):
return self.name
class Meta:
ordering = ['name']
class Payment(models.Model):
user = models.ForeignKey(Kids, on_delete=models.CASCADE, blank=True, null=True)
bank_paper_id = models.IntegerField(null=True, blank=True)
payment_date = models.CharField(max_length=100, null=True, blank=True)
paid = models.FloatField(null=True, blank=True)
need_to_pay = models.FloatField(null=True, blank=True)
notes = models.CharField(max_length=500, blank=True, null=True)
def __str__(self):
return self.user.name
views:
class UpdateKidView(UpdateView):
model = Kids
fields = '__all__'
template_name = 'vrtic/update_kid.html'
success_url = reverse_lazy('vrtic:kids')
def create_payment(request, pk):
kid = Kids.objects.get(id=pk)
payment_form = PaymentForm()
if request.method == 'POST':
payment_form = PaymentForm(request.POST)
if payment_form.is_valid():
payment = payment_form.save(commit=False)
payment.user = kid
payment_form.save()
return redirect('vrtic:kids')
context = {
'payment_form': payment_form,
'kid': kid
}
return render(request, 'vrtic/update_kid.html', context)
form:
class PaymentForm(forms.ModelForm):
class Meta:
model = Payment
fields = '__all__'
class UpdateKidView(UpdateView):
model = Kids
form_class = KidsForm
second_form_class = PaymentForm
template_name = 'vrtic/update_kid.html'
success_url = reverse_lazy('vrtic:kids')
def get_context_data(self, **kwargs):
context = super(UpdateKidView, self).get_context_data(**kwargs)
context['form'] = self.form_class(instance=self.get_object())
context['second_form'] = self.second_form_class()
return context
def post(self, request, **kwargs):
kids_form = self.form_class(request.POST, request.FILES, instance=self.get_object())
if kids_form.is_valid():
kid = kids_form.save()
payment_form = self.second_form_class(request.POST)
...
Not the happiest solution, but u got the idea, if need more help contact me to explain on Serbian, not sure how are the rules here for languages : )

django datefield auto_now = true dont work

I have this table in my model, i just want that if the data is updated the modifyDate field will automatict updated.
note: i am not using the adminsite to update data
class FmCustomerEmployeeSupplier(models.Model):
dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True)
lastname = models.CharField(max_length=500, blank=True, null=True)
firstname = models.CharField(max_length=500, blank=True, null=True)
middleInitial = models.CharField(max_length=500, blank=True, null=True)
bodyTemperature = models.FloatField(blank=True, null=True)
modifyDate = models.DateField(auto_now=True, blank=True, null=True)
modifyBy = models.CharField(max_length=500, blank=True)
#property
def is_past_due(self, *args, **kwargs):
return date.today() > self.modifyDate
class Meta:
verbose_name_plural = "50. Customer's List of Employees, Suppliers and visitors"

I wanna create model which Before adding it must be accepted

I would like to create a model which must be accepted by the moderator before adding, after which every change in eg the title in this model must also be accepted
class MangaRequest(models.Model):
title = models.CharField(max_length=191)
type = models.CharField(max_length=30,choices=TYPE, blank=True, default='', null=True)
status= models.CharField(max_length=30, choices=STATUS, blank=True, default='', null=True)
date_start = models.DateField(blank=True, null=True)
data_end = models.DateField(blank=True, null=True)
age_restrictions = models.ForeignKey(OgraniczenieWiekowe, null=True, default='', blank=True)
volumes = models.SmallIntegerField(null=True, blank=True, default=0)
chapter = models.SmallIntegerField(null=True, blank=True, default=0)
is_accept = models.BooleanField(default=False)
delete = models.BooleanField(default=False)
This is my model and I have done it
def save(self, *args, **kwargs):
if self.is_accept == True:
manga = MangaAccept.objects.create(...)
super(MangaRequest, self).delete()
return manga
else:
super(MangaRequest, self).save()
And the same way is about deletes
My question is how can ACCEPT or REJECT for model and everyone field in this model ? Any sugestion ?