Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get the right data at the right place
I have a Json file and was able to extract some values from it and sum them up. I want to be able to put the result to the right key but can't figure it out. Below is my code: from builtins import print import json import jmespath from collections import Counter const = ['constituency A','constituency B','constituency C'] region = ['region A','region B','reigon C'] poll = ['POLLING STATION A','POLLING STATION B','POLLING STATION C','POLLING STATION Z','POLLING STATION F'] fake = {'transaction':[{'region A':{'constituency A':{ 'POLLING STATION A':{'PARTY A':10,'PARTY B':20,'PARTY C':30,'PARTY D':40}, 'POLLING STATION Z':{'PARTY A':50,'PARTY B':60,'PARTY C':70,'PARTY D':80}, 'POLLING STATION B':{'PARTY A':90,'PARTY B':100,'PARTY C':110,'PARTY D':120}, 'POLLING STATION F':{'PARTY A':190,'PARTY B':1100,'PARTY C':1110,'PARTY D':1120},}, }}]} a = json.dumps((fake)) p = json.loads(a) j = jmespath.search('transaction[*]',p) ham = [] man = set() for new_d in j: for k,v in new_d.items(): for i_k,i_v in v.items(): for w,c in i_v.items(): if w in poll and i_k in const and k in region: ham.append(c) up = len(ham) i= 0 a1=Counter() while i < up: a1 += Counter(ham[i]) i+=1 print(a1) So this is what I wanted to do, the result which is a1 will be placed a dictionary this way =>[ {'region A':{'constituency A':{'PARTY D': 1360, 'PARTY C': 1320, 'PARTY … -
Multiple buttons for differents actions in the same Django form
I have a Django form where I need to include buttons to make certains actions, like fill various fields, I'm doing this with javascript scripts. The problem comes when I click that button, the form validates, like if I'm submiting the form. Are there any ways to prevent this? -
Selenium gives Server Error 500 after click (Django, pytest)
I have a Django app that I want to test via pytest and Selenium. The routine I'm trying to go through is to let Selenium log in, then go to the menu, choose one of the options. This redirects to a new page, which is found fine. There, I let selenium enter data and click a button to start a submission. This, too, works, and redirects to a third page. On this third "your submission was created successfully" page, there is a link displayed that the user can click to collect the results of their submission (this page . This link is displayed correctly, the href URL is fine. But when I let Selenium click on it, I suddenly get a Server Error 500: <html lang="en"><head> <title>Server Error (500)</title> </head> <body> <h1>Server Error (500)</h1><p></p> </body></html> When I do the exact same thing manually, it works fine. Here's my test code (slightly simplified): @pytest.fixture(scope="class") def chrome_driver_init(request): options = webdriver.ChromeOptions() options.headless = True options.binary_location = CHROME_BIN_PATH driver = webdriver.Chrome(service=CHROME_SERVICE, options=options) request.cls.driver = driver yield driver.quit() @pytest.mark.django_db @pytest.mark.usefixtures("chrome_driver_init") class SubmissionTest(LiveServerTestCase): def test_adding_submission(self): self.driver.get(self.live_server_url) username = TEST_USER pwd = TEST_USER_PWD User = get_user_model() user = User.objects.create_user(username=username, password=pwd) user.save() # click 'Login': self.driver.find_element(By.LINK_TEXT, "Login").click() # … -
URL disapears in createview when going from get to POST
I have a question regarding an issue where I'm out of options and best describes with what is seen in the log. Some background : /order/createnumber/ is just a CBV createView that will show a create form. the url looks like url(r"^createnumber/$", views.OrderCreate.as_view(), name="order-create"), The Class looks like class OrderCreate(CreateView): """ CBV for creating order""" model = Order form_class = OrderFormCreate The above is working for a GET request put fails for a POST request, where both URLs are the same. web_1 |- - [17/Dec/2021:13:08:04 +0100] "GET /order/createnumber/ HTTP/1.0" 200 10209 "http://mytestsite.local/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0" web_1 | Not Found: /order/createnumber/ It happens in my QA environment only, I'm using gunicorn. In development it is working as expected, there I use the django runserver Any ideas on this ? -
Authentication and authorization django app(backend) using keycloak
I had a problem. I had a react app that authenticate, using KeyCloak. From KeyCloak-server i recieve some credentials, like tokens, uuid of user and etc. Then, i am trying to access api on Django Backend, but request.user is Anonymous User. So, how can I can authenticate Django DRF? Should I send credentials from frontend to backend and create User model on backend or I don't need this? -
how to use onChange with dynamic form - jquery
I'm trying to use onChange in order to return some data related to the foreign key in the drop down - select field, but it only works for the first form, after that i've to select the item twice, then returns back the data! i'm using modelformset_factory, views.py @login_required def return_back_imei_oddinfo(request): query = request.GET for item in query: if item.startswith("imei-") and item.endswith("-item"): item_id = query.get(item) break selling_price= Imei.objects.get(id=item_id).mobile.selling_price, mobile=Imei.objects.get(id=item_id).mobile.mobile.model, data = { 'price' : selling_price, 'mobile':mobile, } return JsonResponse(data) and here is my forms.py class ImeiModelChoiceField(ModelChoiceField): def label_from_instance(self,obj): return str(obj.imei) class ImeiInvoiceForm(forms.ModelForm): item = ImeiModelChoiceField(queryset=Imei.objects.filter(status=True),widget=forms.Select(attrs={'onchange':'imeiInfo();'})) class Meta: model = ImeiInvoice fields = ['item','price','cash','discount'] error_messages = { 'item':{ 'required':'تکایە ناتوانی بە بەتاڵی بەجێی بهێڵیت' }, 'price':{ 'required':'تکایە ناتوانی بە بەتاڵی بەجێی بهێڵیت' }, 'cash':{ 'required':'تکایە ناتوانی بە بەتاڵی بەجێی بهێڵیت' }, } widgets = { 'price':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}), 'cash':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}), 'discount':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}), } ItemCustomerInvoice = modelformset_factory(can_delete=True,model=ImeiInvoice,form=ImeiInvoiceForm) and also here is my templates function imeiInfo () { $('select').change(function() { let elm = $(this); data = {}; data[elm.attr("name")] = elm.val(); $.ajax({ url:'/ajax/return_back_imei_oddinfo/', data:data, success:function(data){ console.log(data.price) if (data.price){ elm.closest("div.child_imeiforms_row").find("input.nrx").val(data.price); } else{ alert('not found') } if (data.mobile){ elm.closest("div.child_imeiforms_row").find("input.mobile-type").val(data.mobile); } } }) }) } imeiInfo(); <form action="" method="POST" id="create-permcustomer-invoice">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <i class="fas fa-file-signature"></i> … -
Communication between two Django projects
I have two python-django projects which have different databases. What is the best way two communicate between these two projects? By communication I mean reading data from each other, send data to be written into the other project's database, etc. -
static file css not loading in django
I have tried everything i know to fix this all static files are working perfectly other than css views.py from django.http.response import HttpResponse from django.shortcuts import render def index(response): return render(response , "main/index.html") html head {% extends 'main/base.html' %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href= "{%static "main/css/index.css" %}"> <title> Home Page </title> </head> Please note that i am using bootstrap in base file if that affects anything settings.py STATIC_URL = '/static/' STATIC_ROOT = "/Users/aryankaushik/Desktop/visual studio code /django/assets" STATICFILES_DIRS = [ BASE_DIR / "static", ] I am sure the folders paths are correct as images are rendering correctly.. Thank you in advance -
How to get rid of <QuerySet[]> tag when getting the data on my template from the database? Django
I'm having a bad time figuring this out through searching different stackoverflow question but I'm using a function based view to make my day simplier. But when i'm retrieving this single data from a database and showing only one record using slice. It throws beside it a tag which commonly see when we test print in our terminals. But how exactly to get rid of this? tutorials = Tutorial.objects.values_list('id', flat=True) courses = Course.objects.all() tutorial_title = Tutorial.objects.filter(id__in=tutorials).values('title').values_list('title', flat=True) context = {'tutorial': tutorials,'courses': courses, 'tutorial_title': tutorial_title} Here's my code snippet, where when i call {{ tutorial_title | slice:'1'}}. It should only call one latest record, which works flawlessly but there is a <QuerySet tag beside the shown data. -
Error checking a consistent migration hist ory performed for database connection 'default':
I got an error when i want to makemigrations while connecting to mysql database on django and i hope anyone can help me to solve the problem. My code is given below: DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'django.db.backends.mysql', 'NAME': 'leave_management_sys', 'USER': 'leave_management_sy', 'PASSWORD': 'leave_management_pass', 'HOST': '127.0.0.1', 'PORT': '3306' } -
DRF TypeError: create() got an unexpected keyword argument
So I am trying to save model with serializer, but getting TypeError on save method. It seems the problem is not in data, or serializer, so I don't know how to solve it. serializers.py: class DistributorSeializer(serializers.ModelSerializer): """ Fields: exclude = ['company']. Overrides: `create()`, `to_representation()`. """ class Meta: model = Distributor exclude = ['company'] def create(self, validated_data): request = self.context.get('request') if request and hasattr(request, 'user'): worker: Type[Worker] = Worker.objects.get(user=request.user) validated_data['company'] = worker.company print(validated_data) print(self) return super().create(**validated_data) return self.Meta.model.objects.create(**validated_data) So when I am trying to call create method throw super class I am getting error, but when to do the same but throw Meta class - it works. {'name': 'Name', 'address': 'Address', 'phone': '+48999999999', 'company': <Company: Smotors>} DistributorSeializer(context={'request': <rest_framework.request.Request: POST '/companys/distributor/'>, 'format': None, 'view': <companys.views.DistributorsViewSet object>}, data={'name': 'Name', 'address': 'Address', 'phone': '+48999999999'}): id = IntegerField(label='ID', read_only=False, required=False) name = CharField(max_length=50) address = CharField(allow_blank=True, allow_null=True, max_length=255, required=False, validators=[<UniqueValidator(queryset=Distributor.objects.all())>]) phone = CharField(allow_blank=True, allow_null=True, max_length=16, required=False, validators=[<django.core.validators.RegexValidator object>]) comment = CharField(allow_blank=True, allow_null=True, max_length=800, required=False) email = EmailField(allow_blank=True, allow_null=True, max_length=254, required=False) count = BooleanField(required=False) Internal Server Error: /companys/distributor/ Traceback (most recent call last): File "C:\Users\march\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\march\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\march\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line … -
pagination in django not pagination the posts by 6 posts per page
after writing the view for my pagination in django, the button works fine, meaning that they load new pagesz but the problem is that all the posts still remains in all the new pages and that is not what's expected. views.py def ElementLists(request): vectors = Vectors.objects.filter(status="published").order_by("?") paginator = Paginator(vectors, 6) page_number = request.GET.get('page') vector_paginator = paginator.get_page(page_number) elementlist.html <li class="page-item"> {% if vector_paginator.has_previous %} <a class="page-link" href="?page={{vector_paginator.previous_page_number}}" arialabel="Previous"> <span class="ti-arrow-left">Previous</span> <span class="sr-only">Previous</span> </a> {% endif %} </li> <li class="page-item"> {% if vector_paginator.has_next %} <a class="page-link" href="?page={{vector_paginator.next_page_number}}" aria-label="Next"> <span class="ti-arrow-right">Load More</span> <span class="sr-only">Next</span> </a> {% endif %} </li> -
Dockerizing a django postgres application getting password authentication failed for user "root" Role "root" does not exist
Hi i am dockerizing my django postgres application ,whereas i am specifying user as admin but still i am getting connected to postgres db as root and getting errors. DockerFile FROM ubuntu:20.04 RUN apt update && apt install python3-pip python3-dev -y ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 WORKDIR /code COPY requirements.txt /code/ RUN pip3 install --upgrade pip RUN apt-get install libffi-dev RUN pip3 install cffi RUN pip3 install -r requirements.txt COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /code/entrypoint.sh RUN chmod +x /code/entrypoint.sh COPY . /code RUN python3 manage.py collectstatic --no-input ENTRYPOINT ["/code/entrypoint.sh"] entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi exec "$@" docker-compose.yml version: "3.3" services: db_new: image: postgres:12.0-alpine container_name: db_new ports: - 5432:5432 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=admin - POSTGRES_PASSWORD=admin - POSTGRES_DB=docker2 redis: image: "redis:alpine" web: restart: always container_name: web build: context: . dockerfile: Dockerfile command: bash -c "/usr/local/bin/daphne -b 0.0.0.0 -p 8000 setup.asgi:application" volumes: - static_volume:/code/static/ - media_volume:/code/media/ ports: - "8000:8000" env_file: - ./.env depends_on: - db_new - redis celery: build: . command: /usr/local/bin/celery -A setup worker -l info depends_on: - db_new - redis celery-beat: build: . command: … -
Django: widget-tweaks for Dropdown-form - attr not working
I'm currently trying to style my Dropdown Forms which I've been creating with widget tweaks. Therefore, I currently got one style-class for every dropdown which is obviously not really efficient: CSS .processor_dropdown { position: absolute; width: 178px; height: 24px; left: 467px; top: 518px; overflow: visible; } .graphicscard_dropdown { position: absolute; width: 178px; height: 24px; left: 467px; top: 568px; overflow: visible; } HTML <label style="top: 500px;" for="" id="label_config_1">Mein Prozessor </label> {{ form.processor|add_class:"processor_dropdown"}} <label style="top: 550px; for="" id="label_config_1">Meine Grafikkarte</label> {{ form.graphicscard|add_class:"graphicscard_dropdown" }} But since I need to define the position "left" and "top" differently, I firstly created it just like this. But now I want to go more "common" way and create one class for all dropdowns and define the position attributes locally. Therefore the widget tweaks documentation has a pretty clear way to do so - with the "attr"-statement: HTML {% load widget_tweaks %} <label style="top: 500px;" for="" id="label_config_1">Mein Prozessor </label> {{ form.processor|add_class:"processor_dropdown"|attr:"left:467px"|attr:"top:518px"}} But it's not working somehow and I have no idea why. Is the "add_class" - statement not linkable with the attr - statement? I hope you can help me out here. Thank you in Advance! -
Django Form - Select dropdown
How do I Output both "id_no" and "name" [id_no - name] combined in dropdown select form. Can it be done directly to the form using {{form}} only. Model: class Employee(models.Model): id_no = models.CharField(unique = True,max_length=6) name = models.CharField(max_length=100) Form: class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = __all__ -
Issues in validating Image file passed through post request in django
I want to validate 2 things in my django project: Is the Image passed is valid Image or not (having proper extension, nonempty etc.) I have a function isCovering70p which returns bool, depending on whether the object in the image is covering 70% area or not. Now I have to check this also before saving the data to the db. If the image posted by user fails any of these 2, 400 response code should be sent. This is my models.py: def user_image_dir_path(instance, filename): return f"uploads/users/{instance.email}/{filename}" class UserDetail(models.Model): email = models.EmailField(max_length=80) registration_time = models.DateTimeField(auto_now_add=True) image_path = models.ImageField(upload_to=user_image_dir_path) image_meta = models.CharField(max_length=100) @property def filename(self): return os.path.basename(self.file.name) This is my serializers.py: class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = UserDetail fields = ['full_name', 'email', 'org_id', 'image_path'] From the DRF docs, I understood that my #1 validation condition will be taken care by DRF/django. But, how and where should I take care of #2 condition? Also, I want to update my image_meta field based on isCovering70p. How and where should I put the logic for that update? -
Changing the video format in Django
What's the best way to change video format from any to mp4 in Django? models.py class Post(models.Model): video = models.FileField(validators=[FileExtensionValidator(allowed_extensions=['mp4', 'mov', 'wmv', 'avi', 'flv', 'webM', 'mkv'])]) views.py if request.method == 'POST' in request.POST: form = NewVideo(request.POST, request.FILES) if form.is_valid(): obj = form.save() else: form = NewVideo() All the answers on the forum that I found are from many years ago, either require Celera or don't work. Is there a library, an option in Python that will change eg MOV to MP4? The preferred place of use is models.py or views.py -
How to make complex query to Db in Django
I would like to get data from my SQLite DB. My models: class Group(models.Model): groupName = models.CharField(max_length=100) description = models.CharField(max_length=255) inviteKey = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) deletedAt = models.DateTimeField(auto_now=True) class Members(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) groupId = models.ForeignKey(Group, on_delete=models.CASCADE) isAdmin = models.BooleanField(default=False) And also build in Users. I need to display all Groups where currentUser is member. For that i need to build query. To avoid many-to-many relationship i created "Members" table to manage Group's members. What i've tried def getGroups(request): currentUserId = request.user.id # 1. Get all groups where currentUser is member. groups = Members.objects.filter(userId_id = currentUser.id) # this always return 3 object which is wrong. # by that filter doesn't work # other steps .. return render(request, 'group/allGroups.html') My members table: -
How to implement simple notifications in drf?
Normally in django with templates I implement basic notifications like this. For example. class Article(models.Model): name = models.CharField() owner = models.ForeignKey(User) class Comment(): article = models.ForeignKey(Article) txt = models.CharField() user = models.ForeginKey() datetime = models.DateTimeField(auto_now_add=True) class ArticleNotification(): article = models.ForeignKey(Article) msg = models.CharField() is_seen = models.BooleanField(default=False) datetime = models.DateTimeField(auto_now_add=True) If someone commented on article the owner will see notifications. @transaction.atomic def post_comment(request, article_id): comment = Comment.objects.create(article_id=article_id, txt="Nice Article", user=request.user) ArticleNotification.objects.create(article_id=article_id, msg=f"User {request.user} commented on your post") Now to show the notifications I normally make a context processor: # context_processor: def notifcations(request): notifs = Notfication.objects.filter(article__owner=request.user).order_by("-datetime") return {"notifs":notifs} In this way I can normally implement basic notification system with refresh. Now in (drf + react) what will be the preferred way for this type of task. Instead of context processor should I have to make an get api to list notifications And call this api on every request from react frontend ? -
Can I build MindMaps in Python?
I am working on my web app. I want to be able to create mind maps on my website. Can I do it in Django with python or do I need to use other languages to build this function of creating Mind Maps? -
Pass JSON data to Shopify using Add to cart button
I am new to Shopify so please pardon my ignorance, if I ask a stupid question. So far I have setup an external Django website, which let's user enter their details. When the user press "Add to cart" button, I want all of these details to be passed onto Shopify and product added to Cart. I have gone through some posts, and I understand I can do "Add to cart" quite easily just by using webstore.shopify.com/cart/product_id:quantity But I have not been able to figure how to pass the attributes. I need to pass 12 different attributes. If it's possible to pass JSON file, with "Add to Cart" button what would be great. Research done so far: Shopify - Loading data from an External REST API in a Liquid template Shopify public JSON URLs https://shopify.dev/api/ajax/reference/cart#post-cart-add-js If this user completes the transaction, I want all of these details returned to my Django website. Could anyone please guide me how I can do this. Thank you in advance, Kind regards, Shashank -
how to deploy django channels app on azure?
I want to deploy django channels app on azure but I did not found any tutorial. I tried to deploy it but server is not accepting web socket connections. -
(Django aggregate) how to get average spent time and the dates of them
my model class UserRetention(models.Model): user = models.ForeignKey('users.User', on_delete=models.PROTECT,null=True, blank=True,related_name='user_retention') in_date = models.DateTimeField(auto_now_add=True) out_date = models.DateTimeField(blank=True, null=True) @property def duration(self): try: return self.out_date - self.in_date except: pass class Meta: get_latest_by = 'in_date' my goal I need to do something like this UserRetention.objects.all().aggregate(..... to get a dictionary object with avg_weekly_duration calculated by number of hours? [ { "avg_weekly_duration": "3", }, { "avg_weekly_duration": "10", }, { "avg_weekly_duration": "8", }, { "avg_weekly_duration": "15", } ] -
DRF SOCIAL OAUTH 2
The problem is to get another access token from refresh token. I can't find the url to send refresh token to get fresh access token. -
Récupérer les valeurs d'un champs foreign key dans createview
Bonjour, je découvre Django et je bloque sur le problème suivant (en simplifieé je ne mets pas tous les champs) Models.py class Produit(models.Model): nom = models.CharField(max_length=255, unique=True) type = models.CharField(max_length=255) class ProduitBordereau(models.Model): nom = models.Charfields(max_length=255) type = models.CharField(max_length=255) prix_achat = models.DecimalField(max_digits=8, decimal_places=2, default=0) forms.py class ProduitBordereauNewForm(BSModalModelForm): produit = forms.ModelChoiceField(queryset=Produit.objects.all(), widget=forms.Select(attrs={'class': 'form-select'})) class Meta: model = ProduitBordereau fields = {'prix_achat '} widgets = { 'prix_achat': forms.NumberInput(attrs={'class': 'form-control'}), } views.py #----------PRODUIT BORDEREAU---------- class ProduitBordereauCreateView(BSModalCreateView): form_class = ProduitBordereauNewForm template_name = 'produitbordereau/produitbordereau_nouveau.html' success_message = "Success: le produit a été ajouté." success_url = reverse_lazy('bordereau_list') def form_valid(self, form): form.instance.nom = self.request.produit.nom form.instance.type = self.request.produit.type return super(ProduitBordereauCreateView, self).form_valid(form) Comment puis-je lors de la validation du formulaire donner à mes champs 'nom' et 'type' de mon modèle produitbordereau les valeurs des champs 'nom' et 'type' de mon modèle produit?