Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Combine Common Values from Joining Two List of Dictionaries
I have 2 Lists of dictionaries, example below: list one = [ {'day': '2021-09-05 00:00:00+02:00', 'airtime_total_for_day': '650.00', 'data_total_for_day': '0'}, {'day': '2021-09-16 00:00:00+02:00', 'airtime_total_for_day': '124.20', 'data_total_for_day': '20.00'}, ] list_two = [ {'day': '2021-09-10 00:00:00+02:00', 'data_bundle_total_for_day': '100.00'}, {'day': '2021-09-16 00:00:00+02:00', 'data_bundle_total_for_day': '50.00'}, {'day': '2021-09-18 00:00:00+02:00', 'data_bundle_total_for_day': '45.00'}, ] I would like to merge the two lists together and at the same time, merge data_total_for_day with data_bundle_total_for_day under the name data_total_for_day. Also, if data_total_for_day & data_bundle_total_for_day happen to fall on the same day which they do on the 2021-09-16, the values need to be added together e.g. data_total_for_day on the 2021-09-16 is: 20.00 data_bundle_total_for_day on the 2021-09-16 is: 50.00 So on that specific day, data_total_for_day needs to be: 70.00 I've struggled and all & any help with be greatly appreciated. Things I tried: https://www.codegrepper.com/code-examples/python/merge+two+list+of+dictionaries+python How to merge two list of dictionaries based on a value join two lists of dictionaries on a single key -
How to make users see other user products in Django [closed]
is it possible to create a link to a different user and see only that users items? I started up a software that allows users to post their products to a site were every user can see the product. The problem is, I want any user to click on that post and it takes the user to a page that has items only by that user -
How to switch to windows desktop via bash
I'm following this instruction https://stackoverflow.com/a/33993532/16250669, but I can't complete step 5, how do I get to C:\Users\kudla\Desktop\food_delivery via bash console if when I enter ls I get output: bash-4.3# ls bin docker-entrypoint.sh lib proc sbin tmp dev etc media root srv usr docker-entrypoint-initdb.d home mnt run sys var -
Open ports 8000 and 3000 on EC2 AWS instance
I am trying to run Django in port 8000 and React in port 3000 on an EC2 AWS instance. I first created the inbound rules for ports 8000 and 3000: Then, I start both Django and React on ip 0.0.0.0 sudo npm start sudo python manage.py runserver 0.0.0.0:8000 And I can check both ports are open and listening: However, when I try to reach the urls http://external_ip:8000/ or http://external_ip:3000/ Nothing is working. However, I can make Django server works if I change 8000 by 80. What am I doing wrong or missing? -
How can i determine number object show per page when using ListView pagination in django?
please how can i determine number of objects/page show(not number of pages) in Django when using ListView Pagination. that's my code in Views.py : from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class PostList(ListView): model=Post context_object_name='all_post' ordering=['-created_at'] thank you! -
How to configure ID parameters in django_rest_framework APIView
My goal is to specify behavior that allows me to enter an ID into my URL. Currently, I am able to send GET, PUT, and PATCH requests to the URL 'localhost:8000/api/?id=#' where the hash represents any object id. I would like to update my code to understand that if I send a GET/PUT/PATCH request to 'localhost:8000/api/2' that I am looking for and object with id=2 my models.py class player(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) team = models.CharField(max_length=50) position = models.CharField(max_length=50) number = models.IntegerField() def __str__(self): return "{}, {}".format(self.first_name, self.last_name) my serializer.py class playerSerializer(serializers.ModelSerializer): class Meta: model = player fields = ['id', 'first_name', 'last_name', 'team', 'position', 'number'] my views.py from django.shortcuts import render from django.http import HttpResponse, response from django.shortcuts import get_object_or_404 from rest_framework import serializers from rest_framework. serializers import Serializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from main.models import player from .serializers import playerSerializer import json class playerList(APIView): serializer_class = playerSerializer throttle_scope = "main_app" def get_queryset(self, *args, **kwargs): players = player.objects.all() return players def get(self, request, *args, **kwargs): try: id = request.query_params["id"] if id != None: player_object = player.objects.get(id=id) serializer = playerSerializer(player_object) except: players = self.get_queryset() serializer = playerSerializer(players, many=True) return Response(serializer.data) def … -
Django - Comparing id of queryset with fetch object id
I am learning django with practicing. I have one object. It has id, name, lastname. Also, I have one queryset. It has same attributes id,name, lastname. All I want is comparing id's. I can compare ids if they both are equal but my problem is if they both are not equal django gives me error like matching query does not exist. because I use filter function. I want to do this operation if icformkeyinput.filter(id=v['Id']): if icformkeyinput.filter(id!=v['Id']): My problem is How can I use != operator? I want to do this because if there is unmatched id between icformkeyinput and v then add v to icformkeyinput. -
django many to many queryset
i have two models : 1----- class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) name = models.CharField(max_length=150) phone = models.CharField(max_length=50) picture = models.ImageField(blank=True, null=True , upload_to='profile' ) profession = models.ManyToManyField(Profession) 2----- class Profession(models.Model): profession = models.CharField(max_length=50) i want to display all the profession that i have and in the same time i want to display the number of accounts that they have this profession like this pic enter image description here -
Cannot connect django to postgres running inside docker container
My django app is not dockerized, but I run postgres inside docker container using docker-compose.yml script. After docker-compose up I can connect to db with dbeaver, but not with django app. Every time I'm getting an error: django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution File docker-compose.yml: version: "3.9" services: db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" - POSTGRES_USER="postgres" - POSTGRES_PASSWORD="postgres" - POSTGRES_DB="postgres" ports: - 5432:5432 volumes: postgres_data Django project file config/settings.py: ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env.str("DB_NAME"), 'USER': env.str("DB_USER"), 'PASSWORD': env.str("DB_PASS"), 'HOST': env.str("DB_HOST"), 'PORT': env.decimal("DB_PORT") } } -
Get data from template to views in Django
How do i get the data (from database) in template to a view that i have for another app? I am building a very simple ecommerce website and would like to save the order of the users and save those products' name and quantity in the table 'Orders'. Here is a snap of my code to make it more clear: Template code Actual page display My view -
i am trying to add choice for candidate. It is giving me error that cannot represent value enums meta instance
i am trying to add choice for candidate. It is giving me error that cannot represent value enums meta instance message Enum AccountsCandidateGenderChoices cannot represent value EnumMeta instance. Is there any way to store choice inside candidate model? class Candidate(models.Model): class Gender(models.TextChoices): MALE = "Male" FEMALE = "Female" gender = models.CharField(max_length=100,choices=Gender.choices,default=Gender.MALE) class CandidateGender(graphene.Enum): MALE = "Male" FEMALE = "Female" mutation{ createCandidate(input: {gender:FEMALE}){ Candidate{ id, gender } } } -
Web3py Interacting with smart contract
Hey I'm working on a project and want to know if I can use python/django to make a frontend dapp where people can mint a token while connected to metamask ? Like signing their account and interact with the smart contract ? I really don't get it why I need to use javascript in order to make a minting process. Can some ligten me so I can continue to focus on python/django to AUTH, INTERACT with the blockchain. -
Django Ajax Not Found "url"
i am trying to use ajax with django: $('.btnMyc').click(function() { $.ajax({ type: "GET", url: "/getpic", data: { username: document.getElementById("usernameid").value }, urls.py: urlpatterns = [ path('', views.vscomain, name="vscomain"), path('getpic',views.send_pic,name="getpic"), ] and there is a function names send_pic in views.py but when i type username and click it i get this error: Not Found: /getpic [21/Sep/2021 14:00:59] "GET /getpic?username=sfdgl HTTP/1.1" 404 2400 -
Error while loading static files in Django
Trying to load static files but it is showing following error. ERROR GET http://127.0.0.1:8000/static/css/user/style.css net::ERR_ABORTED 404 (Not Found) - home:25 GET http://127.0.0.1:8000/static/css/user/style.css 404 (Not Found) - home:25 GET http://127.0.0.1:8000/static/img/logo.png 404 (Not Found) - home:149 GET http://127.0.0.1:8000/static/img/logo.png 404 (Not Found) - home:1 Click here to see error image. CODE -ADMIN settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") 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 urlpatterns = [ path('admin/', admin.site.urls), path('', include('Welcome.urls')), path('auth/', include('Authentication.urls')), path('ad/', include('Ads.urls')), path('user/', include('UserDashboard.urls')), path('admin/', include('AdminDashboard.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) APPS template <link href="{% static 'css/user/style.css' %}" rel="stylesheet"> Dirs Structure Click here to Project Directory Structure Image CODE EXPLANATION Simply added static files in the root dir and tried to import them in template but css files are not loading But some media files are successfully loaded like this media <link rel="shortcut icon" type="image/jpg" href="{% static 'img/logo.png' %}" />. Also in dir structure, we can see img and css folder at same place in static folder and images from image folder are loaded but css from css folder does not. -
Using saved database settings to generate code (if-statements) [closed]
I currently have an app that generates financial documents based on user-set settings These settings look something like this: Trial Balance ☐ Use main accounts ☐ Include Opening Balances ☐ Print Null Values ☐ Print Account Number All these settings are boolean variables and can easily be checked with if UseMainAccount == True : However, this would obviously take quite a few if statements to complete and can become very tedious. Is there a way to shorten this process (I know in Delphi and some other codes there are "case" statements for this. But would a case statement be possible in Django/Python -
Token generated by django-restframework-simplejwt not valid
This was working just fine before I tried to add social authentication to the project, and now when I send the verification email with the token, the token verifier says that the token is not valid! class ResendVerifyEmail(APIView): serializer_class = RegisterSerialzer def post(self, request): data = request.data # email = data.get('email') email = data['email'] print(email) try: user = User.objects.get(email=email) # print('hello') if user.is_verified: return Response({'msg':'User is already verified','status':'status.HTTP_400_BAD_REQUEST'}) print (user.username) token = RefreshToken.for_user(user).access_token current_site= get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+ user.username + ' this is the resent link to verify your email \n' + absurl data = {'email_body':email_body,'to_email':user.email, 'email_subject':'Verify your email'} Util.send_email(data) return Response({'msg':'The verification email has been sent','status':'status.HTTP_201_CREATED'}, status=status.HTTP_201_CREATED) except User.DoesNotExist: return Response({'msg':'No such user, register first','status':'status.HTTP_400_BAD_REQUEST'}) class VerifyEmail(APIView): serializer_class = EmailVerificationSerializer def get(self, request): token = request.GET.get('token') try: payload = jwt.decode(token, settings.SECRET_KEY) # print('decoded') user = User.objects.filter(id=payload['user_id']).first() # print(user) if user.is_verified: return Response({'msg':'User already verified!'}, status=status.HTTP_400_BAD_REQUEST) else: user.is_verified = True # user.is_authenticated = True user.is_active = True # if not user.is_verified: user.save() return Response({'email':'successfuly activated','status':'status.HTTP_200_OK'}, status=status.HTTP_200_OK) # except jwt.ExpiredSignatureError as identifier: except jwt.ExpiredSignatureError: return Response({'error':'Activation Expired','status':'status.HTTP_400_BAD_REQUEST'}, status=status.HTTP_400_BAD_REQUEST) # except jwt.exceptions.DecodeError as identifier: except jwt.exceptions.DecodeError: return Response({'error':'invalid token','status':'status.HTTP_400_BAD_REQUEST'}, status=status.HTTP_400_BAD_REQUEST) also, I have added these … -
Regex Error Finding Details from a bank statement
I am working with Regex and currently I am trying to extract the Name, IFSC and Account No. from the PDF. I am using following code to extract the details. acc_name= " ", '\n'.join([re.sub(r'^[\d \t]+|[\d \t]+:$', '', line) for line in data.splitlines() if 'Mr. ' in line]) acc_no= " ", '\n'.join([re.sub(r'Account Number\s+:', '', line) for line in data.splitlines() if 'Account Number' in line]) acc_code = " ", '\n'.join([re.sub(r'IFSC Code\s+:', '', line) for line in data.splitlines() if 'IFSC Code' in line]) But the data which I am getting back is following: (' ', ' 50439602642') (' ', 'Mr. MOHD AZFAR ALAM LARI') (' ', ' ALLA0211993') I want to remove the commas, brackets and quotes. I am new with regex so any help would be appreciated. -
Upload an csv file then, store data in MCQs format in the model
I'm creating an quiz app in django.The model is like this, class Question(models.Model): questions = models.CharField(max_length=50, unique=True) choice1 = models.CharField(max_length=50, unique=True) choice2 = models.CharField(max_length=50, unique=True) choice3 = models.CharField(max_length=50, unique=True) choice4 = models.CharField(max_length=50, unique=True) correct_answer = models.CharField(max_length=50, unique=True) I want to upload an MCQ-contained file and the model automatically stores the MCQs according to entries. e.g, if the file contains 20 MCQs then all MCQs store in the model according to the pattern given above. -
Django: How to delete Media Files on Digitalocean Spaces/ Amazon S3 automatically when Model instance is deleted
I have the following model defined in my Django-App def directory_path(instance, filename): return 'attachments/{0}_{1}/{2}'.format(instance.date, instance.title, filename) class Note(models.Model): title = models.CharField(max_length=200) date = models.DateField(default=datetime.date.today) # File will be saved to MEDIA_ROOT/attachments attachment = models.FileField(upload_to=directory_path) def __str__(self): return self.title I successfully set up AWS S3/ Digitalocean Spaces to store the media file uploaded via the attachment field. However, when I delete an instance of the model, the file remains in my bucket. What do I have to do, in order to delete the file automatically in my s3 bucket, if the corresponding model intance is deleted? -
How can I change template of account activation Email of django
I created class based view to access uid and token . Here I create one web page which have one button of activate user. I am sending one uid and token to user email. I created class based view to get uid and token. I am sending email on user gmail account. where user get link for activate his account. Email looks like this : You're receiving this email because you need to finish activation process on 127.0.0.1:8000. Please go to the following page to activate account: http://127.0.0.1:8000/activate/Mg/ata7ek-01e823899301fe357286112596a25655 Thanks for using our site! The 127.0.0.1:8000 team .... But now I wish to change this content/template of email for activate account . How can I change this template in django Here is my djoser setting DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'user_profile.serializer.UserSerializer', 'user': 'user_profile.serializer.UserSerializer', } } How can I change it ? -
How to resolve missing dependencies in Docker Alpine
I have Django application that works just fine when I build my docker image using python:3.10.0rc2-buster or python:3.10.0rc2-slim-buster without any problem. In order to decrease the image size, I switched to python:3.10-rc-alpine, however, I am facing dozens of missing dependencies. I found this post very helpful Docker Alpine Linux python (missing) It allowed me to resolve some of the missing dependencies. Appreciate your support to guide me on what can I do to resolve this ? These are the missing dependencies errors I am receiving: #6 9.141 ERROR: unable to select packages: #6 9.173 libcairo2 (no such package): #6 9.173 required by: world[libcairo2] #6 9.173 libgdk-pixbuf2.0-0 (no such package): #6 9.173 required by: world[libgdk-pixbuf2.0-0] #6 9.173 libldap2-dev (no such package): #6 9.173 required by: world[libldap2-dev] #6 9.173 libpango-1.0-0 (no such package): #6 9.173 required by: world[libpango-1.0-0] #6 9.173 libpangocairo-1.0-0 (no such package): #6 9.173 required by: world[libpangocairo-1.0-0] #6 9.173 libsasl2-dev (no such package): #6 9.173 required by: world[libsasl2-dev] #6 9.173 libsnmp-dev (no such package): #6 9.173 required by: world[libsnmp-dev] #6 9.173 libssl-dev (no such package): #6 9.173 required by: world[libssl-dev] #6 9.173 pdftk (no such package): #6 9.173 required by: world[pdftk] #6 9.173 python-dev (no such package): #6 9.173 required … -
How do i query all the fields in a django Many to Many
Trying to loop over a many to many relationship where I want all the fields. My Models: class Recipe(models.Model): title = models.CharField(max_length=200) slug = AutoSlugField(populate_from="title") category = models.ForeignKey(RecipeTopic, on_delete=models.CASCADE) image = models.ImageField() description = models.TextField() ingredients = models.ManyToManyField(Ingredient, through="IngredientList") directions = models.TextField() servings = models.IntegerField() time = models.IntegerField() cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE) def __str__(self): return self.title class IngredientList(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) Recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) amount = models.FloatField(default=1) unit = models.ForeignKey(Units, on_delete=models.CASCADE) My Views: from .models import Recipe def home(request): recipe = Recipe.objects.all() context = { "title": "Home Page", "recipe": recipe } return render(request, "home.html", context) and my template: {%for r in recipe %} <h2>{{r.title}}</h2> <h4>Ingredients:</h4> {%for i in r.ingredients.all %} <p>---{{i.amount}}{{i.unit}} {{i.ingredient}}</p> {%endfor%} {%endfor%} Want to showcase the ingredients, their amount, and the units that goes along with them. Except that I am only getting the "ingredient" title -
setting new file storage path in django model
I am trying to change the file storage path in model instance via view.py (instance.model.path = new_path) and I get can't set attribute. Not sure why as I can change the file name. view.py def SaveFile(request): if request.method == 'POST': model, created = MyModel.objects.get_or_create(record_id=request.POST['record_id']) file=request.FILES['report'] model.report = file.name call_id = model.record.call_ID date = datetime.now() date = str(date.strftime("%d.%m.%Y-%H:%M:%S")) file_storage = FileSystemStorage(location=os.path.join(MEDIA_ROOT, 'Reports', call_id)) file_name = file_storage.save(str(date + '-' + file.name),file) model.report.path = file_storage.location model.report = file_name model.save() return JsonResponse(file_name, safe=False) -
Errors don't show in Templates after custom validation
I'm working on a form where few field inputs depend on each other. I implemented custom validation and added error messages to it but, although custom validation works, error messages don't get shown in templates. form.py class NewCalculationForm(forms.ModelForm): def clean(self): cleaned_data = super(NewCalculationForm, self).clean() if self.cleaned_data.get('Tsrcin') <= self.cleaned_data.get('Tsrcout'): raise forms.ValidationError({"Tsrcout": "Source outlet temperature has to be lower than inlet temperature."}) # msg = "Source outlet temperature has to be lower than inlet temperature." # self.errors["Tsrcout"] = self.error_class([msg]) if self.cleaned_data.get('Tsinkin') >= self.cleaned_data.get('Tsinkout'): raise forms.ValidationError({"Tsinkout": "Sink outlet temperature has to be higher than inlet temperature."}) # msg = "Sink outlet temperature has to be higher than inlet temperature." # self.errors["Tsinkout"] = self.error_class([msg]) return cleaned_data class Meta: model = Calculation fields = ['Tsrcin', 'Tsrcout', 'Qsrc','Tsinkin','Tsinkout',] view.py def index(request): if request.method == 'POST': form = NewCalculationForm(request.POST or None) if form.is_valid(): Tsrcin = form.cleaned_data.get("Tsrcin") Tsrcout = form.cleaned_data.get("Tsrcout") Qsrc = form.cleaned_data.get("Qsrc") Tsinkin = form.cleaned_data.get("Tsinkin") Tsinkout = form.cleaned_data.get("Tsinkout") [Pnet, Pel, thermaleff, savepath] = cycle_simulation(Tsrcin, Tsrcout, Qsrc, Tsinkin, Tsinkout) file1 = DjangoFile(open(os.path.join(savepath, "TSDiagrammORCCycle.png"), mode='rb'),name='PNG') file2 = DjangoFile(open(os.path.join(savepath, "TQDiagrammORCCycle.png"), mode='rb'),name='PNG') instance = Calculation.objects.create(userid = request.user,Tsrcin = Tsrcin, Tsrcout = Tsrcout,\ Qsrc = Qsrc, Tsinkin = Tsinkin, Tsinkout = Tsinkout, Pel = Pel,\ time_calculated = datetime.today(), result = Pnet,\ thermaleff … -
How to perform a __all_in query with Django?
I have three models class Pizza(models.Model): toppings = models.ManyToManyField(Topping) class Topping(models.Model): name = models.CharField(max_length=50) class Order(models.Model): must_have_toppings = models.ManyToManyField(Topping) I want to find all Orders that match a certain Pizza. For this, I would like to do something like orders = Order.objects.filter(must_have_toppings__all_in=my_pizza.toppings) What I tried: orders = Order.objects.filter(must_have_toppings__in=my_pizza.toppings) doesn't work, because Orders with just one of the Pizza's toppings in their must_have will be returned. And: orders = Orders.objects for topping in my_pizza.toppings.all(): orders = orders.filter(must_have_toppings=topping) doesn't work, because it will return orders that have all the toppings from the pizza, even if some of the must_have_toppings are missing. For example, a Pizza with Tomatoes and Mushrooms will return an Order that needs Tomato, Pepper, and Mushroom. How can I look for Orders where the must_have_toppings are ALL in the Pizza object? (I am using MySql)