Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Testing using Testcase error finding the batch_name and instances
I am performing the testing for the models.py file Django After completing the test case for a few classes I am stuck at a point First, let me share the models.py file import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) … -
Why IsAdminUser is not naming IsStaffUser?
Why IsAdminUser is not named IsStaffUser in django restframework permmission? class IsAdminUser(BasePermission): """ Allows access only to admin users. """ def has_permission(self, request, view): return bool(request.user and request.user.is_staff) IsStaffUser seems more appropriate just to me? -
Django CSRF verification failed. Webhook payment system
I'm trying to implement a webhook for my payment system. I have a path to my webhook view, which is a simple definition where the provided id is printed. The usage is like this http://localhost:8000/api/mollie-webhook/?id=ExampleId Path # mollie webhook path('api/mollie-webhook/', mollie_webhook, name='mollie_webhook'), View def mollie_webhook(request): id = request.POST['id'] print(id) return JsonResponse(data={"response": "Success!"}) I'm getting the following error CSRF verification failed. Request aborted. -
Django_filters check if value/connection exists
Hej! I'm looking for an option on how to filter IF the value exists, the value itself is irrelevant. To filter all institutions with the given AddOn. A checkbox would be best where I can 'check' if I want my database entries filtered by this variable or not. If it's 'checked' I want to filter all entries which have the given variable and if it's not checked I don't want to filter. models.py class Institution(models.Model): name = models.CharField( verbose_name=_("Name of the institution"), max_length=200, ) abbreviation = models.CharField( # null=False, but "" allowed. Is Django convention verbose_name=_("Acronym"), max_length=25, blank=True, help_text=_("if applicable"), ) class AddInstitutionMorebio(models.Model): institution = models.OneToOneField( Institution, on_delete=models.PROTECT, related_name="institution_morebio" ) id_morebio = models.CharField( max_length=6, unique = True ) filters.py class InstitutionFilter(django_filters.FilterSet): name = django_filters.CharFilter(method='name_filter', label="Name") morebio_id = AddInstitutionMorebio.objects.filter(id_morebio=True) # this does nothing Does someone know what to do? Any help is appreciated! :) -
Creating a form that updates only 1 field of an entry
I am currently trying to create a checklist that would print a customer database. this checklist would print all the customers for a specific service - in this case, its IT14's- and it would let the user update the checklist field (isdone_IT14) However, the error I am running into at the moment, is that the form is not valid due to the fact that the rest of the fields are required. It looks like when the checklist is ticked, the form is trying to create a new entry. How would I fix that issue so that it only updates the field for that one entry? Please see the below code and errors (print(form.errors)) Models.py: class CompanyClass(models.Model): #Company Only Fields CompanyName = models.CharField(max_length=50 , blank=False) RefNo = models.CharField(max_length=50 , blank=False ) #Contact Details ContactPerson = models.CharField( max_length=50, blank=False) EmailAddress = models.CharField(max_length=50, blank=False) #Services IT14 = models.BooleanField(default=True) FinancialStatements = models.BooleanField(default=True) IsProvisionalTaxPayer = models.BooleanField(default=True) AnnualReturns = models.BooleanField(default=True) # CheckList isdone_IT14 = models.BooleanField(default=False) isdone_FinancialStatements = models.BooleanField(default=False) isdone_Provisionals = models.BooleanField(default=False) isdone_AnnualReturns = models.BooleanField(default=False) Views.py: class companyIT14(View): def get(self,request): it14s = CompanyClass.objects.filter(IT14 = True).order_by('CompanyName') form = CompanyForm() content = {'it14s':it14s , 'form':form} return render(request, 'main/Checklists/companyIT14.html', content) def post(self,request): it14s = CompanyClass.objects.filter(IT14=True).order_by('CompanyName') form = CompanyForm(request.POST) content = … -
How to serve django video streaming app on nginx
I have a django app which uses opencv videocapture to stream video from a cctv cam into my computer screen. But after hosting it using nginx. The video stream gets slowed down, hangs and sometimes quit with an error message. I read that configuring rtmp server is the way to do it but there is literally no tutorial to do so. Please Help! -
signal for custom user registration in django
help please !! I have a custom user model that I am using in my project. And I create a wallet to my new users by using signal, when they register. @receiver(post_save, sender=User) def create_saving_wallet(sender, instance, **kwargs): [...] In the function, I am doing basic things like wallet = Wallet(user_id=user, wallet_type=wallet_type, amount=amount And, I have in app.py this class to send the signal : from django.apps import AppConfig from django.core.signals import request_finished class MyAppConfig(AppConfig): def ready(self): from wallet import views # Explicitly connect a signal handler. request_finished.connect(views.create_saving_wallet, dispatch_uid="azerty123") Everything work well when we use the registration form, but if we use admin site to login the signal is called and then the old wallet is updated. How can I do to avoid this behavior ? The signal should just be called when save() method of my custom user is called. I am not sure but since I have this bug, does it mean that when a user logged in, save() method is called ? -
Django Baton installation
I am trying to add Django-Baton to my Django project but i get this error when trying to run the server: from django.utils.translation import ugettext as _ ImportError: cannot import name 'ugettext' from 'django.utils.translation' (/home/kalilinux/Desktop/Virt/myvirtualenv/lib/python3.8/site-packages/django/utils/translation/__init__.py) -
How to get a csv right into SQL
The question from a noob. I have a website from which i can download csv. This is the only purpose of the site: open it in a web-browser, enter a login + password, select the necessary fields - get a csv. The question is : are there any ways to execute this http request from my web application (django) to get this csv upload right into my SQL, bypassing the web browser? -
is Heroku apps Ranks on Google
I want to deploy my Django Project on Heroku just for testing project such as testing project. But I dont want to rank my project on google. I am not sure heroku project is rank on google or not. is any option available like I can make my project private.. -
How to remove intermediate pages during Django all auth Facebook login?
I am using Django all-auth to enable Google & Facebook social logins to my application. The config is as follows: Django Allauth Settings: ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_AUTHENTICATION_METHOD = "email" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_VERIFICATION = "none" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_ADAPTER = "streampala.users.adapters.AccountAdapter" # https://django-allauth.readthedocs.io/en/latest/configuration.html SOCIALACCOUNT_ADAPTER = "streampala.users.adapters.SocialAccountAdapter" # https://django-allauth.readthedocs.io/en/latest/forms.html ACCOUNT_FORMS = { 'login': 'allauth.account.forms.LoginForm', 'signup': 'users.forms.AdvertisersSignUpForm', 'add_email': 'allauth.account.forms.AddEmailForm', 'change_password': 'allauth.account.forms.ChangePasswordForm', 'set_password': 'allauth.account.forms.SetPasswordForm', 'reset_password': 'allauth.account.forms.ResetPasswordForm', 'reset_password_from_key': 'allauth.account.forms.ResetPasswordKeyForm', 'disconnect': 'allauth.socialaccount.forms.DisconnectForm', } SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE": [ "profile", "email", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/youtube.upload", "https://www.googleapis.com/auth/youtube.force-ssl", ], "AUTH_PARAMS": { "access_type": "offline", }, }, "facebook": { 'METHOD': 'oauth2', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'first_name', 'last_name', 'middle_name', 'name', 'name_format', 'picture', 'short_name' ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v7.0', }, } This is what I see after clicking on Google/Facebook login button: And this comes up after completing Facebook login: I don't want any of these two intermediate screens, and tried modifying configuration as well. But these screens are not mentioned in the Django All-Auth docs so what am I missing? -
cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls/__init__.py)
ImportError at / cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls/init.py) Request Method: GET Request URL: https://aas-system.herokuapp.com/ Django Version: 4.0.1 Exception Type: ImportError Exception Value: cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls/init.py) Exception Location: /app/.heroku/python/lib/python3.9/site-packages/webpush/urls.py, line 1, in Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Tue, 01 Feb 2022 07:52:34 +0000 -
OperationalError no such column: ""
I am trying to create a "checklist" type form in Django based on a customer model. The checklist would just need to display the Name, RefNo, Contact Person and Email Address fields for each customer that has been saved into the database. However, I have then added a boolean field (isdone_IT14) which the user should tick to say whether that task for that customer has been done. When I try to load the checklists page the error: no such column: main_companyclass.isdone_IT14 is shown Please see the below code and full error message: Models.py: class CompanyClass(models.Model): #Company Only Fields CompanyName = models.CharField(max_length=50 , blank=False) RefNo = models.CharField(max_length=50 , blank=False ) #Contact Details ContactPerson = models.CharField( max_length=50, blank=False) EmailAddress = models.CharField(max_length=50, blank=False) #Services IT14 = models.BooleanField(default=True) # CheckList isdone_IT14 = models.BooleanField(default=False) def __str__(self): return ( self.CompanyName) Forms.py: class CompanyForm(ModelForm): class Meta: model = CompanyClass fields = '__all__' Views.py: class companyIT14(View): def get(self,request): it14s = CompanyClass.objects.filter(IT14 = True).order_by('CompanyName') form = CompanyForm() content = {'it14s':it14s , 'form':form} return render(request, 'main/Checklists/companyIT14.html', content) def post(self,request): it14s = CompanyClass.objects.filter(IT14=True).order_by('CompanyName') form = CompanyForm(request.POST) content = {'it14s': it14s, 'form': form} if form.is_valid(): form.save() return redirect('companyIT14') else: return render(request, 'main/Checklists/companyIT14.html', content) Template (companyIT14.html): {% extends "main/base.html"%} <html lang="en"> <head> <meta … -
Rename and move files in local system using website
I am developing a website with frontend react and backend as django where users can generate names of files in a particular format. Now this files will be in their local system or their local servers we can say. I need to rename the file and move that to a source folder. Is that possible using a website? I have heard this is possible but now sure how. Anybody knows how this can be done? -
How to fix 'Meta.fields' must not contain non-model field names: username for django graphene authentication endpoint
In my Django application I have created customer user model which uses email as username. class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True,) user_id = models.UUIDField( default=uuid4, unique=True, ) I am using graphene for APIs. For authentication endpoint I am following below steps, https://django-graphql-auth.readthedocs.io/en/latest/quickstart/ I am keep getting below error, sports_league-web-1 | File "/usr/local/lib/python3.10/site-packages/django_filters/filterset.py", line 71, in __new__ sports_league-web-1 | new_class.base_filters = new_class.get_filters() sports_league-web-1 | File "/usr/local/lib/python3.10/site-packages/django_filters/filterset.py", line 358, in get_filters sports_league-web-1 | raise TypeError( sports_league-web-1 … -
django: Password is not storing in DB with form
I'm trying to save some form inputs into the DB by extending the default auth library. For some reason, it is only saving the "email" in the DB. The password field was not stored and no error was shown. What am I doing wrong? Please help! Thanks! #views.py from django.shortcuts import render, redirect from django.http import HttpResponse from Accounts.forms import CreateUserForm # Create your views here. def registerPage(request): #debugDump form = CreateUserForm if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): return HttpResponse(request) form.save() context = { 'form':form } #return HttpResponse(form.error_messages) return render(request, 'accounts/register.html', context) #Accounts\forms from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.contrib.auth import get_user_model from django.http import HttpResponse User = get_user_model() class CreateUserForm(forms.ModelForm): password1 = forms.CharField() password2 = forms.CharField() class Meta: model = User fields = ['email','password1', 'password2'] def clean_email(self): ''' Verify email is available. ''' email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean(self): ''' Verify both passwords match. ''' cleaned_data = super().clean() password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") if password1 is not None and password1 != password2: self.add_error("password2", "Your passwords must match") return cleaned_data -
Django Testing using Testcase error finding the batch_name
I am performing the testing for the models.py file Django After completing the test case for few classes I am stuck at a point First, let me share the models.py file class Batch(models.Model): commodity_id = models.PositiveIntegerField(null=True, blank=True) commodity_variety_id = models.PositiveIntegerField(null=True, blank=True) farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="batches", null=True, blank=True, db_column='farm_id') start_date = models.DateTimeField(null=True, blank=True) acerage = models.FloatField(verbose_name='Batch Acerage', help_text="In Acres;To change this value go to farms>crop" , validators=[MaxValueValidator(1000000), MinValueValidator(0.01)]) batch_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0)], help_text="In Percentage", default=100, null=True, blank=True) stage = models.CharField(max_length=100, choices=config.STAGE_CHOICES, default='germination', null=True, blank=True) expected_delivery_date = models.DateTimeField(null=True, blank=True) current_pdd = models.FloatField(null=True, blank=True) historic_pdd = models.FloatField(null=True, blank=True) current_gdd = models.FloatField(null=True, blank=True) historic_gdd = models.FloatField(null=True, blank=True) sub_farmer_id = models.PositiveIntegerField(null=True, blank=True) batch_status = models.CharField(max_length=100, choices=config.BATCH_STATUS, default='to_start') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) updated_by_id = models.PositiveIntegerField(null=True, blank=True) created_by_id = models.PositiveIntegerField(null=True, blank=True) historical_yield_per_acre = models.FloatField(verbose_name="Yield / Acre - Historical", null=True, blank=True) expected_produce = models.FloatField(default=0, null=True, blank=True) actual_produce = models.FloatField(default=0, null=True, blank=True) sop_adherence = models.FloatField(default=0, null=True, blank=True) actual_yield_per_acre = models.FloatField(default=0, null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) commodity_name = models.CharField(max_length=200, null=True, blank=True) batch_name = models.CharField(max_length=200, null=True, blank=True) batch_median_health = models.PositiveIntegerField(null=True, blank=True) pending_tasks = models.PositiveIntegerField(null=True, blank=True, default=0) history = HistoricalRecords() def __str__(self): return self.batch_name def save(self, *args, **kwargs): SOPMaster = apps.get_model('sop_management', 'SOPMaster') BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement') batch_sop_list = … -
Django Serializer - Combine fields from two models
I have two models namely: class B (models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) class A (models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) b = models.ForeignKey(B,on_delete=models.CASCADE,null=True) I want a serializer which returns a response like this: { "id": 1, "name": "test", "b_id": 2, "b_name": "test } -
Django can't find me .evn variables? decouple.UndefinedValueError: ENVIORNMENT not found. Declare it as envvar or define a default value
I am very new to Django and trying to configure python-decouple to use .env variables. I am getting DB_PASSWORD not found. Declare it as envvar or define a default value. when trying to run the server. The .env file is located in the root directory. Here is my code: raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: ENVIORNMENT not found. Declare it as envvar or define a default value. settings.py DATABASES = { "default": { "ENGINE": config("DB_ENGINE"), "NAME": config("DATABASE_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT", cast=int), "OPTIONS": { "init_command": "SET foreign_key_checks = 0;", }, } } .env SECRET_KEY='nvyj6_-&m@lg87$%l3@@#+r046ioem^18+ql*)t)' DEBUG=True DB_ENGINE=django.db.backends.mysql DATABASE_NAME=blogs DB_USER=root DB_PASSWORD= DB_HOST=127.0.0.1 DB_PORT=3306 Django==3.1.4 python-decouple==3.3 -
Confusion of using Django rest Frame work
So there is a thing I have been very confused about and even after search and watching youtube videos still my concept is not clear. I have created an app with frontend in react and used django rest framework for backend because I know the data that comes from react is in json which normal django doesnt understand. so that's it. Now there is one more app I am working on and my client told me to created an API. Now my questions why would I need an API if the app is only for web can't I use simple django for it? Or not creating an API and directly interacting with the app is bad idea? also can if I create an API do you think I can use it for mobile backend too. How would registration login and logout things work? -
Django Form with dependent ForeignKey forms on one Page
Good day, I am trying to implement django with a dependent foreignkey forms on one page. I have three moodels Store, Product, and ProductClothing. They are all ForeignKey related respectively. Users get to create their store seperately, and are redirected to the store detail view where they will now have to upload Products. But this time, I want them to upload both products and product clothing at once. Below is my models.py and views.py of what I have currently on the store detail view. Also the error I get is: error.py NOT NULL constraint failed: product_productclothing.product_id models.py class Store(models.Model): owner = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, unique=True) slug = AutoSlugField(populate_from='name', unique=True) description = models.CharField(max_length=255, blank=True) def __str__(self): return self.name class Product(models.Model): store = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL) owner = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2, verbose_name=_("Regular price")) class ProductClothing(models.Model): CLOTHING_GENDER_CHOICES = ( ('M', 'Male',), ('F', 'Female',), ('U', 'Unisex',), ) CLOTHING_TYPE_CHOICES = ( ('dress', 'Dresses',), ('fabric', 'Fabrics',), ('shirt', 'Shirts',), ('suit', 'Suits',), ('tshirt', 'T-Shirts',), ('base_layers', 'Base_Layers',), ('blazer', 'Blazers',), ) product = models.OneToOneField(Product, on_delete=models.CASCADE) gender = models.CharField(max_length=10, choices=CLOTHING_GENDER_CHOICES, blank=True, null=True) clothing_type = models.CharField(max_length=255, choices=CLOTHING_TYPE_CHOICES, blank=True, null=True) def __str__(self): return self.product.title views.py @login_required def store_dashboard_view(request, slug): store = get_object_or_404(Store, slug=slug) … -
Model don't get objects in clean_<fieldname> functions
I have a question. İ have a custom user model and İ created a form for user creating. User model and Registration form code will be above. In clean methods for every fields User methods don't work. So I wanna get User model objects but User model returns empty QuerySet. But I have 2 users in my database. I try get user objects in clean_email and clean_username but both of get methods return empty QuerySet. Can anyone help me? User model: class UserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, date_of_birth, password=None): if not email: raise ValueError("Users must have email") if not username: raise ValueError("Users must have username") if not first_name: raise ValueError("Users must have first name") if not last_name: raise ValueError("Users must have last name") if not date_of_birth: raise ValueError("Users must have date of birth") email = self.normalize_email(email) first_name = normalize_name(first_name) last_name = normalize_name(last_name) user = self.model( email = email, username = username, first_name = first_name, last_name = last_name, date_of_birth = date_of_birth ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, date_of_birth, password=None): user = self.create_user( email = email, username = username, first_name = first_name, last_name = last_name, date_of_birth = date_of_birth, password = password ) user.is_admin = True … -
Group By Django queryset by a foreignkey related field
I have a model Allotment class Kit(models.Model): kit_types = (('FLC', 'FLC'), ('FSC', 'FSC'), ('Crate', 'Crate'), ('PP Box', 'PP Box')) kit_name = models.CharField(max_length=500, default=0) kit_type = models.CharField(max_length=50, default=0, choices=kit_types, blank=True, null=True) class AllotmentFlow(models.Model): flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) asked_quantity = models.IntegerField(default=0) alloted_quantity = models.IntegerField(default=0) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) send_from_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) flows = models.ManyToManyField(AllotmentFlow) For a stacked graph I am trying to get the data of different kit_type alloted in different months. For that I have tried annotate but it isn't getting the desired results dataset = Allotment.objects.all().annotate( month=TruncMonth('dispatch_date')).values( 'month').annotate(dcount=Count('flows__kit__kit_type')).values('month', 'dcount') Expected Output: [{'month':xyz, 'kit_type':foo, count:123},...] I am getting the month and count of kit type from above but how do I segregate it by kit_type? -
Store all response of request module in database
So, I am using Django rest framework and to log all these API calls i am using Django rest framework API Logger module but does not log third party API calls. In my case i am using request module to deal with third party API calls and i want to store all the response into database of request module. please help me regarding this, Thanks. for example how i am using request module class LoginView(APIView): def get(self, request, *args, **kwargs): data = request.GET.copy() url = '{}/patient/mrn-login/'.format(settings.SNM_BASE_URL) params = {"no": data.get('no')} headers = {'Authorization': settings.SNM_AUTH_TOKEN} resp = requests.get(url, params=params, headers=headers) # Check the response status here if resp.status_code < 300: ''' When got the status 200 send the OTP to user telecom system here only ''' json_resp = resp.json().get('data') if data.get('channel') == 'email': otp_resp = send_email_otp(json_resp) else: otp_resp = send_otp(json_resp) return Response(otp_resp.json(), status=otp_resp.status_code) return Response({"message": "User doesn't exist"}, status=status.HTTP_404_NOT_FOUND) -
django form clean_<fieldname> method
I looked through similar answers but was surprised there was nothing in that list addressing such a basic question. My Django form is as follows: class JobApplicationForm(forms.Form): message = forms.CharField(widget=forms.Textarea) documents = forms.FileField(label="Documents", widget=DocumentUploadWidget) def clean(self): super().clean() def clean_documents(self): print ("clean_documents") return self.cleaned_data['clean_documents'] I can't find how to get clean_documents() to be called. The documentation says to use the form.is_valid() method but that doesn't work for me. Here is my sample Django shell session: Python 3.7.5 (default, Feb 23 2021, 13:22:40) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from home.forms import JobApplicationForm >>> f = JobApplicationForm({'message':'sdfsfsdfs'}) >>> f.is_bound True >>> f.is_valid() False >>> f.errors {'documents': ['This field is required.']} >>> At no stage did I see the result of the print statement in the clean_documents() method. What else needs to happen to see it?