replacing dropdown lookup with related user field - django

In a form I have a drop down of usernames, this is referenced in the 'taken_by' field. I would like to display first_name and last_name, this is achieved through the __str__ but I can't seem to get it to function, the list of usernames are presented but not the firstname. Suggestions welcome.
from django.contrib.auth.models import User
from django.conf import settings
class Sample(models.Model):
sample_id = models.AutoField(primary_key=True)
area_easting = models.IntegerField(choices = EASTING_CHOICES)
area_northing = models.IntegerField(choices = NORTHING_CHOICES)
context_number = models.IntegerField()
sample_number = models.IntegerField()
material_type = models.CharField(max_length=200, default='', blank=True, null=True, choices = MATERIALS)
weight = models.DecimalField(max_digits=6, decimal_places=2)
description = models.CharField(max_length=500, default='', blank=True, null=True)
recovery_method = models.CharField(max_length=200, default='', blank=True, null=True, choices = RECOVERY_METHODS)
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='taken_by', on_delete = models.PROTECT)
comments = models.CharField(max_length=1000, default='', blank=True, null=True)
def __str__(self):
return self.taken_by.first_name
# return str(self.sample_id)
# return str(self.firstname)+ '-' +str(self.lastname)
# return u'%s %s' % (self.first_name, self.last_name)
Form setup as requested
class BotanySampleFilterForm(forms.ModelForm):
class Meta:
model = Sample
fields = (
# 'botany_id',
'sample_id',
'area_easting',
'area_northing',
'context_number',
'sample_number',
'material_type',
'weight',
'description',
'recovery_method',
'taken_by',
'comments'
)

Related

Sum in Django Rest Framework (DRF) Serializer

Excuse me devs, i wanna ask about how to count on drf serializer, i need codes that can serialized fields plant from table A and it relations with another table B with count of them "plants_active"
Here's my code:
# Models
class TablePlants(models.Model):
plant_id = models.CharField(primary_key=True, max_length=20, unique=True)
gateway = models.ForeignKey(
TableGatewayDevice, models.DO_NOTHING, blank=True, null=True)
name = models.CharField(max_length=150, blank=True, null=True)
date = models.DateField(blank=True, null=True)
contact_person = models.CharField(max_length=70, blank=True, null=True)
contact_email = models.CharField(max_length=50, blank=True, null=True)
contact_phone = models.CharField(max_length=30, blank=True, null=True)
plant_status = models.CharField(max_length=20, blank=True, null=True)
weather_status_code = models.ForeignKey(
TableAuxWeather, models.DO_NOTHING, db_column='weather_status_code', blank=True, null=True)
timezone = models.CharField(max_length=200, blank=True, null=True)
image = models.FileField(
upload_to='plants/', validators=[file_size, validate_file_extension], null=True, blank=True)
class Meta:
db_table = 'table_plants'
def __str__(self):
return 'TablePlants[id: {id}, name: {name}]'.format(
id=self.id, name=self.name)
class PVOwner(models.Model):
pv_owner_id = models.AutoField(primary_key=True)
company = models.ForeignKey(TableCompany, on_delete=CASCADE,
blank=True, null=True, related_name="pv_owner_company")
class Meta:
db_table = 'table_pv_owner'
class TableSitePlant(models.Model):
pv_owner = models.ForeignKey(
PVOwner, on_delete=CASCADE, blank=True, null=True, related_name="pv_site_owner_plant")
site_owner = models.ForeignKey(
SiteOwner, on_delete=CASCADE, blank=True, null=True, related_name="site_owner_plant")
plant = models.ForeignKey(TablePlants, on_delete=CASCADE,
blank=True, null=True, related_name="site_plant")
class Meta:
db_table = 'table_site_plant'
# Serializer
class MainMenuSerializer(serializers.ModelSerializer):
plants_active = serializers.IntegerField(source="plant")
class Meta:
model = TableSitePlant
fields = ['plants_active']
# Views
#permission_classes([AllowAny])
class OverviewPlantsActiveView(generics.RetrieveAPIView):
queryset = TableSitePlant.objects.all().filter(plant__plant_status='offline')
serializer_class = OverviewPlantsActiveSerializer
lookup_field = 'pv_owner'
What i expecting is i can count how many plants that have status online
You can use the get method to return response as you desired.
#permission_classes([AllowAny])
class OverviewPlantsActiveView(generics.RetrieveAPIView):
queryset = TableSitePlant.objects.all().filter()
serializer_class = OverviewPlantsActiveSerializer
lookup_field = 'pv_owner'
def get(self, request):
queryset = self.get_queryset().filter(plant__plant_status='online')
return Response({
"active_plants": queryset.count(),
})

