Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate a block of HTML code when submitting a form via Django
I would be grateful if someone explained to me how I could create a block of HTML Code when submitting a form with Django. For instance, if I want to upload an image, how could I automatically generate a HTML code block that puts the image inside a div with background and etc. Thanks! I searched a bit through documentation, and on the internet and couldn't find much about it. -
Psycopg2 error when i run my django project inside a container on windows
I have my django project in my pc (WIndows 11) and i want to put my project in a container, but when i am trying to run 'docker-compose build' in the terminal, i have always the same error. This is my Dockerfile FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN apt-get update && apt-get install -y libpq-dev RUN pip install --upgrade pip && pip install -r requirements.txt COPY . /code/ i am on that problem since monday. I have a 'pg-config' in my path and my django project works fine in my computer. I tried to use only 'psycopg2-binary' but i get a error that the 'psycopg2' package is not installed. I am on windows ! -
Django models: you need to display the menu and submenus
Can you please help. That's the question. I have a menu, the name of the menu is 'catr' and there is a submenu 'subcat' , I want to make the entire menu list output, and if the menu id matches the menu, then a subcategory is output, but I don't understand how to implement it.Help please.Sorry if I didn't explain it clearly, I hope you will understand, thank you in advance Here's what I tried to do enter image description here enter image description here -
Integrate pystray library with django in macOS
from documentation: run_detached(setup=None) Prepares for running the loop handling events detached. This allows integrating pystray with other libraries requiring a mainloop. Call this method before entering the mainloop of the other library. Depending on the backend used, calling this method may require special preparations: macOS Pass an instance of NSApplication retrieved from the library with which you are integrating as the argument darwin_nsapplication. This will allow this library to integrate with the main loop. source I do not understand this statement. How can I pass NSApplication instance to Icon class as argument. Where do I get this instance?. I am using macOS m1 -
How to properly run tests based on the APITestCase in Django?
When I use the python manage.py test command, in the console I see such a result: Ran 0 tests in 0.000s. How to run these UNIT tests? Also how to know the correctness of URLs which I use in the reverse function? project/urls.py: urlpatterns = [ path('', include('client.urls')), ] client/urls.py: urlpatterns = [ path('clients', ClientView.as_view()), path('clients/<int:pk>', ClientView.as_view()), ] client/tests.py: from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from client.models import Client class ClientTestCase(APITestCase): def setUp(self): self.data = { "first_name": "Jimmy", "last_name": "Smith", "email": "jimmysmith@gmail.com" } self.response = self.client.post( reverse('client:client-list'), self.data, format="json" ) def create_client(self): self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) self.assertEqual(Client.objects.count(), 1) self.assertEqual(Client.objects.get().first_name, 'Jimmy') def get_clients(self): response = self.client.get(reverse('client:client-list')) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(Client.objects.count(), 1) def get_client(self): client = Client.objects.get() response = self.client.get( reverse('client:client-detail', kwargs={'pk': client.id}), format="json" ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, client) def update_client(self): client = Client.objects.get() new_data = { "first_name": "Bob", "last_name": "Marley", "email": "bobmarley@gmail.com" } response = self.client.put( reverse('client:client-detail', kwargs={'pk': client.id}), data=new_data, format="json" ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(Client.objects.get().first_name, 'Bob') def delete_client(self): client = Client.objects.get() response = self.client.delete( reverse('client:client-detail', kwargs={'pk': client.id}), format="json" ) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(Client.objects.count(), 0) -
Cannot save a modelform using Django Crispy Forms
I cannot save my form because the payload is not formatted correctly.. I'm using HTMX for rendering the form in a modal here's the code: forms.py class RecipeForm(forms.ModelForm): title = forms.CharField( label="Titolo", ) method = forms.CharField( widget=forms.Textarea(), label="Procedimento", ) tags = CustomTagsMultipleChoice( queryset=Tag.objects.all(), widget=forms.CheckboxSelectMultiple, label="Tag", ) hero_image = forms.ImageField( label="Immagine", ) class Meta: model = Recipe fields = ["title", "method", "tags", "hero_image"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs = { "hx-post": reverse_lazy("recipes:recipe_create"), "hx-target": "#dialog", } self.fields["tags"].required = False self.fields["method"].required = False self.fields["hero_image"].required = False self.fields["tags"].label = False self.helper.layout = Layout( FloatingField("title"), FloatingField("method", css_class="fl-textarea"), "hero_image", InlineCheckboxes("tags"), Div( Submit("submit", "Salva"), Submit("button", "Cancella", css_class="btn btn-danger", data_bs_dismiss="modal"), css_class="text-end", ), ) views.py @login_required def recipe_create(request): if request.method == "POST": form = RecipeForm(request.POST,request.FILES) if form.is_valid(): form.save() return HttpResponse(status=204, headers={"HX-Trigger": "recipeSaved"}) form = RecipeForm(request.POST,request.FILES) context = {"recipe_form": form} return render(request, "recipes/partials/_recipe_create.html", context) form = RecipeForm() context = {"recipe_form": form} return render(request, "recipes/partials/_recipe_create.html", context) _recipe_create.html {% load crispy_forms_tags %} <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Aggiungi una ricetta</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button> </div> <div class="modal-body"> {% crispy recipe_form %} </div> </div> if I print request.POST I get this badly formatted payload <QueryDict: {'------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name': ['"submit"\r\n\r\nSalva\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="csrfmiddlewaretoken"\r\n\r\n0DWNbShUV0r8mFSPUNQaSQapC38FQFrMeOtmqFY64H4x3ReOuG7suKqUip7sSpqv\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="title"\r\n\r\ntest\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="method"\r\n\r\n\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g--\r\n']}> the form … -
Why Nginx is Serving my django app in port 8000 instead of 80?
i have created a app using django https://github.com/pyalz/video_app . I run this application now using django compose build django compose up . When i open http://0.0.0.0:8000 its coming with static files. when i open http://0.0.0.0:80 its not showing me static files **Docker compose ** version: '3.7' services: django_gunicorn: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - django_gunicorn volumes: static: Docker File FROM python:3.10.0-alpine RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./video_app /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] Entry.sh #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input DJANGO_SUPERUSER_PASSWORD=$SUPER_USER_PASSWORD python manage.py createsuperuser --username $SUPER_USER_NAME --email $SUPER_USER_EMAIL --noinput gunicorn video_app.wsgi:application --bind 0.0.0.0:8000 NGINX Docker file FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf Default.conf upstream django { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { alias /static/; } } enter image description here enter image description here Could you please help me resolve this issue -
Django How add math result from form in Model.objects.create
I'm trying to divide one value by another from the form and write the result. But it doesn't work def add_project(request): form_address = AddressForm(request.POST or None) form_project = ProjectForm(request.POST or None) form_detail = ProjectDetailForm(request.POST or None) if request.method == 'POST': if form_address.is_valid() and form_project.is_valid() and form_detail.is_valid(): address_clean = form_address.cleaned_data project_clean = form_project.cleaned_data detail_clean = form_detail .cleaned_data a = Address.objects.update_or_create(**address_clean) p = Project.objects.create( address = a[0], manager = request.user, file = project_clean['file'], sq = project_clean['sq'], rent_tax = project_clean['rent_tax'] ) sq_price = project_clean['rent_tax'] / project_clean['sq'] ProjectDetail.objects.create( project = p, sq_price = sq_price, **detail_clean ) return redirect("crm:homepage") context = {'form_address':form_address, 'form_project':form_project, 'form_detail':form_detail,} return render(request, 'crm/add_project.html', context) I try sq_price = project_clean['rent_tax'] / project_clean['sq'] The print command outputs a number. But Django says it is an error: create_method..manager_method() got multiple values for keyword argument 'sq_price' Traceback project_clean { 'file': 'https://aaa.com/zzz.zip', 'rent_tax': 1548, 'sq': Decimal('325')} -
Django Social account is redirected to gitlab.com instead of gitlab.local
Hello I have installed gitlab locally on my own server. I am trying to make django settings with django social app with the steps specified in the readthedocs readthedocs link to enter through readthedocs gitlab accounts, but for some reason my server connects to gitlab.com when I say connect with gitlab via readthedocs instead of https://gitlab.local. I need to redirect it to my server. How do I do this, the django docs say the following steps but I have no idea how and where to change it. https://django-allauth.readthedocs.io/en/latest/providers.html#gitlab GitLab The GitLab provider works by default with https://gitlab.com. It allows you to connect to your private GitLab server and use GitLab as an OAuth2 authentication provider as described in GitLab docs at http://doc.gitlab.com/ce/integration/oauth_provider.html The following GitLab settings are available, if unset https://gitlab.com will be used, with a read_user scope. GITLAB_URL:Override endpoint to request an authorization and access token. For your private GitLab server you use: https://your.gitlab.server.tldSCOPE:The read_user scope is required for the login procedure, and is the default. If more access is required, the scope should be set here. which file do I need to modify to make the following setting or what is the way to do it? Example: SOCIALACCOUNT_PROVIDERS … -
Conditional Aggregation of Foreign Key fields
I would like to get the count of foreign key objects with django, the foreign key itself will change conditionally. So, something like the example below. Game.objects.annotate( filled=models.Case( models.When( GreaterThan( models.F("size_max"), ( models.Count( models.Case( models.When( participant_type=1, then="players" ), models.When( participant_type=2, then="teams", ), ), ), ), ), then=1, ), default=0, ) ) What I'd like to achieve is this: players and teams are reverse foreign keys to Game. I want to check whether the size_max field of Game exceeds the count of players or teams depending on the participant_type. How would I go about achieving this? Any help would be appreciated. The above query results in an error - it introduces a GROUP BY with the model name in it. So, something like GROUP BY ('Game'), "game"."id" which I have no clue why this happens. -
Django RestFramework - convert list to dict
I'm translating an API in Java to DRF and the consumption will be in a data.py Using DRF API ind = requests.get(base_url + "get_ind?ind_id={}".format(ind)) print(ind.json()) [{ "id": 1, "ind_id": 1, "co_ind": "Some String", "no_ind": "Some String", "ds_ind": "Some String", "ds_not_ind": "", "uni_id": 1, "per_id": [ { "id": 7, "no_per": "Some String", "tip_var": "", "co_per": "Some String", "no_cat": "", "per_id": 7, "uni_id": 1 }, { "id": 9, "no_per": "Some String", "tip_var": "", "co_per": "Some String", "no_cat": "", "per_id": 9, "uni_id": 1 }, ], "co_mod": "Some String" }] I want: Using Java API ind = requests.get(base_url + "get_ind?ind_id={}".format(ind)) print(ind.json()) { "id": 1, "ind_id": 1, "co_ind": "A", "no_ind": "DOMÍCILIOS QUE POSSUEM EQUIPAMENTO TIC", "ds_ind": "Total de domicílios", "ds_not_ind": "", "uni_id": 1, "per_id": [ { "id": 7, "no_per": "Proporção de domicílios que possuem equipamentos TIC", "tip_var": "", "co_per": "DIC_TV", "no_cat": "", "per_id": 7, "uni_id": 1 }, { "id": 9, "no_per": "Proporção de domicílios que possuem equipamentos TIC", "tip_var": "", "co_per": "DIC_RADIO", "no_cat": "", "per_id": 9, "uni_id": 1 }, ], "co_mod": "A" } This is the view.py: class GetIndFilter(SearchFilter): def filter_queryset(self, request, queryset, view): queryset = super().filter_queryset(request, queryset, view) ind_id = request.GET.get('ind_id') if(ind_id != ''): result = Inds.objects.filter(ind_id = ind_id) return result class GetIndViewSet(viewsets.ModelViewSet): queryset … -
Подключение приложения с github в django-проект [closed]
Всем привет, я нуб. Делаю свой проект на Django в свободное от работы время. Я хочу подключить в строку для ввода адреса на странице плагин, который по опенсорсу распространяется на гитхабе. Он использует jquery. Я не могу понять куда мне его втыкать в проекте и где что указывать, чтобы было весело. Просмотрев несколько видео и прочитав несколько статей, я клонировал гит репозиторий в папку со статикой в джанго, а в шаблоне указал к ней путь. И попробовал метод из этого стороннего приложения применить к инпуту. Начал с того, что получаю инпут, около которого текстом написан мой метод, начал шевелить подключение JS кода к шаблону, избавился от ошибок и пришёл к тому же результату. Пожалуйста, помогите, я за деньги готов по зуму созвониться чтобы получить ответ. {% load static %} <!DOCTYPE html> <html> <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script> <script src={% static 'gameslist/jquery/jquery.fias.min.js' %} ></script> <input type="text"> $('text').fias({ oneString: true }); </html> Получаю на странице это enter image description here -
Django/Python/Plotly Icon level
I am working on a dashboard and I would like to use "icon rating" (is there a name for this?). I mean having a range of icons and see if they are full/empty/coloured in a scale of 1 to 4/5 or whatever number of icons. The most usual case is done with stars in many reviews but I would like to do it with other icons related to my dashboard topic. What's the best way to do it? I am using Django/Python/Plotly for this dashboard so tools related to these would be best. -
Django Rest Framework unique field constraint on array
So, I'm trying to make an endpoint where I insert a list of objects. My issue is the behavior and response when inserting duplicates. What I want to accomplish is to: Send the duplicate lead external_id(s) in the error response Insert any other non duplicated object I'm pretty sure this logic (for the response and behavior) could be accomplished in the modifying the serializer.is_valid() method... but before doing that, I wanted to know if anyone had experience with this kind of request.. Maybe there is a "clean" way to do this while keeping the unique validation in the model. Data on OK response: [ { "external_id": "1", "phone_number": "1234567890" } ] Data for a FAIL request (1 is dup, but 2 should be inserted. Expecting a response like "external_id" : "id 1 is duplicated"): [ { "external_id": "1", "phone_number": "1234567890" }, { "external_id": "2", "phone_number": "2234567890" } ] models.py class Lead(models.Model): external_id = models.CharField(max_length=20, unique=True) phone_number = models.CharField(max_length=50) serializers.py class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' def create(self, validated_data): lead = Lead.objects.create(**validated_data) log.info(f"Lead created: {lead.import_queue_id}") return lead views.py class LeadView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @extend_schema(description="Insert campaign data", request=LeadSerializer(many=True), responses=None, tags=["Leads"]) def post(self, request): serializer = … -
Iterator should return strings, not bytes (the file should be opened in text mode)
this is my code.. def import_excel(request): if request.method == 'POST': person_resource = PersonResource() dataset = Dataset() new_person = request.FILES['myfile'] if not new_person.name.endswith('csv'): messages.info(request,'Wrong format') return render(request,'upload.html') imported_data = dataset.load(new_person.read(),format='csv') for data in imported_data: value = Person( data[0], data[1], data[2] ) value.save() return render(request,'upload.html') while importing the csv file to the database getting the error: iterator should return strings, not bytes (the file should be opened in text mode) like this -
Python django Failed to create a virtualenv
I was trying to create a virtual env with python3. But it failed to create new. But the existing virtual env are working fine. Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 82, in _get result = get_wheel( File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\acquire.py", line 23, in get_wheel wheel = from_bundle(distribution, version, for_py_version, search_dirs, app_data, do_periodic_update, env) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\bundle.py", line 17, in from_bundle wheel = periodic_update(distribution, of_version, for_py_version, wheel, search_dirs, app_data, per, env) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 35, in periodic_update handle_auto_update(distribution, for_py_version, wheel, search_dirs, app_data, env) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 69, in handle_auto_update embed_update_log.write(u_log.to_dict()) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\app_data\via_disk_folder.py", line 154, in write self.file.write_text(json.dumps(content, sort_keys=True, indent=2)) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\pathlib.py", line 1154, in write_text with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f: File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\pathlib.py", line 1119, in open return self._accessor.open(self, mode, buffering, encoding, errors, PermissionError: [Errno 13] Permission denied: 'C:\\Users\\DELL\\AppData\\Local\\pypa\\virtualenv\\wheel\\3.10\\embed\\3\\pip.json' fail -
Can we import the modules/functions from stand alone python code to DJango framework?
I have a parent directory under which we have multiple directories where standalone Python codes are developed and these py files are executed with parameters(ex - python --env=prod file_name.py) and in the same parent directory I have the directory of DJango code and the DJango code are importing the modules from standalone python modules. When I try to start the Django server using the command - "python manage.y runserver" I get the message - "manage.py: error: unrecognized arguments: runserver". Can you please help if importing of standalone python modules are allowed or not into the Django and if allowed then how we can achieve it. -
Why docker compose dosent create container with container_name
i create Dockerfile and docker-compose.yml. i build image with tag "django-image" Dockerfile: `FROM python:3 WORKDIR /code-django COPY . /code-django RUN pip3 install -r requirements.txt` docker-compose.yml: services: db: image: postgres container_name: db-money volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: image: django-image container_name: money volumes: - .:/code-django ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db in docker compose i have 2 services,"db" and "web". docker compose creates "db" with "container_name: db-money" and starts it. but compose dosent create anothe container with "container_name: money". why the second "container_name" dosent work?? enter image description here -
unable to install backports.zoneinfo
when i execute 'pip install -r requirements.txt ' this is displayed and i can't download backports.zoneinfo . `(venv) ##########@Air-de-#### ###### % pip install -r requirements.txt ... lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found #include "Python.h" ^~~~~~~~~~ 1 error generated. error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Successfully built PyYAML Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects (venv) ######@Air-de-###### ####### % pip install backports.zoneinfo ... lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found #include "Python.h" ^~~~~~~~~~ 1 error generated. error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects` -
Django Sitemap Generates https:// Twice in Development
The example.com/sitemap.xml is returning loc with double https:// making the generated sitemap to be incorrect/unacceptable. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://https://example.com</loc> <changefreq>monthly</changefreq> <priority>1.0</priority> </url> I've tried changing the protocol in the sitemaps.py file from https to http but that only appends http:// in front of the https://example.com/. Any ideas? -
Django 1.11.29. When sending long string on subject, Django inserts \t and extra space after comma
Django 1.11.29. When sending long string on subject, Django inserts \t and extra space after comma. I tried sending emails setting to QP, 8bit. But Django if subject length is more than 70 chars, it inserts extra space and tabulation From nobody Fri Jan 20 13:25:04 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Subject: Earth - Earth population is 4, 652, 123 people and digest is d3ea33dbe135a35fdde8984d1d920b8e6149526ed1fb5c9c656e8834d85d3a4e From: me@me.com To: me1@me.com Date: Fri, 20 Jan 2023 13:25:04 -0000 Message-ID: <20230120132504.88256.54199@medet-Lenovo-ideapad-330-15IKB> Content-Transfer-Encoding: quoted printable Subject: Earth - Earth population is 4, 652, 123 people and digest is d3ea33dbe135a35fdde8984d1d920b8e6149526ed1fb5c9c656e8834d85d3a4e Content-Type: text/html; charset=UTF-8 MIME-Version: 1.0 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tem= por incididunt ut labore et dolore magna aliqua. Suscipit tellus mauris a d= iam maecenas sed enim ut. In vitae turpis massa sed. Dictum varius duis at = consectetur lorem. At volutpat diam ut venenatis tellus in metus vulputate = eu. Vel quam elementum pulvinar etiam non quam lacus suspendisse. Lacus lao= i've tested and tried a lot of things, but i dont know how to resolve to sending long subjects. I also checked and its not helps https://code.djangoproject.com/ticket/7747 i've tested and tried a lot … -
I can't loop trough a dictionnary in my Django Template
I'm trying to loop trough a dictionnary to create a simple table with the keys in a column and the values in the other. So in my view I create the dictionnary vegetables_dict. I loop trhough the "items" of a "cartitem". If the item doesn't alrady exists I created a key with the name of a ForignKey of "item" and a value with its attribute quantity. Otherwise I increment the already existing key with the corresponding quantity def dashboard_view(request): carts = Cart.objects.filter(cart_user__isnull = False) cartitems = CartItem.objects.all() vegetables_dict = {} for item in cartitems: if item.stock_item.product_stockitem.name in vegetables_dict: vegetables_dict[item.stock_item.product_stockitem.name] += item.quantity else : vegetables_dict[item.stock_item.product_stockitem.name] = item.quantity context = { 'carts' : carts, 'cartitems' : cartitems, 'items' : vegetables_dict } return render(request, "maraicher/dashboard.html", context) In the template i Tried : <table> <thead> <tr> <th colspan="2"> Récapitulatif de récole</th> </tr> </thead> <tbody> <th>Produit</th> <th>Quantité</th> <div>{{items}}</div> {% for key, value in items.item %} <tr> <td>{{key}}</td> <td>{{value}}</td> </tr> {% endfor %} </tbody> </table> {{items}} render the dictionnary but the table is empty. Any idea what is happening? I aslo tried {% for item in items %} <tr> <td>{{item}}</td> <td>{{item.item}}</td> </tr> {% endfor %} -
What is the main difference between making a query using Manager.raw() method and connection.cursor() method?
I need to know which one is faster and why, and I also need to know the cases for each one. I try them both but I can't find the difference. -
What is the best experinces to structure a Django project for scale?
Django is great. But as we add new features, as our dev team grows, the software needs to be stable on production, things can get quite messy. We are going to want some common patterns, derived from experience, on how to structure your Django project for scale and longevity. What is your suggestion? Indeed, there are many models and patterns for development, but we want to know your experiences. -
session based django social
I'm using social-auth-app-django for authenticate with google. The process working fine and the user is register in the DataBase. The problem begins when I'm trying to login the users automatically when they register with Google. The users keeps to be unauthenticated in the session. Here is my current configurations using social-auth-app-django and djoser: settings.py: AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend' ) DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': True, 'SEND_CONFIRMATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'CREATE_SESSION_ON_LOGIN': True, 'SOCIAL_AUTH_TOKEN_STRATEGY': 'members.social_token.TokenStrategy', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': [ 'http://localhost:3000/google' ], 'SERIALIZERS': { 'current_user': 'members.serializers.UserCreateSerializer', } I think the most relevant part is the SOCIAL_AUTH_TOKEN_STRATEGY. Where the members.social_token.TokenStrategy is: from django.contrib.auth import login from django.http import HttpRequest from django.conf import settings from importlib import import_module class TokenStrategy: @classmethod def obtain(cls, user): from rest_framework_simplejwt.tokens import RefreshToken from six import text_type refresh = RefreshToken.for_user(user) request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) session_key = None request.session = engine.SessionStore(session_key) login( user=user, request=request, ) user.is_active = True return { "access": text_type(refresh.access_token), "refresh": text_type(refresh), "user": user, } I can see that the sessionid and the csrftoken is been saved in the browser cookies and in the TokenStrategy the request.user.is_authenticated equals to true. My problem is that for all the following requests the value of the request.user.is_authenticated keeps …