Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to mirror a container directory on the host?
All I want is to be able to read a directory of my container from my host machine. I.e., a symlink from my host machine to the container's directory, and I don't require anything more than read permissions. I have tried many different methods: services: django: volumes: - /tmp/docker-django-packages:/usr/local/lib/python3.12/site-packages Problem: /tmp/docker-django-packages is not created if it doesn't exist, but there is no docker error, however no python packages can be resolved by the container's python process. If I manually make /tmp/docker-django-packages on the host, then I still get the same error. services: django: volumes: - type: bind source: /tmp/docker-django-packages target: /usr/local/lib/python3.11/site-packages bind: create_host_path: true Problem: /tmp/docker-django-packages is not created. If I make it manually, it is not populated. The container behaviour is not affected at all. services: django: volumes: - docker-django-packages:/usr/local/lib/python3.11/site-packages volumes: docker-django-packages: driver: local driver_opts: type: none o: bind device: "/tmp/docker-django-packages" Problem: host directory not created if it doesn't exist, not populated if it already exists, and the container functions as normal services: django: volumes: - type: volume source: docker-django-packages target: /usr/local/lib/python3.11/site-packages volumes: docker-django-packages: driver: local driver_opts: type: none o: bind device: "/tmp/docker-django-packages" Problem: host directory not created, nor populated, container yet again functions as if these lines weren't … -
Why this inner atomic block not rolled back in a viewflow custom view code
I created this custom create process view to add in logged in user's email to the saved object, I also added a transaction block so that when the next step fails (inside self.activation_done() statement) it will roll back the db changes inside form_valid() and then display the error in the start step, so no new process instance is saved. from django.core.exceptions import ValidationError from django.db import transaction from django.http import HttpResponseRedirect from viewflow.flow.views import CreateProcessView, StartFlowMixin class StarterEmailCreateProcessView(CreateProcessView): """ Sets the user email to the process model """ def form_valid(self, form, *args, **kwargs): """If the form is valid, save the associated model and finish the task.""" try: with transaction.atomic(): super(StartFlowMixin, self).form_valid(form, *args, **kwargs) # begin of setting requester email # https://github.com/viewflow/viewflow/issues/314 self.object.requester_email = self.request.user.email self.object.save() # end of setting requester email self.activation_done(form, *args, **kwargs) except Exception as ex: form.add_error(None, ValidationError(str(ex))) return self.form_invalid(form, *args, **kwargs) return HttpResponseRedirect(self.get_success_url()) Based on Django documentation, exception raised inside the transaction is rolled back However, upon form displays the error message, new process instances are still saved, so I suspect the transaction is not rolled back and I don't know why. -
How to authorize a Gmail account with Oauth to send verification emails with django-allauth
So from 2025 less secure apps are going to be disabled and i can't figure out how to integrate gmail account with django-allauth anymore in order to send verification emails. I have OAuth consent screen and credentials, Client_id, Client_secret but i don't understand how can I use this gmail account with django. I know i lack code here, but literally didn't get anywhere other than creating an account in google console and activating OAuth/Credentials. Been searching for any guide online but they are all using less secure apps. Tried something with https://docs.allauth.org/en/dev/socialaccount/providers/google.html but not even sure if this has anything to do with logging in an account into the app and sending emails using that account -
Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at dashboard/:110:27 django python
i am working on a chart that shows data on the dashbord. it's taking the data from the db and trying to make a json from that but in the html code it's not working. showing Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () this is the view def dashboard(request): mood_data = MentalHealthSurvey.objects.values( 'mood').annotate(count=Count('mood')) stress_data = MentalHealthSurvey.objects.values( 'stress_level').annotate(count=Count('stress_level')) # Serialize data for JavaScript mood_data_json = json.dumps(list(mood_data)) stress_data_json = json.dumps(list(stress_data)) context = { 'mood_data_json': mood_data_json, 'stress_data_json': stress_data_json, } return render(request, 'employees/dashboard.html', {'context': context}) this is the template code. {% extends 'employees/base_generic.html' %} {% block title %} Employee Dashboard {% endblock %} {% block content %} <div class="container"> <h2>Survey Data</h2> <canvas id="moodChart"></canvas> <canvas id="stressChart"></canvas> </div> {% endblock %} {% block scripts %} <script> const moodData = JSON.parse('{{ mood_data_json|safe }}') console.log('moodData:', moodData) const stressData = JSON.parse('{{ stress_data_json|safe }}') const moodLabels = (moodData || []).map((item) => item.mood || 'Unknown') const moodCounts = (moodData || []).map((item) => item.count || 0) const stressLabels = (stressData || []).map((item) => item.stress_level || 'Unknown') const stressCounts = (stressData || []).map((item) => item.count || 0) const moodChart = new Chart(document.getElementById('moodChart'), { type: 'pie', data: { labels: moodLabels, datasets: [ { data: moodCounts, backgroundColor: ['#28a745', '#ffc107', '#dc3545', '#17a2b8', '#6f42c1'] … -
React Flow Edges Not Displaying Correctly in Vite Production Mode with Django Integration
I am developing a Django website and encountered an issue while integrating React Flow UI into one of the apps. The frontend of the site was previously written entirely in pure HTML, CSS, and JavaScript, so I am new to React. I needed to generate a React Flow canvas and pass it to a Django template. Using Vite to bundle the React app, I successfully implemented this, but I encountered a problem: in production mode (after building with npx vite build), the CSS behavior differs from development mode (running with npx vite dev). In development mode, styles render correctly. However, in the production version, styles work only partially — specifically, edges between nodes (react-flow__edge-interaction) are not displayed. Problem In production mode, React Flow edges (react-flow__edge) are not displayed, and their CSS classes only partially work. In development mode, everything functions correctly. Video with an example of the problem: click Project structure Standard files/directories for Django and React apps are omitted for brevity: <app_name>/ ├── templates/ │ └── <app_name>/ │ └── reactflow_canvas.html ├── static/ │ └── reactflow-frontend/ | ├── dist/ (dir with build files (index.css and index.js) │ ├── src/ │ │ ├── App.jsx │ │ ├── App.css │ │ ├── … -
Django : 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead
I am newbie at Python/Django i have been charged to migrate old project from Python 3.7 / Django 2.2.5 to the Python 3.12 and Django 5.1 but when i did this some functionality didn't work now . For exemple before i have in the Admin interface when i click on "Add watcher" i can create watcher and in the same page choose the realted Trigger, Indicator and other staff. But in my new version when i choose Add Watcher i have this error : RuntimeError at /admin/watchers/watcher/add/ 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead. I am using the last version of django-polymorphic, nested-admin from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin, PolymorphicInlineSupportMixin import nested_admin from django.db import transaction from watchers.models import * class TriggerInline(nested_admin.NestedStackedPolymorphicInline): model = apps.get_model('triggers', 'Trigger') child_inlines = tuple([type(f'{subclass.__name__}Inline', (nested_admin.NestedStackedPolymorphicInline.Child,), { 'model': subclass, 'inlines': [ TriggerComponentInline] if subclass.__name__ == "CompositeTrigger" else [] }) for subclass in apps.get_model('triggers', 'Trigger').__subclasses__()]) #Same that TriggerInline class IndicatorInline(nested_admin.NestedStackedPolymorphicInline) class WatcherChildAdmin(PolymorphicChildModelAdmin): base_model = Watcher inlines = (IndicatorInline, TriggerInline,) #Other infos #Register subclass for subclass in Watcher.__subclasses__(): admin_class = type(f'{subclass.__name__}Admin', (nested_admin.NestedPolymorphicInlineSupportMixin,WatcherChildAdmin,), { 'base_model': subclass, 'exclude': ['periodicTask', ], }) admin.site.register(subclass, admin_class) @admin.register(Watcher) class WatcherParentAdmin(PolymorphicInlineSupportMixin, PolymorphicParentModelAdmin): base_model = Watcher child_models = tuple(Watcher.__subclasses__()) #Other Functions Both Trigger and … -
How to create a "Bulk Edit" in Django?
I would like to create a bulk edit for my Django app, but the problem is that I don't get the function to work. I got lost at some point while creating it, and don't know what I am doing wrong. I feel sruck at this point, I don't see other options. Here is what I have done so far (I am using airtable as the database): The error is mostly when it tryies to retrieve the products from the tables after being selected with the checkbox (I tried to debug it, and change it but I don't see what else I could do) models.py from django.db import models class RC(models.Model): sku = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) cost = models.DecimalField(max_digits=10, decimal_places=2) weight = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class Category(models.Model): sku = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=255) category = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class LB(models.Model): sku = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=255) cost = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class PM(models.Model): sku = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=255) cost = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators … -
Split queryset into groups without multiple queries
How can I retrieve a ready-made queryset divided into two parts from a single model with just one database hit? For example, I need to fetch is_featured=True separately and is_featured=False separately. I tried filter function of python but I want to do it alone with query itself is that possible. I want to add 2 featured and 8 organic products on one page. In general, is it correct to divide them into two groups, bring them in, and then set the correct position for each? p = Product.objects.all() featured_products = filter(lambda p: p.is_featured, p) list(featured_products) [<Product: Nexia sotiladi | 2024-12-06 | -20241206>, <Product: Nexia sotiladi | 2024-12-06 | -20241206>` these are is_featured=True -
Configuring Celery and its progress bar for a Django-EC2(AWS)-Gunicorn-Nginx production environment
I am trying to implement a Celery progress bar to my Django website, which is now on the Web via AWS EC2, Gunicorn, and Nginx, but I simply cannot get the Celery progress bar to work. The bar is supposed to come on after the visitor clicks the submit button, which triggers a process that is run by Celery and feedback on progress is fed to the frontend via Celery Progress Bar. Celery fires up initially, but then flames out if I hit the submit button on my website, and never restarts until I manually restart it. Below is the report on the Celery failure: × celery.service - Celery Service Loaded: loaded (/etc/systemd/system/celery.service; enabled; preset: enabled) Active: failed (Result: timeout) since Mon 2024-12-09 15:14:14 UTC; 6min ago Process: 68636 ExecStart=/home/ubuntu/venv/bin/celery -A project worker -l info (code=exited, status=0/SUCCESS) CPU: 2min 51.892s celery[68636]: During handling of the above exception, another exception occurred: celery[68636]: Traceback (most recent call last): celery[68636]: File "/home/ubuntu/venv/lib/python3.12/site-packages/billiard/pool.py", line 1265, in mark_as_worker_lost celery[68636]: raise WorkerLostError( celery[68636]: billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 15 (SIGTERM) Job: 0. celery[68636]: """ celery[68636]: [2024-12-09 15:14:13,435: WARNING/MainProcess] Restoring 2 unacknowledged message(s) systemd[1]: celery.service: Failed with result 'timeout'. systemd[1]: Failed to start celery.service - Celery Service. … -
Django cant access variable from form created with ModelForm
I am trying to create a simple form based on ModelForm class in Django. Unfortunately I keep getting UnboundLocalError error. I checked numerous advises on similar issues, however it seems I have all the recommendations implemented. If I run the below code, I get following error: UnboundLocalError: cannot access local variable 'cook_prediction' where it is not associated with a value My models.py: from django.db import models class RecipeModel(models.Model): i_one = models.BigIntegerField(default=0) v_one = models.FloatField(default=0) My forms.py: from django import forms from .models import RecipeModel class RecipeInputForm(forms.ModelForm): class Meta: model = RecipeModel exclude = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['i_one'].initial = 0 self.fields['v_one'].initial = 0 My views.py: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . import forms @login_required def index(request): if request.method == 'POST': recipe_form = forms.RecipeInputForm(request.POST) else: recipe_form = forms.RecipeInputForm() if recipe_form.is_valid(): cook_prediction = recipe_form.cleaned_data if recipe_form.is_valid() == False: print("Recipe form is not valid!") After running the code, except for the above mentioned error message, I also get the Recipe form is not valid! printout from the last line of views.py. How to get rid of this error and successfully get variable from form based on ModelForm? -
Python async performance doubts
I'm running an websocket application through Django Channels and with Python 3.12. I have a ping mechanism to check if my users are still connected to my application where at a fixed time interval the fronted sends a ping message to my server (let's say every 5 seconds) and when I receive that message I do the following: I call await asyncio.sleep(time interval * 2) ; Afterwards I check if the timestamp of the last message I received in this handler or in any other of the ones that is active is higher than time_interval * 1.5 and if it is I disconnect the user in order to free that connection resources since it isn't no longer active; However we noticed that this sleep call we make every X seconds for each active connection that we have when a ping call is received may be causing some performance issues on the application as an all. We are assuming this because we noticed that every time we shut down this ping logic we need less resources (number of pods and CPU) to handle the median number of traffic we have then when we have this ping handler active. In other hand … -
Django override settings not being assigned in the __init__ method even though they are available
I am overriding settings for the entire test class like this: @mock_aws @override_settings( AWS_CLOUDFRONT_DOMAIN="fake_domain", AWS_CLOUDFRONT_KEY="fake_key", AWS_CLOUDFRONT_KEY_ID="fake_key_id", AWS_CLOUDFRONT_DISTRIBUTION_ID="fake_distribution_id", ) class TestCloudfrontClient(TestCase): def setUp(self): self.cf_client = CloudfrontClient() and here is the CloudfrontClient class: class CloudfrontClient: """Client to interact with AWS S3 through Cloudfront""" def __init__( self, cloudfront_pk_id=settings.AWS_CLOUDFRONT_KEY_ID, cloudfront_key=settings.AWS_CLOUDFRONT_KEY, cloudfront_distribution_id=settings.AWS_CLOUDFRONT_DISTRIBUTION_ID, cloudfront_domain=settings.AWS_CLOUDFRONT_DOMAIN, rsa_signer=rsa_signer ): self.cf_client = client('cloudfront') self.distribution_id = cloudfront_distribution_id self.cloudfront_signer = CloudFrontSigner(cloudfront_pk_id, rsa_signer) self.cloudfront_domain = cloudfront_domain breakpoint() At the breakpoint if I print settings.AWS_CLOUDFRONT_KEY_ID I get the fake_key_id but when I print cloudfront_pk_id I get empty string. This is also the case for other variables and it is messing my test results. Am I missing something about how override_settings work? -
PostgreSQL Azure database not connecting to Django app
I have issues with a Django deployment. I am deploying on Azure through github. The app builds and deploys successfully, I am able to migrate the database, but then I receive a error when I try to log in, it seems that the data is not being saved. [migrate](https://i.sstatic.net/it8xLAnj.png) [showmigrations](https://i.sstatic.net/7ogvwvye.png) [django error](https://i.sstatic.net/e8nY3xmv.png) I have added logs to see if I can find where the issue might be but I am unable to establish where the issue lies. -
How to create android app for Django website?
I have django website already running. It is using MySQL as database and hosted in windows VPS with windows IIS server. Now I need to create a mobile app (android app) for my django website. (I'm not too much familiar with android development) **1. So what is the better way to do this? And how to do this?** -
How to sum two datefields in sqlite using django orm
My django5 model has two datetime fields, bgg_looked_at and updated_at. They are nullable, but fields should not be null when this query is ran. So far I tried class UnixTimestamp(Func): function = 'strftime' template = "%(function)s('%%s', %(expressions)s)" # Escape % with %% output_field = FloatField() # Explicitly declare the output as FloatField and listings = Listing.objects.annotate( bgg_looked_at_timestamp=Coalesce( UnixTimestamp(F('bgg_looked_at')), Value(0.0, output_field=FloatField()) ), updated_at_timestamp=Coalesce( UnixTimestamp(F('updated_at')), Value(0.0, output_field=FloatField()) ) ).annotate( sum_fields=ExpressionWrapper( F('bgg_looked_at_timestamp') + F('updated_at_timestamp'), output_field=FloatField() ) ).order_by('sum_fields') but I get TypeError: not enough arguments for format string when I just do a len(listings) -
Unable to run frappe-gantt in my Django project
I develop a Django app that will display gantt projects graph and I came to frappe-gantt, an open source librairy (https://github.com/frappe/gantt/tree/master) that is exactly what I am looking for. But, I have an error when trying to run the simple example: Uncaught TypeError: t is undefined. Librairy seems to be correctly loaded as HTTP responses return 200 and console.log(typeof Gantt); return "function". Gantt function target a DOM element that currently exist. I did not find any answer in SO. To notice that when loaded, frappe-gantt.umd.js header Content-Type is text/plain instead of "application/json" that maybe could explain? Thanks for your help {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css"> <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script> <link rel="stylesheet" href="{% static 'dist/frappe-gantt.css' %}"> <script src="{% static 'dist/frappe-gantt.umd.js' %}"></script> </head> <body> <section class="section"> <div class="container"> <div class="columns"> <div class="column is-2"> <div class="aside"> <h3 class="menu-label">Projects</h3> <hr> <ul class="menu-list"> {%for p in projects %} {% if p.tasks.count > 0 %} <li> <a {% if p.id == id|add:0 %} class="is-active" {%endif%} href="?id={{p.id}}"> {{p.name}} </a> </li> {% endif %} {% endfor %} </ul> <hr> <h3 class="menu-label">Options</h3> <ul class="menu-list"> <li> <a target='_blank' href="/admin">admin</a> </li> </ul> </div> </div> {% if tasks_count %} <div class="column is-10"> <div … -
django alter checkconstraint with json field
I want to alter table to add check constraint in mysql, if using sql like below ALTER TABLE Test ADD CONSTRAINT chk_sss CHECK( JSON_SCHEMA_VALID( '{ "type":"object", "properties":{ "latitude":{"type":"number", "minimum":-90, "maximum":90}, "longitude":{"type":"number", "minimum":-180, "maximum":180} }, "required": ["latitude", "longitude"] }', sss ) ) class Test(models.Model): sss = models.JSONField(null=True) class Meta: constraints = [ CheckConstraint( check = ???????), ] how to write this sql in model ? -
How can I fix pycham wrong django type hint
member_meta_models: QuerySet[MemberWantedMetaModel] = MemberWantedMetaModel.objects.filter(member_id=member_id) Pycharm says "Expected type QuerySet[MemberWantedMetaModel,MemberWantedMetaModel], got QuerySet[MemberWantedMetaModel] I think type hint is right. How Can I fix it. If my type hint is wrong, How can I fix it? (I am using python 3.13.0, Django 5.1.4 mypy, pydantic) Thanks -
AttributeError: 'WSGIRequest' object has no attribute 'user_profile' in Django Web Application
When developing a Web application using the Python Django framework, I encountered an error 'AttributeError: 'WSGIRequest' object has no attribute 'user_profile''. My code attempts to access request.user_profile in a view function. I have already ensured that the user authentication middleware is enabled. What could be the possible reasons for this? I have tried the following methods: Checked the configuration and functionality of the user authentication middleware to ensure it operates properly and can correctly identify the user. Reviewed other operations related to the request object in the view function to confirm that the request object has not been accidentally modified. -
Slug Field in Django Model Not Including Related Tags on Save
I have the following save method in my Django model: slug = models.SlugField(unique=True, blank=True, null=True, max_length=255) def save(self, *args, **kwargs): if self.pk is None: super().save(*args, **kwargs) tags = Tag.objects.filter(office__id=self.id).values_list("name", flat=True) print("Tags") print(tags) location_work_override_id = self.location_work_override.id if self.location_work_override else '' location_work_id = self.contest.location_work_id if self.contest and self.contest.location_work_id else '' if not self.slug and tags: self.slug = slugify( f"{self.display_name}-{'-'.join(tags)}-{location_work_override_id}-{location_work_id}-{self.contest.short_name}-{self.contest.contest_number}" ) elif not self.slug: self.slug = slugify( f"{self.display_name}-{location_work_override_id}-{location_work_id}-{self.contest.short_name}-{self.contest.contest_number}" ) super().save(*args, **kwargs) The slug field is supposed to include related Tag names from a Tag model that has a ForeignKey to Office. However, when I create a new Office instance in the Django admin, the tags variable in the save method is always empty, even though I add the tags in the admin interface. I suspect this is a timing issue because the save method of Office runs before the related Tag objects are saved. My Questions: How can I ensure that the Tag objects are saved before the save method of the Office model accesses them? Is there a way to correctly populate the slug field with the tags in this scenario, preferably without relying on manual order of operations? I’m looking for a robust solution that works reliably in the Django admin … -
Unable to login subdomain of django tenant, primary domain and admin log in work
I have a multi tenant app using the library django-tenants. When logging into the core URL with the created superuser, the login page works completely fine. When using the subdomain address to login, the page returns a 500 error when using the correct username and password that exists and the console says Uncaught (in promise) SyntaxError: Unexpected token '<', " <!doctype "... is not valid JSON. When using an login username that doesn't exist, the output is 400 Bad Request. The odd part, is I can access the admin panel of a subdomain, log in completely fine, change the URL to go to a part of the app - and the user is now logged in. After being logged in, I can submit forms completely fine and data is being captured, it is solely the login page on a subdomain that has an error submitting. I am lost since subsequent data forms submit and go correctly, and there are no invalid tokens (from what I see) views.py def dual_login_view(request): """Authenticate users with both Django Authentication System and Django Rest Framework""" if request.method == "POST": username = request.POST.get("login") password = request.POST.get("password") user = authenticate(request, username=username, password=password) if user is not None: … -
uniqueConstraint and get_or_create not working?
I am trying to make a thread safe/concurrent aware create function for some moel, as I understood it the following should work: @transaction.atomic def create_new_request(self, request: Request): item_id = 1 item = Item.objects.get(id=item_id) print("creating", request.user) purchase_request, request_created = PurchaseRequest.objects.select_for_update().get_or_create( requester=request.user, status="draft", ) purchase_request.save() print("get or created: ", purchase_request.id, request_created) Then I created a unique constraint in the meta (as only "drafts" have this constraint of a single draft per user) class PurchaseRequest(models.Model): class Meta: verbose_name = "Original Purchaserequest" verbose_name_plural = "Original Purchaserequests" constraints = [ models.UniqueConstraint( fields=["requester", "status"], condition=Q(status="draft"), name="unique_draft_user" ) ] However the moment I sent multiple requests at once from the frontend (using promise.all to sent many simultaneously), I notice that the application crashes with the following errors: creating paulweijtens creating paulweijtens creating paulweijtens get or created: 483 True 2024-12-08 22:21:27,732 ERROR root duplicate key value violates unique constraint "unique_draft_user" DETAIL: Key (requester_id, status)=(224, draft) already exists. Traceback (most recent call last): File "", line 916, in get_or_create return self.get(**kwargs), False ^^^^^^^^^^^^^^^^^^ File "", line 637, in get raise self.model.DoesNotExist( isp.procure.purchase.models.PurchaseRequest.DoesNotExist: PurchaseRequest matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 89, in _execute return … -
signnow API/django app/ send email/ e-signing contract/
thank you for your time. i had a task to do: Tasks at hand o Brief description of the tasks to be performed ▪ The objective is to create a Django app that enables a user to register, log in, and sign a pre-defined contract. The contract will have 2 signing parties: one of them is the user that logs in initially and signs the contract, the other signing party is to be invited to sign by email. o User Stories ▪ As a user, I want to register, so that I could get logged in to use the signing features of the app • Acceptance Criteria o Basic django authentication is enough (session auth) o Username and password is enough for registration o No extra validation required for password or username o Upon logging in, I should be directed to the contract instantiation page ▪ As a user, I want to log in, so that I could use the signing features of the app • Acceptance Criteria o Log in with username and password o No extra validation required for password or username o Upon logging in, I should be directed to the contract instantiation page ▪ As a … -
Django-Extensions: how to add local variables to shell_plus
I have multiple dictionaries, and I want each key/value pair to be defined in the local scope of a django-extensions shell_plus session. My current management command looks something like this: import django import code devs = { 'hot_water': object() 'air': object() } procs = { 'clean_keg': lambda x: 'do_something' } # unnecessary code when using `shell_plus` model_map = { model.__name__: model for model in django.apps.apps.get_models() } local = { 'procs': procs, 'devs': devs, **devs, **procs, **model_map } code.interact(local=local) Now I find myself wanting to add settings, models, and several other Django objects that are already included with shell_plus, but I can't find a way to add local variables to the shell_plus session. Brett Thomas's answer shows how to import modules into a shell_plus session, but doesn't show how to add variables from a dict-like object. How do I add variables to a shell_plus session? -
Django Allauth 65.2.0 headless mode - session token problems
I have a setup with django, drf, django-allauth headless and nextjs acting somewhat as a proxy to my django api, completely decoupled and server from different servers (a regular django setup and separate node server for next) Settings: AUTH_USER_MODEL = "user.User" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] HEADLESS_ONLY = True HEADLESS_FRONTEND_URLS = {} # HEADLESS_TOKEN_STRATEGY = "apps.core.backends.allauth_token_strategy.DRFTokenAndAnonSessionTokenStrategy" SOCIALACCOUNT_PROVIDERS = { "google": { "APP": { "client_id": config.OAUTH.GOOGLE.CLIENT_ID, "secret": config.OAUTH.GOOGLE.CLIENT_SECRET, }, "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "offline", }, "OAUTH_PKCE_ENABLED": True, } } URLs: (the change is purely for aesthetics) from allauth.headless.constants import Client from allauth.headless.urls import build_urlpatterns from django.urls import path, include from django.urls.resolvers import RoutePattern def build_allauth_url_patterns(): path_object = build_urlpatterns(Client.APP)[0] path_object.pattern = RoutePattern("") return [path_object] urlpatterns = [ path("user/", include((build_allauth_url_patterns(), "headless"), namespace="app")), path("accounts/", include("allauth.urls")), ] I want to use the headless mode since I don't need the CSRF features of django allauth browser implementation, however I want to use the handshake of django-allauth so I'm sending a post request to the api via a form from nextjs. for this example consider my domain as localhost <form method="post" action="https://api.localhost/v1/user/auth/provider/redirect" className="w-full"> <Button variant="outline" className="gap-2 w-full" type="submit"> <Icons.LogIn /> <span>Sign Up With Google</span> </Button> <Input …