Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MYSQL drive issue when Django app run on Azure Function
When running Django app on Azure function, Im getting below error. "ENGINE": "django.db.backends.mysql" Result: Failure Exception: NameError: name '_mysql' is not defined Stack: Is there any solution for this issue ? Assuming cant install mysql module on Azure function. -
Pycharm theme colors not changing from color scheme
PROBLEM Hi, I'm new to PyCharm, but used to Atom with a bunch of plugins as my IDE for Django, etc (switching cause no more Atom support, and it has bugs). I applied a theme I like well enough, duplicated it, and went to Settings > Editor > Color Scheme to change the colors of parts I don't like in ... > Color Scheme > Python For the most part, it's fine. It shows that both binary (bytes) and Text (unicode) strings are green, as I want. And they are fine when writing a function, doc string, etc: But when I'm in urls.py, the url routes aren't green like the other strings: WHAT I ALSO TRIED I checked the color schemes for Django, but it only has default colors for the template language only. Same thing in the HTML section for Attribute value (for href, src, etc values) Same for their inheritance at ... Language defaults > String > String text. I can add any other function in urls.py, call it anywhere, and it'll show the proper green (see url routing above), but not for path(). QUESTION Any ideas where / how to make it green? What have I missed? … -
python manage.py runserver not running proper
I am currently working in a Django project. I am running it through Docker, but I want to run it manually. I keep getting messages of error after run "python manage.py runserver" and it does perfoming system checks, I am stuck on this. Log: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\camil\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\camil\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( ^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\management\base.py", line 377, in run_checks return checks.run_checks(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() ^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\urls\resolvers.py", … -
Django error migrating nesting model w/o migrating base model
Purpose to have one BaseModel that can be nested by other models NOTE: BaseModel should not be written to database So I have one BaseModel like below class StaticVariable(models.Model): class Meta: managed = False title = models.CharField( max_length=250, blank=False, null=False ) alias = models.CharField( max_length=250, blank=False, null=False, unique=True ) created_at = models.DateTimeField( auto_now_add=True, blank=False, null=False ) updated_at = models.DateTimeField( auto_now=True, blank=False, null=False ) enabled = models.BooleanField( default=True, blank=False, null=False ) deleted = models.BooleanField( default=False, blank=False, null=False ) I made migrations and applied it, since class Meta has managed=False parameter, actual sql table is not being created (as expected) After that I craete new model wich is being nested from StaticVariable model as base class BodyType(StaticVariable): class Meta: db_table = 'body_type' ordering = ["title", "-id"] Then I makemigrations, which looks like this from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('utils', '0004_staticvariable'), ('app', '0002_alter_category_enabled'), ] operations = [ migrations.CreateModel( name='BodyType', fields=[ ('staticvariable_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='utils.staticvariable')), ], options={ 'db_table': 'body_type', 'ordering': ['title', '-id'], }, bases=('utils.staticvariable',), ), ] But, unexpectedly I catch below error when I try to migrate Running migrations: Applying app.0003_bodytype...Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) File … -
Vues generic DeleteView : accès à la clé
Salut à toutes et à tous, j'espère vous savoir en bonne santé et je vous adresse mes vœux pour le nouvel an par anticipation. J'ai une liste d'enseignant que j'affiche avec trois boutons:Voir, Modifier et Supprimer. Ce dernier ouvre une fenêtre modale qui demande confirmation de suppression: Voulez-vous supprimer {{nom et prénom}} de la personne. Le problème c'est qu'à chaque itération de la boucle {% for %} C'est toujours le nom du premier enseignant récupéré par l'objet de contexte qui s'affiche. Je suis convaincu que le problème vient de la fenêtre modale car quand je la retire, tout fonctionne correctement. Comment faire pour résoudre ce problème ? Merci d'avance -
Troubleshooting AWS Elastic Beanstalk Deployment Errors with Django Applications - Error: EbExtension build failed
When I was trying to deploy my Django application to AWS Elastic Beanstalk. Then I got this error. 2023/12/30 21:26:42.478526 [ERROR] An error occurred during the execution of command [app-deploy] - [PreBuildEbExtension]. Stop running the command. Error: EbExtension build failed. Please refer to /var/log/cfn-init.log for more details. What is the reason for that? Here is my Django.config which is located in .ebextensions folder. When I remove the 'commands' it gives me 502 bad gateway since the application cannot import the relavant packages. commands: 01_activate_virtualenv: command: "source /var/app/venv/staging-LQM1lest/bin/activate" 02_install_requirements: command: "pip install -r /var/app/current/requirements.txt" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django-pixel/core/wsgi.py -
Django URL Pattern Results in 404 Not Found Error stripe succeed
I'm working on a Django project with a payment processing feature and encountering a "404 Not Found" error when making a request to a specific URL. I've set up my URL patterns and views, but the request to /dashboard/services/payment/success/ is not being found. On the platform of stripe the payments are successful and I receive a confirmation in the console log. Here's the relevant code and error log: [30/Dec/2023 21:33:10] "POST /dashboard/services/payment/success/ HTTP/1.1" 404 4949 Error notifying backend:"Request failed with status code 404" urlpatterns = [ # ... other URL patterns ... path('payment/', views.make_payment, name='make_payment'), path('payment/success/', views.payment_success, name='payment_success'), path('payment/success_page/', views.payment_succeed, name='payment_succeed'), ] @login_required def make_payment(request): if not request.user.is_client: messages.error(request, "Only clients can make payments.") return redirect('services:dashboard') diagnostic_requests = DiagnosticRequest.objects.filter(client=request.user, payments__isnull=True) if not diagnostic_requests.exists(): messages.info(request, "You have no unpaid diagnostic requests.") return redirect('services:dashboard') total_cost = diagnostic_requests.aggregate(Sum('service__cost'))['service__cost__sum'] if request.method == 'POST': if request.headers.get('X-Requested-With') == 'XMLHttpRequest': # Initialize Stripe API stripe.api_key = settings.STRIPE_SECRET_KEY # Create a Stripe Payment Intent intent = stripe.PaymentIntent.create( amount=int(total_cost * 100), # Convert to cents currency='usd', payment_method_types=['card'] ) # Return the client secret in a JSON response return JsonResponse({'client_secret': intent.client_secret}) # Create a Payment record payment = Payment.objects.create( user=request.user, stripe_payment_intent_id=intent.id, paid_amount=total_cost, currency='USD' ) # Link payment with all diagnostic … -
Combining two databases together for seamless login
I have 2 applications developed with two different frameworks. One is using pure PHP and the other using Python Django. My question is related to database combination for seamless login. How does one even begin to have the following scenario? User is created on python application with email and password. User should be able to seamlessly login with credentials from one database to the other PHP application If user wants to login directly onto PHP application, they can do that as well. How would something like this be accomplished? I tried a couple of options of combining webhooks, but do not have enough knowledge of this to even understand. -
TypeError: Cannot combine queries on two different base models
In my django project i have 3 app, agent, teamlead, and phone. Both teamleaders models and agents models are of type FieldOfficer. A FieldOfficer has a phone. And since these phones are rotated, ie chances of a phone belonging to many FieldOfficers and viceversa are high. The FieldOfficer class is an abstract one and housed inside a python package separately. Now my problems start when i try to make a ModelForm from the Phone model. I keep getting a "TypeError: Cannot combine queries on two different base models." type here FieldOfficer Abstract Class from django.db import models class FieldOfficer(models.Model): first_name = models.CharField(max_length = 30, blank=False, null=False) last_name = models.CharField(max_length = 30, blank=False, null=False) personal_phone_number = models.CharField(max_length=30, unique=True, blank=False, null=False) alternative_phone_number = models.CharField(max_length=30, unique=True, blank=False, null=False) region = models.CharField(max_length=30) class Meta: abstract = True agent.models.py class Agent(FieldOfficer): teamleader = models.ForeignKey('teamleader.TeamLeader', null=True, on_delete=models.SET_NULL, related_name='teamlead') def __str__(self): return f'{self.first_name} {self.last_name}' teamlead.models.py class TeamLeader(FieldOfficer): def __str__(self): return f'{self.first_name} {self.last_name}' phone.Models.py class Phone(models.Model): field_officers = models.ManyToManyField(FieldOfficer, through='AgentPhoneAssignment', related_name="phone") def __str__(self): return f'{self.name} {self.imei}' class AgentPhoneAssignment(models.Model): field_officer = models.ForeignKey(FieldOfficer, on_delete=models.SET_NULL) phone = models.ForeignKey(Phone, on_delete=models.SET_NULL) ... # other fields def __str__(self): return f'{self.field_officer} {self.phone}' Create Phone form Class class CreatePhoneForm(forms.ModelForm): class Meta: model = Phone fields = … -
`UNIQUE constraint failed at: pharmcare_patient.id` in my pharmcare app
I have a Django app in my project I am currently working on called pharmcare, and I kind of getting into a unique constraint issue whenever I want to override the save() method to insert/save the total payment made by the patient so that the pharmacist that is creating the form or updating the patient's record won't perform the math manually. Whenever I used the form from CreateView on the view.py without overriding the save method with the function I created dynamically to solve the math, it performed the work perfectly well, but in the admin panel, the answer wouldn't appear there. However, if I tried using the save() in my models.py of the app I'd get that error. If I remove the save() method in the model, the error will disappear, and that's not what I want, since I want it to be save in the db immediately the pharmacists finished creating or modifying the form. I had used the get_or_create method to solve it but it remains abortive, and another option which I don't want to use (since I want the site owner to have the option of deleting the pharmacist/organizer creating the record at ease same with … -
Form with dynamic choices won't set choice as selected when bound
I have this form where one of the fields ("wheels") has a dynamically generated list of choices: class CarForm(forms.Form): colour = forms.ChoiceField(choices=(("BLACK", "Black"), ("YELLOW", "Yellow"))) wheels = forms.ChoiceField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["wheels"].choices = [(_, _) for _ in range(4)] When I bind the form with data, Django does not set the choice for the field with the dynamic choices to "selected": f = CarForm({"colour": "YELLOW", "wheels": 2}) f.is_valid() Out[10]: True f.as_p() Out[11]: ''' <p> <label for="id_colour">Colour:</label> <select name="colour" id="id_colour"> <option value="BLACK">Black</option> <option value="YELLOW" selected>Yellow</option> </select> </p> <p> <label for="id_wheels">Wheels:</label> <select name="wheels" id="id_wheels"> <option value="0">0</option> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select> </p> ''' I guess that's because the form's __init__ method is called before the choices are set, but I have to call __init__ first, otherwise the method complains with an AttributeError: 'CarForm' object has no attribute 'fields' I want to show the form with the user's input to the user so that they can see the result of their request and adapt accordingly. It's not very user friendly if the selections they made are not reflected in the form. How can I fix this? -
ImportError: cannot import name 'ReCaptchaField' from 'captcha.fields'
guys im trying to run django server but i have this error from captcha.fields import ReCaptchaField ImportError: cannot import name 'ReCaptchaField' from 'captcha.fields' what can i do im trying to remove and install django-ReCaptcha but nothing change -
¨WorkflowScript: 35: unexpected token: catch @ line 35, column 5¨ from Jenkins build job
Iḿ trying to deploy a build using the following Jenkins file but build job returned an error immediately. The jenkins file seems to be correct. The configuration is: We have App&WebServer on cloud instance1 and installation is owned by user: preProd We have Jenkins server on cloud instance2 and installation is owned by user: jenkins User: jenkins public key is added into instance1 and login without password is working fine The user/admin user in Jenkins web interface is ´testUser´ and using pipeline job with github key included The plan is to deploy a Django build on cloud instance1 jenkinsfile: #!groovy node { try { stage 'Checkout' sshagent(credentials : ['1000']) { sh 'ssh -o StrictHostKeyChecking=no preProd@xxx.xxx.xxx.xx uptime' sh 'ssh -v preProd@xxx.xxx.xxx.xx' } sh 'cd preprod-testP' sh 'pwd' sh 'ls' sh 'git init' sh 'git status' sh 'git pull https://xxxxxxxxxxxx:ghp_qwfaqwefdaf21asffasfas1e@github.com/testP/preprod-testP.git' sh 'git branch' stage 'Build' sh 'virtualenv env -p python3' sh '. env/bin/activate' sh '/home/preProd/preprod-testP/env/bin/pip freeze' sh '/home/preProd/preprod-testP/env/bin/pip install -r requirements.txt' stage 'Test' sh '/home/preProd/preprod-testP/env/bin/python manage.py makemigrations' sh '/home/preProd/preprod-testP/env/bin/python manage.py migrate' stage 'Deploy' sh 'JENKINS_NODE_COOKIE=dontKillMe nohup /home/preProd/preprod-testP/env/bin/python manage.py runserver 0.0.0.0:8000 &' sh 'echo "deployment is successfully completed."' sh 'sudo service gunicorn restart' sh 'sudo service nginx restart' } catch (err) { sh … -
How to create instance of a django model
views.py def create_post(request): profile_inst = Profile.objects.filter(author_real=request.user).first() print(profile_inst) if request.method == 'POST': print('POST request') form = CreatePost(request.POST,request.FILES) if form.is_valid(): print(request.FILES) form.save() else: print('JUST a VISIT!') form=CreatePost(initial={'author':profile_inst}) return render(request,'create_post.html',{'form':form}) ValueError at /create_post/ Cannot assign "'username | admin'": "Post.author" must be a "Profile" instance. Post Model class Post(models.Model): post_id = models.IntegerField(default=0) author = models.ForeignKey(Profile,on_delete=models.CASCADE,null=True,blank=True,default='') title = models.CharField(max_length=255,default="No Title") views = models.IntegerField(default=0) posted_on = models.DateTimeField(auto_now_add=True) thumbnail = models.ImageField(upload_to='images/',default='') content = RichTextField(default='',blank=True,null=True) def __str__(self): return f'{self.title}' CreatePost Model class CreatePost(ModelForm): thumbnail = forms.ImageField() title = forms.TextInput() author = forms.CharField(widget=forms.HiddenInput()) # author = forms.TextInput(widget=forms.HiddenInput()) class Meta: model=Post exclude=['views','posted_on','post_id'] above is my view to create post on the blog i'm making, but for some reason django is not accepting profile_inst as a Profile instance and givin' the error shown above. Please ignore the post_id field, that i just created for some purpose but is not yet being used yet as of my knowledge. appreciating any efforts! -
Django DRF use same URL pattern for different views
In Django Rest Framework, I have two separate views for the same model. I would like to use the same url pattern to access both views, and differentiate between the two based on the method that is used. So I have something like: class MyObjectListAPIView(generics.ListAPIView): pass class MyObjectCreateAPIView(generics.CreateAPIView): pass Both views obviously would have different logic. The url pattern for both would be 'myObjects\', and depending on the method that is used (GET or POST), it would need to refer to the appropriate view (MyObjectListAPIView or MyObjectCreateAPIView respectively). Is there a way to achieve this (without reverting to plain Django and losing the functionality of DRF)? -
"GET / HTTP/1.1" 404 405 error occurred when doing class-based-view in django
I tried to make two processes of uploading excel file and saving it into database by using class-based-view, but it occurred an error. views.py from django.shortcuts import render,redirect from django.http import HttpResponse, HttpResponseRedirect from .forms import UploadFileForm, InputForm from .models import Memo import pandas as pd from django.views import View # Create your views here. class upload_file_and_saving_to_database(View): def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request,'report/success.html') else: form = UploadFileForm() return render(request,'report/upload.html',{'form':form}) def saving_to_database(request): df=pd.read_excel(r'C:\Users\leeta\OneDrive\바탕 화면\TK project\myproject\media\upload\sample_file.xlsx') df_cp=df analysis_with_list=df_cp.query('출금액!=0') analysis_with_list=analysis_with_list.loc[:,['적요','출금액']] analysis_with_list=analysis_with_list.groupby(by=['적요']).sum() analysis_with_list.reset_index(drop=False, inplace=True) ss=[] for i in range(0,len(analysis_with_list)): st = (analysis_with_list['적요'][i]) ss.append(st) for i in range(0,len(analysis_with_list)): Memo.objects.create(memo=ss[i]) urls.py from django.urls import path from . import views from report.views import upload_file_and_saving_to_database urlpatterns=[ path("upload/",views.upload_file_and_saving_to_database.as_view(),name="upload"), the error occurred. Not Found: / [30/Dec/2023 15:39:10] "GET / HTTP/1.1" 404 2169 Method Not Allowed (GET): /report/upload/ Method Not Allowed: /report/upload/ [30/Dec/2023 15:39:15] "GET /report/upload/ HTTP/1.1" 405 0 How can I solve this problem? Please help. -
Can you please explain me the form_valid() function here?
class ArticleCreateView(CreateView): model = Article template_name = "article_new.html" fields = ("title", "body") # new def form_valid(self, form): # new form.instance.author = self.request.user return super().form_valid(form) I am reading a book and author is telling that to insert the author automatically we can use this function in our createview inherited class. But he didnt explained anything regarding this function. What is this for_valid() function? What it does? and specially the return line? -
TypeError: Object of type ndarray is not JSON serializable
frontend_data = {'message': 'Data filtering successfully.', 'data': column_data_dict, 'type': 'line_chart', 'column': selected_column} frontend_data.update({'context':context_data}) return JsonResponse(frontend_data) TypeError: Object of type ndarray is not JSON serializable Proper Solution, context_data update frontend_data data -
Django Formset Validation - Validation/saving across two formsets
User interaction: The user have the ability to input bilagsnr, account(konto), debet and kredit. Each bilag object can have several innslag objects. Each bilag can only be saved once, with its innslag objects. Within each bilag, the innslag fields of debet and kredit needs to have sum = 0. How do i solve this? Model: class Bilag(models.Model): bilagsnr = models.PositiveIntegerField(primary_key=True, unique=True) class Innslag(models.Model): innslagBilagsnr = models.ForeignKey(Bilag, on_delete=models.CASCADE) innslagKonto = models.ForeignKey(Kontoplan, on_delete=models.CASCADE) innslagDebet = models.PositiveIntegerField(blank=True, null=True) innslagKredit = models.PositiveIntegerField(blank=True, null=True) View: def bokforing(request): InnslagFormSet = formset_factory(form=InnslagForm, extra=3) if request.method == 'POST': formset = InnslagFormSet(request.POST) if formset.is_valid(): total_debet = 0 total_kredit = 0 for form in formset: if form.has_changed(): form.save(commit=False) debet_value = form.cleaned_data["innslagDebet"] kredit_value = form.cleaned_data["innslagKredit"] if debet_value is not None: total_debet += debet_value if kredit_value is not None: total_kredit -= kredit_value if total_debet + total_kredit == 0: return HttpResponse("Valid") else: return HttpResponse("Not Valid") else: formset = InnslagFormSet() return render(request, "bokforing.html", {'formset': formset}) Overview of validation: Have tried to use different models, forms and so forth. -
Django REST view creates new instead of updating object
I'm using the Django REST framework for the first time. It looks, from the documentation, like serialzer.save() updates an object when given a primary key and creates a new one when not. However, when I go to update an object it creates a new one. (I have not tried to create a new object yet). In serializers.py I have this: class ThingCurrentClassSerializer(serializers.ModelSerializer): active = serializers.BooleanField(read_only=True) class Meta: model = ThingCurrentClass fields = ['title', 'active', 'description_short', 'description_long', 'length_in_minutes', 'adult_only', 'adult_only_reason', 'handout_fee', 'handout_limit', 'material_fee', 'material_limit', 'fee_itemization', 'scheduling_notes', 'special_needs_notes', 'heat_source', 'topic', 'track', 'tags', 'private_camp'] In my views.py I have this: class ThingCurrentClassList(generics.ListCreateAPIView): queryset = ThingCurrentClass.objects.all() serializer_class = ThingCurrentClassSerializer renderer_classes = [TemplateHTMLRenderer] success_url = reverse_lazy('instructables/') template_name = 'thingcurrentclass_list.html' def get(self, request): queryset = ThingCurrentClass.objects.all() return Response({'thingcurrentclasses': queryset}) class ThingCurrentClassDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ThingCurrentClass.objects.all() serializer_class = ThingCurrentClassSerializer renderer_classes = [TemplateHTMLRenderer] template_name = 'thingcurrentclass_detail.html' success_url = reverse_lazy('instructables/') def get(self, request, pk): thingcurrentclass = get_object_or_404(ThingCurrentClass, pk=pk) serializer = ThingCurrentClassSerializer(thingcurrentclass) return Response({'serializer': serializer, 'thingcurrentclass': thingcurrentclass}) def post(self, request, pk): thingcurrentclass = get_object_or_404(ThingCurrentClass, pk=pk) serializer = ThingCurrentClassSerializer(thingcurrentclass, data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer, 'thingcurrentclass': thingcurrentclass}) serializer.save() return redirect('thingcurrentclass_list') In the thingcurrentclass_list.html template I have this: {% extends "base_generic.html" %} {% block content %} <html><body> <h1>Class List</h1> {% if thingcurrentclasses … -
Binding web version of pgadmin to gunicorn
I have a gunicorn file that is executing and correctly displaying the web together with nginx and supervisor SOCKFILE=/home/boards/run/gunicorn.sock exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- but in addition to that, now I need to add pgadmin so as to be reachable like this: myweb.com/pgadmin I have added a new location in my nginx file upstream app_server { server unix:/home/boards/run/gunicorn.sock fail_timeout=0; } Here below is the new added snippet: location /pgadmin { proxy_pass http://app_server; include proxy_params; } but I get a 404 when I try to reach www.myweb.com/pgadmin what am I missing? do I have to create a separate gunicorn file? do I just have to add another bind command to that gunicorn snippet as shown and if yes how? thanks -
Trouble with CSRF token validation in python django
enter image description hereI'm currently working on a travel management using python django and I'm having issues with CSRF token validation. I've implemented CSRF protection in my application, but for some reason, it's not working as expected.if login with a user csrf issue were risen what is the reason for this but i give the csrf verification for the login page then what is the reason may occur this -
Select for update through a foreign key
models STATUSES = ( (FAILED_STATUS, "Failed"), (DONE_STATUS, "Done"), (PENDING_STATUS, "Pending"), (BANK_ACCEPTANCE, "Bank Acceptance"), ) amount = models.BigIntegerField() status = models.CharField(max_length=20, default=PENDING_STATUS, choices=STATUSES) wallet = models.ForeignKey("Wallet", on_delete=models.PROTECT) timestamp = models.DateTimeField(null=True, blank=True) class Wallet(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) uuid = models.UUIDField(default=uuid.uuid4, unique=True) balance = models.BigIntegerField(default=0) def deposit(self, amount: int): self.balance = F("balance") + amount self.save() Task @shared_task def perform_tx_periodic(): accpeted_tx = Transaction.objects.select_related("wallet__owner").select_for_update().filter( status="bank_acceptance", timestamp__lte=timezone.now() ) with transaction.atomic(): for tx in accpeted_tx: wallet = Wallet.objects.select_for_update().get(id=tx.wallet_id) if tx.amount < wallet.balance: logger = Logger(user=tx.wallet.owner) wallet.balance = F("balance") - tx.amount wallet.save(update_fields=["balance"]) tx.status = tx.DONE_STATUS logger.withdraw_log(amount=tx.amount) else: tx.status = tx.FAILED_STATUS tx.save(update_fields=["status"]) for query in connection.queries: print(query["sql"]) how can i lock wallet objects through foreign key on transaction model? this code has query n+1 i want to decrease queries after all, is there any way to optimize this task? for example, decrease volume of code, or perform fewer query consider this: each wallet, may have multiple transaction at same time, so if i don't lock each wallet row, i may have non-positive balance in my wallet. we should handle the this situation to -
there has been an admin login error in my code
enter image description here i am not able to see the admin login page i have made seperate pages one named hello and the other my app home i am very new to django [enter image description here](https://i.stack.imgur.com/Muife.png) enter image description here here are some of the screenshots of my code to make it seem better -
New event loop per request Django+ASGI
I got new event loop on each request even if i use daphne as my server with Django. view: async def main_page(request): loop = asyncio.get_running_loop() return HttpResponse(id(loop)) settings: ASGI_APPLICATION = 'project.asgi.application' start server: daphne project.asgi:application or python manage.py runserver (daphne first in installed apps) Logs: Starting ASGI/Daphne version 4.0.0 development server at 127.0.0.1:8000 deps: python==3.10 django==4.2.8 daphne==4.0.0 asgiref==3.7.2 It works like I'm using WSGI server - new loop on each request (according to new loop id). But id should be the same, isn't it? How can i fix it?