django form is not picking data which is already in database

How do I update my form as the
form.instance.users = request.user
is not working however if I print request.user on terminal it prints the username of the user currently logged in.
Also in this form I want to pick existing data from that user to display in the form to update it.
The save form button return HttpResponse saved successfully but the data is not stored in the database.
models.py
class BasicDetails(models.Model):
GENDERS = (
('M', 'Male'),
('F', 'Female'),
('O', 'Others'),
)
users = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
father_name = models.CharField(max_length=50, blank=True, null=True)
mother_name = models.CharField(max_length=50, blank=True, null=True)
date_of_birth = models.DateField(blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDERS)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.first_name+" "+ self.last_name
class Education(BasicDetails):
current_year = datetime.date.today().year
YEAR_CHOICES = [(r, r) for r in range(2000, datetime.date.today().year+2)]
course_name = models.CharField(max_length=100, blank=True, null=True)
university_board_name = models.CharField(
max_length=200, blank=True, null=True)
passing_year = models.IntegerField(
choices=YEAR_CHOICES, default=current_year, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(default=timezone.now)
forms.py
class BasicDetailsForm(forms.ModelForm):
class Meta:
model = BasicDetails
fields = '__all__'
exclude = ['users']
class EducationForm(forms.ModelForm):
class Meta:
model = Education
fields = '__all__'
exclude = ['users']
views.py
#login_required
def View(request):
education = EducationForm()
education.instance.users = request.user
if request.method =="POST":
print(request.user.id)
education = EducationForm(request.POST,instance=request.user)
if education.is_valid():
education.save(commit=True)
return HttpResponse("Saved Successfully")
else:
education = EducationForm()
return render(request, 'app/view.html',{'education':education})

Django ManyToManyField not showing in admin

As this questions says, I am having trouble displaying a ManyToManyField in the django admin page.
The m2m field that I'm having trouble displaying is comics in the Gig model.
Here is the code for my project:
#models.py file
class Host(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='host')
name = models.CharField("Venue Name", max_length=200)
slug = models.SlugField(allow_unicode=True, blank=True, null=True)
description = models.TextField("Brief Venue Description - [50 Characters Max]", max_length=50, blank=True)
profile_pic = models.ImageField("Profile Picture", upload_to='host/profile_pics',blank=True)
class Gig(models.Model):
host = models.ForeignKey(Host, on_delete=models.CASCADE, blank=True, related_name='host_gigs')
title = models.CharField("Gig Title",max_length=50, null=True)
date_time = models.DateTimeField("Date/Time of Gig", null=True, blank=True)
description = models.TextField("Describe this gig", max_length=150, blank=True)
instructions = models.CharField('Instructions for accepted comics', max_length=200, blank=True, null=True)
comics = models.ManyToManyField("comic.Comic", through='comic.ComicGig',related_name='gig_comics', default=" ")
#in separate app
#models.py
class Comic(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='comic')
dob = models.DateField("Date of Birth", null=True, blank=True)
mobile = PhoneNumberField(null=True, blank=True)
slug = models.SlugField(allow_unicode=True, blank=True, null=True)
class ComicGig(models.Model):
thegig = models.ForeignKey('host.Gig', on_delete=models.CASCADE, default="", related_name='comic_gig')
comic = models.ForeignKey(Comic, on_delete=models.CASCADE, default="")
approved_comic = models.BooleanField(default=False, null=True)
def approve(self):
self.approved_comic = True
self.save()
Here is my Host admin.py file:
class AuthorAdmin(admin.ModelAdmin):
list_display = ('host', 'title',)
filter_horizontal = ('comics',)
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "comics":
kwargs["queryset"] = Gig.objects.filter(comic_gig__approved_comic=True)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Host)
admin.site.register(Gig, AuthorAdmin)
Here is a picture of my Host model in the admin
Here is a picture of my ComicGig model in the admin

