Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sidebar scroll down to section
I have a sidebar with a list of items where users can go to particular pages. What I'd like to do is to click on the element and scroll down to the section but it has to move to a section only when clicking on this button. The problem is that my a tag looks like this: <a href="{% url 'article_list' %}"> <li class="nav_list">go to section</li> </a> So I am not able to follow this pattern: <html> <body> <a id="top"></a> <!-- the entire document --> <a href="#top">Jump to top of page</a> </body> </html> Because as you can see a tag is already referring to article_list. I am using Django 3.2 and Bootstrap 5. Any advise on how this can be easly implemented will be appreciated. -
"KeyError: 'added' "when importing different lists of json
I'm getting a "KeyError: 'added'" Error when i try to import one of my three lists inside a json file. The list i'm trying to import is the one called "added". I had this working when it was just one list without the name "added" on top but now it seems like i can't access the list anymore. I want to individually import them basically. This is my code to get the Json parts before i import them into the database: class Command(BaseCommand): def import_facility_from_file(self, data): UUID = data.get('UUID', None) Name = data.get('Name', None) PrimaryAddress = data["AddressInfo"]["PrimaryAddress"] The new version of the Json File that im trying to use but thats causing the error: { "added": {"125hk24h5kjh43k5": { "UUID":"125hk24h5kjh43k5", "Name":"Test Facility 1", "AddressInfo": {"PrimaryAddress":"1234 Drive RD"}, "ImporterLastModifiedTimestamp":1643721420}}, "deleted":["235hk24h5kjh43k5,235hk345789h43k5"], "modified":{"995hk24h5kjh43k5": { "UUID":"995hk24h5kjh43k5", "Name":"Test Facility 2", "AddressInfo": {"PrimaryAddress":"2345 Test RD"}, "ImporterLastModifiedTimestamp":1643721420} } } The old version of the json file that worked perfectly with the code i intially wrote: {"00016ed7be4872a19d6e16afc98a7389b2bb324a2": {"UUID":"00016ed7be4872a19d6e1ed6f36b647f3eb41cadedd2130b103a5851caebc26fbbbf24c2f1a64d2cf34ac4e03aaa30309816f58c397e6afc98a7389b2bb324a2","Name":"Test Facility","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test@example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200", "AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0, "InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0}, "Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}}, "00016ed7be4872a15435435435b2bb324a2": {"UUID":"000c93dcb7a0b3d5783bb330892aff6abdb9fb57a7d3701c2d903f3640877579f3173ecd8a80532f6c3d53dbacde78a6a54ae42fef321a5793f5a01934f8de7a","Name":"Test Facility 2","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test@example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200", "AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0, "InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0}, "Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}}, "00234324324343243afc98a7389b2bb324a2": {"UUID":"fffd4dec10054e6e1deb2a2266a7c6bb0136ba46222e734ceed5855651f735cfbe0bb66cfaf27c3d175ae261a8f6df0c36b5390d15c70b07d67e35e1081aaf6d","Name":"Test Facility 3","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test@example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200", "AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0, "InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0}, "Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}}} So i tried it like this to get … -
How to Set DateTimeFields in Django Models to None Value (If current time is greater than this fields)
Below is my codes class Job(models.Model): pin_till = models.DateTimeField("Pin Job Post", null=True,blank=True) Here i wanna auto setup pin_till_date field to None if date is not None and than pin_till_date < now(). How to archives this method ah? with @property function, signals or just define in save function? -
upstream timed out by django and nginx in docker-compose
I have docker-compose which has django and nginx version: "3.9" services: admin_site: build: context: ./ dockerfile: Dockerfile_django.local ports: - "8011:8011" restart: always command: uwsgi --http :8010 --module admin_site.wsgi nginx: image: nginx:latest container_name: nginx volumes: - ./nginx/conf:/etc/nginx/conf.d - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./static:/static ports: - '81:80' depends_on: - admin_site After docker-compose up I can confirm that localhost:8011 works, so uwsgi works correctly. However when I access localhost:81 nginx | 2022/02/18 10:07:14 [error] 24#24: *4 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 172.18.0.1, server: dockerhost, request: "GET / HTTP/1.1", upstream: "uwsgi://172.18.0.2:8011", host: "localhost:81" nginx | 172.18.0.1 - - [18/Feb/2022:10:07:14 +0000] "GET / HTTP/1.1" 504 569 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36" "-" connection timeout occurs. Test: I log in the admin_site container and curl 172.18.0.2:8011 it response correctly. my nginx.conf file is here. upstream django { ip_hash; server admin_site:8011; } server { listen 80; server_name dockerhost; charset utf-8; location /static { alias /static; } location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; } } my nginx container log is here. Is there any place I need to check?? nginx | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration … -
How to catch IntegrityError with ManyToMany add() with wrong ids?
I have two models (just for example): class One(BaseModel): name = models.CharField() twos = models.ManyToManyField(Two) class Two(BaseModel): title = models.CharField() When I try to add a list of ids of model Two to model One with one.twos.add(*[id1, id2]) it works until I pass a wrong id, when this fails with psycopg2.errors.ForeignKeyViolation: insert or update on table "one_twos" violates foreign key constraint "one_two_id_572a5216_fk_twos" DETAIL: Key (two_id)=(e2871924-5bb4-492e-b7c3-4c5ca3cc7f5e) is not present in table "twos_two". django.db.utils.IntegrityError: insert or update on table "one_twos" violates foreign key constraint "one_two_id_572a5216_fk_twos" DETAIL: Key (two_id)=(e2871924-5bb4-492e-b7c3-4c5ca3cc7f5e) is not present in table "twos_two". This does not seem to be the race condition (mentioned here Django: IntegrityError during Many To Many add()). I need to tell the front-end that such-and-such id is not valid, but I can't catch these two IntergityErrors to re-raise my custom exception with a message and id. Would highly appreciate any help with this. -
Django template for loop is empty in another block
I have a function in my view.py: @login_required(login_url='login') def gpd(request,pk): # get gpd by id current_gpd = get_gpd(pk) # get current campaign year #TODO check types current_campaign = get_campaign(current_gpd.gpd_year) # get all corporate goals for current campaign corp_goals = CorporateGoal.objects.filter(gpd_year=current_campaign.year) compl_weight = [] for goal in corp_goals: compl_weight.append(goal.corp_factor_weight*current_gpd.bonus.corporate_component//100) corporate_goals = zip(corp_goals, compl_weight) if is_manager(request)!=None: team = get_team(request) context = {'gpd':current_gpd, 'corporate_goals':corporate_goals, } return render(request, 'app/gpd_forms/form_gpd.html', context) else: context = {'gpd':current_gpd, 'corporate_goal':corporate_goal, } return render(request, 'app/gpd_forms/form_gpd.html', context) As you can see, in context I have corporate_goal. My form_gpd.html: {% extends 'app/navbar/main.html' %} {% load static %} {% block content %} {% include 'app/slidebar/gpd_form_slidebar.html' %} <div class="container" style="background-color:white"> <div class="row"> <div id="section2" class="container-fluid"> {% include 'app/gpd_blocks/corporate_goal.html' %} </div> </div> <hr /> </div> <div class="container" style="background-color:white"> <div class="row"> <div id="section5" class="container-fluid"> {% include 'app/gpd_blocks/test.html' %} </div> </div> <hr /> </div> </div> {% endblock %} for example in corporate block I am executing next: {% load static %} {% block content %} <div class="row" id="super"> <p>&nbsp</p> </div> <div class="row" id="super"> <div class="col-11" style="color: ivory; font-weight: bold; font-size: 1.3em;"> CORPORATE GOALS BLOCK </div> </div> <div class="row" id="super"> <p>&nbsp</p> </div> {% for goal, compl_weight in corporate_goals %} <hr style="height:2px;border:none;color:rgb(87, 124, 161);background-color:rgb(87, 124, 161);" /> <!-- Corporate … -
Create Virtual Environment The system cannot find the path specified
I want to active venv in new folder , when i write "D:\pythonproject\first_django>env\Scripts\activate" in cmd I get " The system cannot find the path specified." also I installed venv , when I run this command "pip install virtualenv" in cmd get "Requirement already satisfied: virtualenv in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (20.13.0) Requirement already satisfied: filelock<4,>=3.2 in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (from virtualenv) (3.4.2) Requirement already satisfied: distlib<1,>=0.3.1 in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (from virtualenv) (0.3.4) Requirement already satisfied: six<2,>=1.9.0 in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (from virtualenv) (1.16.0) Requirement already satisfied: platformdirs<3,>=2 in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (from virtualenv) (2.4.1)" can any one tell me what's problem? I use win11 and python 3.10 -
Payment options with Django
I am trying to make a real time e-commerce site that people can really order stuff on. I wanted it to have an actual payment option like Stripe. But is there any other option other than Stripe? Can I use something like Payoneer, or PayPal or something like that? -
Django form add initial data to bound form
I am trying to add initial data from 1 form into the second form but I cannot seem to get it work. I've tried different methods but the closest I got came from this post Here is my code if request.method == 'POST': laptop_select_form = LaptopSelectForm(request.POST) if laptop_select_form.is_valid(): laptop_model_id = literal_eval(laptop_select_form.cleaned_data['model'])[0] laptop_for_parts_form = LaptopForPartsForm(request.POST, laptop_id=laptop_model_id) if laptop_for_parts_form.is_valid(): else: laptop_select_form = LaptopSelectForm() laptop_for_parts_form = LaptopForPartsForm() And the form class LaptopForPartsForm(forms.ModelForm): def __init__(self, laptop_id=0, *args, **kwargs): super(LaptopForPartsForm, self).__init__(*args, **kwargs) self.laptop_id = laptop_id class Meta: model = LaptopForParts fields = ('__all__') widgets={'laptop_id': forms.HiddenInput()} But I keep getting this error: laptop_for_parts_form = LaptopForPartsForm(request.POST, laptop_id=laptop_model_id) TypeError: __init__() got multiple values for argument 'laptop_id' Can someone more experienced please point me in the right direction? -
Not entering to the delete function [closed]
Here my modelserializer here my delete function note working not entering to the delete function def destroy(self,validated_data): gameevent = validated_data.get('gameevent') match_round =validated_data.get('match_round') match = Matchscore.objects.filter(gameevent=gameevent,match_round=max(match_round)) if match : match.delete() return response("success") else: raise serializers.ValidationError("Can't delete this round") -
I want to create a details page with two models for an auction site with django but keep getting FieldError. How do I correct this error?
I am creating an ebay like aunction site, the details view page should reflect details from two models. One of the models has the details of the current_bid (this is created when creating the listing), there is also the second model that contains new_bids (this is where the users who want to purchase the item can input their bids). The issue(s) I'm having is how to put two models in my details view and also if you can confirm my current logic in finding out the highest bid (if this is correct or not). MODELS.PY class Auction(models.Model): ABSTRACT = 'AB' MODERN = 'MN' ILLUSTRATION = 'IN' select_category = [ ('ABSTRACT', 'Abstract'), ('MODERN', 'Modern'), ('ILLUSTRATION', 'Illustration') ] title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) category = models.CharField( choices=select_category, max_length=12, default=MODERN, null=True, blank=True ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['-created_at'] class Bids(models.Model): auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name='bidding') user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='bidding') new_bid = models.DecimalField(max_digits=8, decimal_places=2) # new_bid = MoneyField(max_digits=10, decimal_places=2, null=False, blank=False, default_currency='USD', default=0) done_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['auction', '-new_bid'] FORMS.PY class AuctionForm(forms.ModelForm): class Meta: model = Auction fields = ['title', 'description', … -
pip install mysqlclient issues
when I try to use pip install mysqlclient issues command I get this error Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... done Collecting issues Downloading issues-0.0.0.tar.gz (858 bytes) Preparing metadata (setup.py) ... doneBuilding wheels for collected packages: mysqlclient, issues Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [42 lines of output] error: command '/opt/rh/devtoolset-7/root/usr/bin/gcc' failed: No such file or directory [end of output] -
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_HOST_USER
I've been trying to set up a contact form for my website and the form seems to go through ok but no email is actually sent. I then tried to debug by printing the EMAIL_HOST_USER in a test.py file from the command line and ran into this error which makes me think the variable isn't being passed from my local_settings.py Full Traceback call File "/Users/temporaryadmin/DCI_Projects/Portfolio/test.py", line 4, in <module> print(settings.EMAIL_HOST_USER) File "/Users/temporaryadmin/DCI_Projects/Portfolio/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 84, in __getattr__ self._setup(name) File "/Users/temporaryadmin/DCI_Projects/Portfolio/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 65, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_HOST_USER, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Any help would be appreciated, thanks. -
how to add django url and function in vue js code
I have a drf view to download the file i dont have knowledge on how to add the url in vue js here is how my code looks like views.py @api_view(('GET',)) def my_view(request,pk): data = get_object_or_404(Mymodel,pk) response = HttpResponse( data.data_file, content_type='', ) return response model.py class Mymodel(models.Model): datafile = models.FileField(upload_to='',blank=True) urls.py path('myurl/<int:pk>/',views.my_view,name='url_download') vue.js downloaddatafile: function (id) { alert('TODO: add URL & function to download datafile, file id: ' + id); }, -
I can not find the solution when it comes to CRISPY FORMS
IN MY DJANGO PROJECT I AM GETTING THIS EXCEPTION File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_formsmyapp -
Django. How to get profile picture url google Oauth2 api
how can I get a google profile picture with Oauth2 authorization settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djoser', 'accounts.apps.AccountsConfig', 'social_django', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'blog' ] SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid'] SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_DATA = ['first_name', 'last_name', 'fullname', 'username', 'picture'] models.py class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) picture = models.URLField(blank=True) fullname = models.CharField(max_length=100) username = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'fullname', 'picture', 'username'] returns all fields except picture during authorization -
How to save a model field having many to many realtionship with another model so that it will update the value automatically on another model?
I am having a model name 'tag' which has field name talent which has many to many relationship field with model name 'talent'. now I want to update the talent field and save it and it should update the talent model's tag field. I'm new in django. Please help me to find the solution for it. here's the code: tag.py from django.db import models from django.utils.translation import gettext as _ from fotoleybend.mixin import ( IsActiveAndVerifiedMixin, PrimaryKeyMixin, TimeStampMixin, ) from talent.models.talent import Talent class Tag(PrimaryKeyMixin, TimeStampMixin, IsActiveAndVerifiedMixin): """Tag model""" tag = models.CharField(unique=True, max_length=105, db_index=True) talents = models.ManyToManyField( "talent.Talent", blank=True, verbose_name=_("Tag Talents"), related_name="tag_talents", ) class Meta: ordering = ["tag"] def __str__(self): return self.tag talent.py from django.db import models from django.utils.translation import gettext as _ from fotoleybend.mixin import ( IsActiveAndVerifiedMixin, PrimaryKeyMixin, TimeStampMixin, ) class Talent(PrimaryKeyMixin, TimeStampMixin, IsActiveAndVerifiedMixin): """Talent model""" talent = models.CharField(unique=True, max_length=155, db_index=True) is_primary = models.BooleanField( verbose_name=_("Primary"), default=True, db_index=True ) tags = models.ManyToManyField( "talent.Tag", blank=True, verbose_name=_("Talent Tags"), related_name="talent_tags", ) class Meta: ordering = ["talent", "is_primary"] def __str__(self): return self.talent -
Django database modeling
I have a scenerio for which im trying to create the database models but I'm not able to find a perfect way to do it Scenerio is as follows . let's say there is a company which gives offer on his(companies own site) site and a different offer on other site(like Amazon) I want to store company details for which I did something as below. Next I have created the Direct Offers Last I have created Vendors offer All the models are as below class Company(models.Model): name= models.CharField(max_length=50, null=True) address= models.CharField(max_length=250, null=True) class DirectOffers(models.Model): Smartphone= models.FloatField(max_length=50, null=True) class VendorsOffers(models.Model): Smartphone= models.FloatField(max_length=50, null=True) category = models.CharField(max_length=250, null=True) owner = models.ForeigKeyField("Company",on_delete=models.CASCADE) But the above doesn't seems right So any help or guidance will be a great help. -
Django websocket and webrtc
I have made a Video Confrencing Application using django websocket and WebRTC and hosted on heroku.I am using channel_layer conneted with radis lab.And when i try to connect with two seprate window operating system and they get connected but when i tried the same with mac and windows my websockt tries to connect but failed. js console.log("working"); function createMenuItem(name) { let li = document.createElement('li'); li.textContent = name; return li; } const menu = document.querySelector('#menu'); window.onbeforeunload = function() { return "Are you sure?"; }; var labelUsername=document.querySelector('#label-username'); var usernameInput=document.querySelector('#username'); var btnJoin=document.querySelector('#btn-join'); var count; var username; var mapPeers={}; var webSocket; function webSocketOnMessage(event){ var parsedData= JSON.parse(event.data); var peerUsername = parsedData['peer']; var action = parsedData['action']; if(username==peerUsername){ return; } var receiver_channel_name = parsedData['message']['receiver_channel_name'] if(action == 'new-peer'){ createOfferer(peerUsername,receiver_channel_name); return; } if(action == 'new-offer'){ var offer=parsedData['message']['sdp']; createAnswerer(offer,peerUsername , receiver_channel_name); return; } if(action=="new-answer"){ var answer = parsedData['message']['sdp']; var peer = mapPeers[peerUsername][0]; peer.setRemoteDescription(answer); return; } console.log('message',message); } btnJoin.addEventListener('click',() =>{ username=usernameInput.value; console.log('username :' ,username); if(username=="") { return; } usernameInput.value=""; usernameInput.disabled=true; usernameInput.style.visibility= 'hidden'; btnJoin.disabled=true; btnJoin.style.visibility='hidden'; var labelUsername = document.querySelector('#label-username'); labelUsername.innerHTML=username; var loc =window.location; var wsStart='ws://'; if(loc.protocol=='https:'){ wsStart= 'wss://'; } var endPoint = wsStart +loc.host + loc.pathname; console.log('endPoint:',endPoint); webSocket=new WebSocket(endPoint); webSocket.addEventListener('open',(e)=> { console.log("open"); sendSignal('new-peer',{}); }); webSocket.addEventListener('message',webSocketOnMessage); webSocket.addEventListener('close',(e)=> { console.log("close") }); webSocket.addEventListener('error',(e)=> { console.log("error") … -
PermissionError: [Errno 13] Permission denied: '/var/log/gunicorn.error.log'
I have a Django app and I want to deploy it in docker but I got the error PermissionError: [Errno 13] Permission denied: '/var/log/gunicorn.error.log'. I have no idea anymore where the problem is. could someone help me, please? My dockerfile: # BUILDER # ########### # pull official base image FROM python:3.9.6-slim as builder # set work directory WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apt-get update \ && apt-get install -y build-essential python3-dev python2.7-dev \ libldap2-dev libsasl2-dev libssl-dev ldap-utils tox \ lcov valgrind \ && apt-get -y install gcc \ && apt install -y netcat # install psycopg2 dependencies RUN apt-get install -y postgresql-server-dev-all musl-dev # lint RUN pip install --upgrade pip COPY . . # install python dependencies COPY requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt # pull official base image FROM python:3.9.6-slim RUN apt-get update && apt install -y netcat # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup --system --disabled-password app && adduser --system --group --disabled-password app # RUN addgroup --system app && adduser --system --group app # RUN adduser --disabled-password --gecos '' app … -
Update in DB column vlaues using django script
I have to update in DB table column name batch_status for which I have written the SQL query here UPDATE farm_management_batch set batch_status = "running" where start_date < now() and batch_status = "to_start" UPDATE farm_management_batch set batch_status = "completed" where batch_status IN ('to_start', 'running') and expected_delivery_date < now() But now I want to write a Django script for this which I have no idea how to do it Here Is the Screenshot -
How to join 2 tables in django ORM
I have 2 Tables. TableA and TableB. id is the primary key in TableB and the foreign key in TableA. My task is to find all the items from TableB where the id should match the item_ids. I am able to get all the items with the below queries. But I'd like to understand how to apply joins on the both tables using select_related to get the same result. item_ids = list(TableA.objects.filter(is_active=True).\ distinct().\ values_list('item_id', flat=True)) items = TableB.objects.filter(Q(id__in=item_ids) & \ Q(display_name__isnull=False) & \ Q(name__isnull=False)).\ values("name", "display_name") Could someone help me with the query? -
Is there a way to mock the firebase_admin credentials.Cerificate class in Django?
In my project, FirebaseAuthentication is used and while running the test cases(pipenv run python manage.py test) I am getting the following error - ValueError: Invalid certificate argument: "None". Certificate argument must be a file path, or a dict containing the parsed file contents. authentication.py from firebase_admin import auth from firebase_admin import credentials cred = credentials.Certificate(os.getenv('FIREBASE_ADMIN_KEY_PATH')) default_app = firebase_admin.initialize_app(cred) tests.py(where I have not imported authentication file) from django.test import TestCase class A(TestCase): .... I am trying to run specific app test case but somehow it is trying to import authentication.py. That is why cred = credentials.Certificate(os.getenv('FIREBASE_ADMIN_KEY_PATH')) is getting executed. I have identified that cred and default_app are declared at global level. And I cannot move it to other function or classes for the same file. I have noticed that cred = credentials.Certificate(os.getenv('FIREBASE_ADMIN_KEY_PATH')) returns the object and not specific data and also calls the Firebase API for authentication. How can I mock this two line at a global level? -
How to do multiple or chained filter functionality dynamically in Django?
context_processors.py def menu_categories(request): subcategories= SubCategory.objects.all() return {'subcategories': subcategories} template {% for subcategory in subcategories%} <li><a href="{{ subcategory.get_url }}">{{ subcategory.title|title}}</a></li> {% endfor %} views.py def products_list(request, subcategory_slug=None, brand_slug=None): if subcategory_slug != None: ----------some filter elif brand_slug != None: ----------some filter else: products = Product.objects.all() context = {'products' : paged_product} return render(request, 'product/products_list.html',context) models.py class Product(DateTimeModel): maincategory = models.ForeignKey(MainCategory, null=True, on_delete=models.CASCADE) productcategory = models.ForeignKey(ProductCategory, null=True,on_delete=models.CASCADE) subcategory_slug = models.SlugField(max_length=300, unique=False, null=True,blank=True) product_slug = models.SlugField(max_length=300, unique=False, null=True, blank=True) ------- ------- def get_url(self): return reverse('product:product_details', args=[self.subcategory_slug, self.product_slug]) I am getting this. I need like this multiple select checkbox filter. It should be done dynamically after the product was added by the vendor. Now, I am done with the single filter results. But, I need to achieve multiple chained filters. Don't know how to do it. Please needed help. -
django jwt "detail": "Authentication credentials were not provided."
I am trying to implement jwt token authentication in my Django Rest Framework application. I am able to receive a token from the django server as you can see POSTMAN request but when I try to get user profile, I got this error. Does anyone have idea?? { "detail": "Authentication credentials were not provided." } I could get access token as you can see. This is SIMPLE_JWT setting in settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=3), 'AUTH_HEADER_TYPES': ('JWT', ), 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken', ) } This is app/urls.py urlpatterns = [ path("admin/", admin.site.urls), path("api/", include("user.api.urls")), path('api/auth/', include('djoser.urls')), path('api/auth/', include('djoser.urls.jwt')), ] This is app/user/urls.py router = DefaultRouter() router.register("api/auth/users/", TraineeRegisterApiView) urlpatterns = [ path('profile/', TraineeProfileApiView.as_view({'get': 'retrieve'})) ]