Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the browse file address or location of Froala editor in Python Django?
I am using Froala Rich Text Editior in Python Django. I want to upload images from already uploaded images and there is an option known as browse image but this browse image showing default images not my uploaded or existing images. Please.enter image description here -
how to add comments to an article in django(Python)?
I'm new to Django, I repeat after the tutorial, but I just can not display comments even from the database in html. urls.py static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') models.py from django.db import models class Post(models.Model): photo = models.ImageField(upload_to='media/photos/',null=True, blank=True) name_barber = models.CharField(max_length=30) description = models.TextField(blank=True, null=True) def __str__(self): return self.description[:10] class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_add = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post, self.name) html file } </style> {% for post in posts %} <img src="{{MEDIA_URL}}{{post.photo.url}}" width="800" /> <h3>{{ post.name_barber}}</h3> <p>{{ post.description}}</p> {% endfor %} <h3> Comments.. </h3> {% if not post.comments.all %} no comments yet...<a href = "#">Add one</a> {% else %} {% for comment in post.comments.all %} <strong> {{ comment.name }} {{ comment.date_add }} </strong> {{comment.body }} {% endfor %} {% endif %} after adding a comment through the admin panel, the page displays: no comments yet.. What is the problem please tell me?? -
Django GEOSException at /
Recently when I tried to create a Polygon instance in Django (version 3.1) I got this error: GEOSException at / Error encountered checking Geometry returned from GEOS C function "GEOSGeom_createLinearRing_r". Here's my coordinates that I'm using: Polygon((51.558994, -0.16349), (51.552505, -0.121468), (51.527564, -0.179695), (51.527564, -0.179695)) These coordinates are just a sample. I'm using Polygon coordinates from the leaflet, but when I try to create django.contrib.gis.geos.polygon.Polygon Instance, I get that error. Do have any idea or approach to store received coordinate from leaflet to polygon in Django? -
Images I upload on the admin console are not served
This is being a bit confusing for me. If I set DEBUG=True run python manage.py runserver on VSC, I can access http://127.0.0.1:8000/admin, log in and upload a new photo that will be displayed when I access portifolio.html among the other photos that were previously updated. These photos are saved on BASE_DIR/media/images. However, when DEBUG=False, the previously shown images are not found anymore (404 error on console). I read online that I should use Whitenoise when serving static files on Django while on production and installed it. Still, I get the same behavior. When I run python manage.py collecstatic, the files located on BASE_DIR/django_app/static are copied to BASE_DIR/static and the media folder remains unchanged. settings.py DEBUG = False INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'users.apps.UsersConfig', ... ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(SITE_ROOT,'static/'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') models.py class ImageModel(models.Model): image = models.ImageField(upload_to='images/') url = models.CharField(max_length=100,default='abcdefg') def get_url(self): return self.url def __str__(self): return self.url views.py def index(request): context = { "images": ImageModel.objects.all() } return render(request,'blog/index.html',context) url.py urlpatterns = [ path('admin/', admin.site.urls), ... ] urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_URL) urlpatterns += static(settings.MEDIA_URL, … -
Django How to get user email in model form
So i have profile update form in django and using form.modelform but unable to get user email by self.request.user.email class UserUpdateForm(forms.ModelForm): #Profile email email=forms.EmailField() username=forms.CharField(required=True,validators=[username_check,]) class Meta: model =User fields =['username','email'] def clean_email(self): form_useremail=self.cleaned_data.get("email").lower() if form_useremail!=self.user.email and User.objects.filter(username=form_username).exists(): raise forms.ValidationError("Email already in use") else: return form_useremail Error 'UserUpdateForm' object has no attribute 'user' appears -
django admin inline fields options filtered based on main form field value
I have the following Models: class Organizations(models.Model): name = models.CharField(max_length=30,unique=True) class Postcodes(models.Model): organization = models.ForeignKey(Organizations,on_delete=models.PROTECT) postcode = models.PositiveBigIntegerField() class Agent(models.Model): organization = models.ForeignKey(Organizations,on_delete=models.PROTECT) name = models.CharField(max_length=50) class AgentPostcodes(models.Model): agent= models.ForeignKey(Agent,on_delete=models.PROTECT) postcode = models.ForeignKey(Postcodes,on_delete=models.PROTECT) and admin.py is class AgentPostcodesInline(admin.TabularInline): model = AgentPostcodes class AgentAdmin(admin.ModelAdmin): list_display = ['organization','name'] inlines = [AgentPostcodesInline] How can I have the inline form fields filtered based on organization for postcodes related to that organization only. Currently it shows postcodes for all organizations even not related to the agent. -
object created in Django forms not created in admin but saved DB
I am using UserCreationForm for the registration of new users, while new users are created using forms at the front end , it saved in database . However, I do not see any updates in the Django admin. I am not sure what is happening here. If someone could help with this issue. views.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form= UserCreationForm() return render(request,'users/register.html',{'form':form}) ---------------------------------------------------------------------------------------------- Project/urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from users import views as user_views from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('register/',user_views.register,name ='register'), path('', include('blogs.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) --------------------------------------------------------------------------------------------------- register.html {% extends 'blogs/base.html' %} {% load crispy_forms_tags %} {% load static %} {% block content %} <h2> Register </h2> <form class =site-form" action ="{% url 'register' %}" method="post"> {% csrf_token %} {{ form|crispy }} <input type ='submit' name="submit" value="Register"> </form> {% endblock %} ------------------------------------------------- Thank you in advance. -
Django multiple forms as popups and AJAX?
In my project I have a page where all the multiple user types are listed as cards and I was trying to add a detail view to each card with update and delete options within the card detail display. So this basically calls for AJAX calls. But I can't seem to figure out how to nest views within templates and style each forms according to my needs. Any advice? -
Form not rendering in template
form not rendering in template please sort out this problem my form forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) my view views.py def contactform(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = ContactForm() return render(request, 'portfolio/contact.html', {'form': form}) my templtae contact.html <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="send"> </form> -
TypeError create_superuser() got an unexpected keyword argument
I am in the progress of learning django, so kindly consider me as a newbie. I was able to use default user model in django, but while trying custom user model , i am facing issues in creating super user. I would like to have Email as username and have few additional fields like mobile number in my custom user table. Below is my models.py Model.py from django.db import models #from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser , BaseUserManager # Create your models here. class AccountManager(BaseUserManager): def create_user(self, email,firstName,lastName,m_phone,password=None,**kwargs): if not email: raise ValueError('Email Id is a required Field') if not firstName: raise ValueError('First name is a required Field') if not lastName: raise ValueError('Last name is a required Field') if not m_phone: raise ValueError('Mobile Ph. no is a required Field') user = self.model(email=self.normalize_email(email), firstName=firstName, lastName = lastName, m_phone = m_phone, **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email,firstName,lastName,m_phone,password): user = self.create_user(email=self.normalize_email(email), firstName=firstName, lastName = lastName, m_phone = m_phone, password = password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(unique=True) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) m_phone = models.CharField(verbose_name='Mobile Number' , max_length=50) l_phone = models.CharField(max_length=50) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) … -
Django translation not working on base html file?
I don't know what I am missing. I am working with django translation. The traslation works perfectly all apps other than the package folder, i.e app that contains settings.py. My file structure is like this: my-project/ manage.py locale/ mysite/ __init__.py settings.py lacale/ templates/ base.html urls.py profile/ __init__.py locale/ templates/ profile/ profile.html views.py urls.py Here are the settings file: MIDDLEWARE = [ .... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', .... ] LANGUAGE_CODE = 'es' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ('en-us', _('English')), ('es', _('Spanish')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) My base.html looks likem This translation does not work: {% load static %} {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> {% load i18n %} <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="author" content="Biplove Lamichhane"> <title>{% block title %}{% endblock title %}</title> </head> <body> <h1>{% trans "Base" %}</h1> {% block content %} {% endblock %} </body> My profile.html goes like this, This translation does work: {% extends 'base.html' %} {% load static %} {% load i18n %} {% block title %}Title{% endblock title %} {% block content %} <h2>{% trans "Check" %}</h2> {% endblock %} Also, I have correctly created django.po file and … -
How do i compute every product unitprice multipy by its quantity
I know how to use aggregate and annonate, (a little bit), but what i want is to compute every item product not the total average, how do i compute every product unitprice multipy by its quantity? this is my views.py This is the annotate total_amount_perproduct = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id') ).annotate( total_per_item=Count(F('unitprice') * F('quantity'), output_field=FloatField()) ) print('annotate', total_amount_perproduct) this is the result of annotate. annonate: <QuerySet [<CustomerPurchaseOrderDetail: 265>, <CustomerPurchaseOrderDetail: 266>]> this is the aggregate total = CustomerPurchaseOrderDetail.objects.filter(Status ='Active' ).filter( id__in=cart.values_list('id') ).aggregate( total=Sum( F('unitprice') * F('quantity'), output_field=FloatField(), ) )['total'] print('aggregate', total) This is the result: aggregate 198.0 -
How to connect two Django models?
New to Django and relational DBs. I'm building the classic Doctor appointment booking app and have come to a point where I don't know what to do. I watched online classes that mentioned no two models should not have ManyToMany relationships coming from both sides. So how can I circumvent the below? class Clinic(models.Model): doctors = # how to get list of all doctors in this clinic automatically from Doctor model class Doctor(models.Model): clinic = models.ManyToManyField(Clinic, related_name="doctor") -
Trying to insert date time value into django model but getting invalid format error
I am trying to save my date time values from the datetimepicker into the Django model. I am getting a time format error. This is the error : time data '2020-09-17T10:05' does not match format "yyyy-mm-dd'T'HH:MM" My code: name = request.POST["name"] date1 = request.POST["start"] startdate = datetime.strptime(date1, "yyyy-mm-dd'T'HH:MM") start = startdate.isoformat() date2 = request.POST["end"] enddate = datetime.strptime(date2, "yyyy-mm-dd'T'HH:MM") end = enddate.isoformat() e = Events(name=name, start=start, end=end) e.save(); -
Static files not served in Django "dockerized" (dev environnement)
I try to "dockerize" a Django apps. All works fine except static files that are not served. I run docker exec -it coverage_africa_web_1 python manage.py collectstatic command and get the confirmation You have requested to collect static files at the destination location as specified in your settings: /usr/src/app/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Found another file with the destination path 'randomization/js/script.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. 140 static files copied to '/usr/src/app/static'. settings.base.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = ( os.path.join(BASE_DIR,'randomization_management/static'), os.path.join(BASE_DIR,'randomization_settings/static'), os.path.join(BASE_DIR,'randomization/static'), ) MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') .env.dev SECRET_KEY=************************************* DEBUG=1 DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=db_dev SQL_USER=user SQL_PASSWORD=user SQL_HOST=db SQL_PORT=5432 DATABASE=postgres DJANGO_SETTINGS_MODULE=core.settings.dev docker-compose.yml version: '3.7' services: web: build: ./app restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine restart: always volumes: - postgres_data:/var/lib/postgres/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=user - POSTGRES_DB=db_dev volumes: postgres_data: -
Django AbstractBaseUser - Unable login to the admin panel
I just wanted to create a custom user model but unfortunately, I can not log in to the admin panel successfuly. I don't know what is my mistake... models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class CustomUserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password=None): if not email: return ValueError("User must have an email!") if not username: return ValueError("User must have an username!") if not first_name or not last_name: return ValueError("User must have a first name and last name!") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, password=None): user = self.create_user( username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name ) user.is_active = True user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name="Email", max_length=60, unique=True) username = models.CharField(verbose_name="Username", max_length=40, unique=True) first_name = models.CharField(verbose_name="First Name", max_length=40) last_name = models.CharField(verbose_name="Last Name", max_length=40) date_joined = models.DateTimeField(verbose_name="Date Joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff=models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def has_perm(self, perm, obj=None): return self.is_admin # this methods are require to login super user from admin panel def has_module_perms(self, app_label): return True settings.py ... … -
Django views and templates and static html
I want to fabricate some HTML inside my view and then have it rendered in my template. What I see rendered is xyz and I just want to see xyz. What am I doing wrong? My template snippet: {{ normalized }} My view snippet: context["normalized"] = "<div>xyz</div>" template_name = "demo.html" return render(request, template_name, context) -
How can I filter django many to many models?
User Model class User(PermissionsMixin, AbstractBaseUser): name = models.CharField(max_length=511, null=True, blank=True) email = models.EmailField(unique=True) phone_number = PossiblePhoneNumberField(blank=True, null=True, default=None) addresses = models.ManyToManyField(Address, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # is_featured = models.BooleanField(default=True) note = models.TextField(null=True, blank=True) date_joined = models.DateTimeField(default=timezone.now, editable=False) default_shipping_address = models.ForeignKey( Address, related_name='+', null=True, blank=True, on_delete=models.SET_NULL) default_billing_address = models.ForeignKey( Address, related_name='+', null=True, blank=True, on_delete=models.SET_NULL) reward_point = models.PositiveIntegerField(default=0, blank=True) last_login_user_ip = models.GenericIPAddressField(blank=True, null=True) last_login_user_country = CountryField(null=True, blank=True) USERNAME_FIELD = 'email' objects = UserManager() history = HistoricalRecords() Order Model class Order(models.Model): created = models.DateTimeField( default=now, editable=False) status = models.CharField( max_length=32, default=OrderStatus.UNFULFILLED, choices=OrderStatus.CHOICES) buyer_user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name='buyer_orders', on_delete=models.SET_NULL) vendor_users = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='vendor_orders') order_updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='order_updated_user', on_delete=models.SET_NULL, blank=True, null=True) is_ready_for_aadibd = models.BooleanField(default=False) is_ready_for_shipment = models.BooleanField(default=False) is_delivered = models.BooleanField(default=False) language_code = models.CharField( max_length=35, default=settings.LANGUAGE_CODE) tracking_client_id = models.CharField( max_length=36, blank=True, editable=False) billing_address = models.ForeignKey( Address, related_name='+', editable=False, null=True, on_delete=models.SET_NULL) User and Order Model relationship is Many to Many Now I'm filtering User (seller) who has at least one order is is_delivered=True. And I Print on user list my HTML page. But Problem is I got user who has not order is_deliverd=True seller_list = User.objects.select_related('vendor_details').prefetch_related('vendor_orders').filter( groups__name="vendor", vendor_details__isnull=False, vendor_orders__is_delivered=True).order_by( 'vendor_details__company_name').distinct() Date filter: seller_list = seller_list.filter(vendor_orders__created__date__gte=default_last_month_start_days, vendor_orders__created__date__lte=default_last_month_last_days) Order Filter: if selected_orders: … -
Keeping record of foreign key fields selected in Python Django
For a project I have a two model Food and Profile. Each day one profile is created.When users adds forr the food_selected field is updated.Everytime I update the food_selected field in profile I want to keep a record of it. So that I can show all the food selected for a single day class Food(models.Model): name = models.CharField(max_length=200 ,null=False) def __str__(self): return self.name class Profile(models.Model): food_selected=models.ForeignKey(Food,on_delete=models.CASCADE,null=True,blank=True) How can i solve this problem. Thank You -
Create an invitation link using django rest framework?
am looking for some advice/Mentorship. wanted to create an invitation link for onboarding user to a company similarly slack does by sending company employees email so that they could directly join the company but using the Django rest framework is there any method that you can refer? see things that I have in my mind coming is that I can put company_id in hash inside a link and then when a user will come with that hash I can compare it and onboard the user. but in that case, there is no link_time_age I can compare! is there any method or any crypto algo in which is can convert company_UUID into some string and decode back into UUID and then compare it through icontains and similarly I can do with time and age of link? but first of all, is this the right approach? or how do people in a company like slack or telegram do? any kind of help will be really appreciated. See what am looking for certain guidance or any reference documentation. -
SearchRank on multiple SearchVectorFields
I'm trying to integrate full text search in my application. Referencing Django 3.1 documentation If I want to do weighted search across several fields I should do the following: from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector vector = SearchVector('body_text', weight='A') + SearchVector('blog__tagline', weight='B') query = SearchQuery('cheese') Entry.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('rank') I decided to add SearchVectorField for the text columns I want to search later, but I think the documentation about how to work with those fields is not good enough and I can't find any reference on how to do the same as the query above, but using SearchVectorField Ideally I want something like the following objects = Post.objects.annotate( rank=SearchRank( F('title_text_vector', weight='A') + F('body_text_vector', weight='B'), SearchQuery('keyword1 keyword2 keyword3') ) ) objects.filter( < MORE QUERIES HERE > ) -
Django changing filters based on the selection made
I need some some help to find a good way to filter my Model. I want to display on a map just the objects which met the checked requirements. I passed my entire dictionary with all entries in my template and I want to create different select-boxes and dropdowns to filter it. For example I need a dropdown and after a value is selected I need to launch another forms with values from the result of the first dropdown selection. It's kind of what excel filters does for a table. I am thinking of using javascript but also I have read that Ajax could do this better. It's something like every E-commerce app does with the products, filtering a value changes the values of the other filters -
How can I render Django Form with vuetify?
In our regular Django form we can render the form with something like this {{form.username}} and we specify the widget within the constructor of the form class like name, class, id, label, etc. Now suppose that I have this form class class LoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput()) password = forms.CharField(widget=forms.PasswordInput()) class Meta: fields = ['email', 'password'] def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['password'].required = True How can I render it with vuetify components in template? # example <v-text-field label="username"></v-text-field> <v-select></v-select> # something like that Thanks you -
How to calculate time duration between 2 time intervals in django rest framework
I am trying to display over time work duration of an employee ,i have standard shift hours and working time , i need to subtract shift hours from worked hours.Here is my code models class EmployeeShift(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) employee_attendance = models.ForeignKey(EmployeeAttendance, on_delete=models.CASCADE, blank=True, null=True) shift = models.ForeignKey(Shift, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() class EmployeeAttendance(models.Model): employee = models.ForeignKey(Employee, related_name='employee_attendances', on_delete=models.CASCADE) check_in = models.TimeField() check_out = models.TimeField() def time_worked(self): check_in = datetime.datetime.combine(self.date, self.check_in) if self.check_out <= self.check_in: next_day = self.date+datetime.timedelta(days=1) else: next_day = self.date check_out = datetime.datetime.combine(next_day, self.check_out) time_worked = check_out-check_in return time_worked class Shift(ModelDateCommonInfo): name = models.CharField(max_length=150) start_time = models.TimeField() end_time = models.TimeField() def total_shift_hours(self): start_time = datetime.datetime.combine(self.created_at, self.start_time) if self.end_time <= self.start_time: next_day = self.created_at+datetime.timedelta(days=1) else: next_day = self.created_at end_time = datetime.datetime.combine(next_day, self.end_time) total_hours = end_time-start_time return total_hours views class EmployeeOverTime(generics.ListAPIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAuthenticated] serializer_class = EmployeeOverTimeSerializer def get_queryset(self): start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') employee_shift_map = EmployeeShift.objects.filter(employee__user=self.request.user,start_date__gte=start_date, start_date__lte=end_date).order_by('start_date') return employee_shift_map serializers class EmployeeOverTimeSerializer(serializers.ModelSerializer): employee_name = serializers.ReadOnlyField(source='employee_attendance.employee.user.first_name', read_only=True) time_worked = serializers.ReadOnlyField(source='employee_attendance.time_worked', read_only=False) total_shift_hours = serializers.ReadOnlyField(source='shift.total_shift_hours', read_only=False) class Meta: model = EmployeeShift fields = ['employee_name','time_worked','total_shift_hours'] Here i want to calculate over_time = time_worked - total_shift_hours , how can i achieve that, please help me … -
Django : using self.key where key is a variable in for loop
Good afternoon everyone. I have created a model in Django (code below) and I overwrite the save method to populate the fields. Inside the save methods I call a parser function which returns me a dict where the key is the name of the field in the model, and value, well is the value i'd like to write. The commented lines are working great (such as self.temp = parsedData['temp']) but I would like to refactor it. I thought of something like this but it's not working and I can't figure out why: for key, value in parsedData.items(): self.key = value Any ideas ? Thank you very much for your help :) class Data(models.Model): deviceId = models.ForeignKey('Device', to_field='deviceId', on_delete=models.CASCADE) rawData = models.CharField(max_length=24, blank=False, null=False) temp = models.DecimalField(max_digits=4, decimal_places=2, default=0) humidity = models.PositiveSmallIntegerField(default=0) pressure = models.DecimalField(max_digits=8, decimal_places=2, default=0) luminosity = models.PositiveSmallIntegerField(default=0) batteryLevel = models.PositiveSmallIntegerField(default=0) time = models.DateTimeField(null=False, default=now) def save(self, *args, **kwargs): """ Use the parser utility functions in utils to decode the payload """ firmware = Device.objects.get(deviceId=self.deviceId).firmware parsedData = parser(self.rawData, firmware) # Commented lignes below are working just fine # self.temp = parsedData['temp'] # self.humidity = parsedData['humidity'] # self.pressure = parsedData['pressure'] # self.luminosity = parsedData['luminosity'] # self.batteryLevel = parsedData['batteryLevel'] # How …