Django. How to write a filter for the current user?

The listings application has a Listing table:
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риэлтор')
region = models.CharField(default="Чуйская", max_length=100, verbose_name='Область')
city = models.CharField(default="Бишкек", max_length=100, verbose_name='Город')
district = models.CharField(blank=True, max_length=100, verbose_name='Район')
title = models.CharField(max_length=200, verbose_name='Заголовок')
address = models.CharField(blank=True, max_length=200, verbose_name='Адрес')
description = models.TextField(blank=True, verbose_name='Описание')
stage = models.IntegerField(blank=True, verbose_name='Этажность')
rooms = models.IntegerField(blank=True, verbose_name='Количество комнат')
garage = models.IntegerField(default=0, blank=True, verbose_name='Гараж')
sqmt = models.IntegerField(blank=True, verbose_name='Площадь')
price = models.IntegerField(blank=True, verbose_name='Цена')
photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Основное фото')
photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 1')
photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 2')
photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 3')
photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 4')
photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 5')
photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 6')
is_published = models.BooleanField(default=True, verbose_name='Публично')
list_date = models.DateTimeField(default=datetime.now, blank=True, verbose_name='Дата публикации')
def __str__(self):
return self.title
class Meta:
verbose_name = 'Объявление'
verbose_name_plural = 'Объявления'
In the realtors application there is a Realtor model:
class Realtor(models.Model):
user_name = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь', related_name='realtor')
name = models.CharField(max_length=20, verbose_name='Имя')
photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Фото')
description = models.TextField(blank=True, verbose_name='Описание')
phone = models.CharField(max_length=20, verbose_name='Телефон')
email = models.CharField(max_length=50, verbose_name='Email')
is_mvp = models.BooleanField(default=False, verbose_name='Реэлтор месяца')
hire_date = models.DateTimeField(default=datetime.now, blank=True, verbose_name='Дата приёма на работу')
def __str__(self):
return self.name
class Meta:
verbose_name = 'Риэлтор'
verbose_name_plural = 'Риэлторы'
In the accounts application, there is a function that in the personal account should only display ads of the current user when he is in the system:
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from listings.models import Listing
from realtors.models import Realtor
def dashboard(request):
listings = Listing.objects.order_by('-list_date').filter(user_name=request.user)
paginator = Paginator(listings, 6)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {
'listings': paged_listings
}
return render(request, 'accounts/dashboard.html', context
)
How to correctly register this filter so that everything works so that the current user’s ads are displayed:
listings = Listing.objects.order_by('-list_date').filter(user_name=request.user)
At the moment, this error:
Cannot resolve keyword 'user_name' into field. Choices are: address, city, description, district, garage, id, is_published, list_date, photo_1, photo_2, photo_3, photo_4, photo_5, photo_6, photo_main, price, realtor, realtor_id, region, rooms, sqmt, stage, title
Who is not difficult, please help. Thank you in advance.
Since there's no user_name field in Listing, it's an error to try and filter on that.
Instead, you presumably are trying to filter on the realtor, which can done with a lookup that spans relationships:
listings = Listing.objects.order_by('-list_date').filter(realtor__user_name=request.user)
user_name is a field on the Realtor model, not the Listing. Those two models are connected by a ForeignKey, so you need to traverse that relationship using the double-underscore syntax.
Listing.objects.order_by('-list_date').filter(realtor__user_name=request.user)
Note though that user_name is a very odd name for that field; it's not the name, it's the User object itself. It should be called just user.

QuerySet Raised: Related Field got invalid lookup: icontains

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.