Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 Bad Gateway / gunicorn.socket: Failed with result 'service-start-limit-hit' | Django, Postgres, Nginx, Gunicorn ,Ubuntu 20.04
I went through a instruction - https://arctype.com/blog/install-django-ubuntu/ The result id 502 BadGateway ` root@1104941-ch54462:~/django_project# systemctl status gunicorn.socket ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: failed (Result: service-start-limit-hit) since Tue 2022-11-15 16:21:55 MSK; 5s ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) Nov 15 16:21:37 1104941-ch54462.tmweb.ru systemd[1]: Listening on gunicorn socket. Nov 15 16:21:55 1104941-ch54462.tmweb.ru systemd[1]: gunicorn.socket: Failed with result 'service-start-limit-hit'. ` ` 2022/11/15 16:17:35 [error] 11517#11517: *2 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 195.224.49.226, server: 1104941-ch54462.tmweb.ru, request: "GET /admin HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin", host: "1104941-ch54462.tmweb.ru" 2022/11/15 16:20:54 [error] 11517#11517: *5 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 195.224.49.226, server: 1104941-ch54462.tmweb.ru, request: "GET /admin HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin", host: "1104941-ch54462.tmweb.ru" 2022/11/15 16:21:07 [alert] 11517#11517: *7 open socket #14 left in connection 4 2022/11/15 16:21:07 [alert] 11517#11517: aborting 2022/11/15 16:21:55 [error] 11599#11599: *2 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 195.224.49.226, server: 1104941-ch54462.tmweb.ru, request: "GET /admin HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin", host: "1104941-ch54462.tmweb.ru" ` What is the problem ? -
Django Logging: ValueError: Unable to configure handler 'gunicorn'
I configured logging for a new Django project, and here is the code for my settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "warnfile": { "level": "WARNING", "class": "logging.FileHandler", "filename": BASE_DIR / "warning.log", "maxBytes": 1024 * 1024 * 25, # 100 mb }, "errorfile": { "level": "ERROR", "class": "logging.FileHandler", "filename": BASE_DIR / "error.log", "maxBytes": 1024 * 1024 * 25, # 100 mb }, "gunicorn": { "level": "DEBUG", "class": "logging.handlers.RotatingFileHandler", "formatter": "verbose", "filename": BASE_DIR / "gunicorn.log", "maxBytes": 1024 * 1024 * 25, # 100 mb }, }, "loggers": { "": { # keeping it empty for all kinds of loggers "handlers": [ "warnfile", "errorfile", ], "level": "WARNING", "propagate": True, }, "gunicorn.errors": { "level": "DEBUG", "handlers": ["gunicorn"], "propagate": True, }, }, } Let me explain: I want to put 2 kinds of logs: warnings, and errors, in 2 differents files. I also want a third file for gunicorn logs to monitor the server side. When I run the server, I get the following error: ValueError: Unable to configure handler 'gunicorn' I also created all the files just in case the logger does't create them for me, but still no changes. Here is my full traceback: Exception in thread django-main-thread: Traceback … -
Required path doesn't exist: /code/bower_components/trix/dist/trix.css trix. Nodejs wont build. How do add trix?
After using the comand "docker system prune -a" nodejs wont build anymore beacuse trix.css is missing. This was probably deleted which pruning. How can I resolve this error (see the screenshot below)? Screenshot of the Error -
Django: How to create an tabular inline like the one in admin panel with "+ Add another"?
I currently rely on the admin panel to create or edit a new/existing order (i.e. Order with its children model OrderItem in the tabular inline). But this time I need to create a view with the same function for non-admin users. More specifically, I need the + Add another button in the tabular inline for users to add more Order Items themselves when necessary. I have looked into a few stackoverflows (one of them) and books. So far they at most only mentioned about inlineformset_factory, but not how to create the + Add another. Any ideas please? Thank you! -
How can I create an book index with Python?
I have a section, and in this section, I have topics, for example, book chapters. But, on this section page, I only have the last three chapters, so, when I click, I can move forward to the single page where I am. This is my HTML template. <ul> {% for chapter in book %} <li> <a href="#{{ chapter }}">{{ chapter }}</a> </li> {% endfor %} </ul> But, how can I access a section in example/book?page=2#chapter_five? I tried to create a function to find the chapter in a for loop with all the pages, but I got that the object was not iterable. I tried it in my views. chapter = chapters.object_list chapters_pages = paginator.num_pages for page in chapters_pages: if page.contains(chapter): context["chapter_page"] = page So I could do it, but it not worked. <ul> {% for chapter in book %} <li> <a href="?page=chapter_page#{{ chapter }}">{{ chapter }}</a> </li> {% endfor %} </ul> -
I can't get any mail from Django send_mail? Where is my mistake?
I am trying to send a mail using Django send_mail() but I can't get any mail from Django send_mail? Where is my mistake? if request.method == "POST": depName = request.POST.get("sedep") Pname = request.POST.get("name") Pmail = request.POST.get("mail") docName = request.POST.get("sedoc") Pphone = request.POST.get("phone") AppointDate = request.POST.get("date") appointment_list = Appointment_List(se_dept = depName, se_doc = docName, patient_name = Pname, patient_phone = Pphone, patient_email = Pmail, calendar = AppointDate) appointment_list.save() # SEND EMAIL subject = 'Your appointment status!' message = 'hello '+ Pname + '! \n' + 'Welcome to Doctor appointment system.\n'+ 'Congratulations your appointment is booked.\n\n Thanking you Team malloc()' from_email = settings.EMAIL_HOST_USER to_list = [Pmail] send_mail(subject,message,from_email,to_list,fail_silently = True) EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'sa3518548@gmail.com' EMAIL_HOST_PASSWORD = 'uqnoifwqucnlefgp' EMAIL_PORT = 587 -
data in my table but it is not showing in django admin
I have data in my table but it is not showing in admin. I started by creating the model from django.db import models class VilleStation(models.Model): nomVille = models.CharField(max_length=255) adresse = models.CharField(max_length=255) cp = models.CharField(max_length=5) def __str__(self): return self.nomVille then in the admin.py I did this from django.contrib import admin from prixcarbu.models import VilleStation class VilleStationAdmin(admin.ModelAdmin): list_display = ('nomVille', 'adresse','cp',) fields = ('nomVille', 'adresse','cp',) admin.site.register(VilleStation, VilleStationAdmin) then I imported via db browser for sqlite a csv file. I see in my base the table correctly filled but in the admin I have nothing. thank for any help. -
HTML can't find JS script in the same folder [closed]
I'm using Django framework I have home.html: <head> </head> <body> <div> <button onclick="test()">Test button</button> </div> <script type="text/javascript" src="utils/htmlScript.js"></script> </body> And htmlScript.js: function test() { alert('hey there') } It cannot get simpler than this. Still, when I load the page I get this log: [15/Nov/2022 21:13:25] "GET /myapp/ HTTP/1.1" 200 147519 Not Found: /myapp/utils/htmlScript.js [15/Nov/2022 21:13:25] "GET /myapp/utils/htmlScript.js HTTP/1.1" 404 2349 My htmlScript.js file is in the folder /myapp/utils/htmlScript.js 100%. I have also tried to put it on the same folder as home.html and put src="htmlScript.js" but it doesn't work either. Can someone guide me on this? Thanks -
Images are disappearing from media folder(i think) after some time after uploading them, app deployed on digital ocean
I have an option for users to upload images from frontend which then gets uploaded in the media folder. But after sometime I notice that the images are disappearing and only the text that I get is remaining. Why is that happening? -
Using related_name instead of name.Class python Django(related_name=favorites)
My reviewer wants me to use related_name instead of referring to Class model! ` @admin.register(Recipe) class RecipeAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'author', 'favorites'] search_fields = ['name', 'author__username'] list_filter = ['tags'] empty_value_display = EMPTY inlines = ( IngredientsInLine, ) def favorites(self, obj): if Favorite.objects.filter(recipe=obj).exists(): return Favorite.objects.filter(recipe=obj).count() return 0 `` I did this: ` def favorites(self, obj): recipe = obj['recipe'] if obj.favorites(recipe=recipe).exists(): return obj.favorites(recipe=recipe).count() return 0 But I do not know if this is correct. -
Post data (dictionary list) with python requests
I'd like to post my dictionary list below via python's http requests. my_data=[ { 'kl':'ngt', 'schemas': [ { 'date':'14-12-2022', 'name':'kolo' } ], }, { 'kl':'mlk', 'schemas': [ { 'date':'23-10-2022', 'name':'maka' } ] } ] trying to do url='http://myapi.com/product x=requests.post(url,json=my_data) after execution it does not post the products on the database -
App not loading error while executing commands
` dam 2022-11-15 18:05:49,686 - adam - INFO - Welcome to ADAM, Finquest's Application for Data Annotation Management! Traceback (most recent call last): File "/home/finq/miniconda3/envs/adam/bin/adam", line 33, in <module> sys.exit(load_entry_point('adam', 'console_scripts', 'adam')()) File "/home/finq/miniconda3/envs/adam/bin/adam", line 25, in importlib_load_entry_point return next(matches).load() File "/home/finq/miniconda3/envs/adam/lib/python3.10/importlib/metadata/__init__.py", line 171, in load module = import_module(match.group('module')) File "/home/finq/miniconda3/envs/adam/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/finq/review/106_review/adam/adam/__main__.py", line 6, in <module> from adam.common.common import check_database_exists File "/home/finq/review/106_review/adam/adam/common/common.py", line 9, in <module> from adam.graphical_user_interface.db_graphical_user_interface.models import UserLogin File "/home/finq/review/106_review/adam/adam/graphical_user_interface/db_graphical_user_interface/models.py", line 5, in <module> class UserLogin(models.Model): File "/home/finq/miniconda3/envs/adam/lib/python3.10/site-packages/django/db/models/base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) File "/home/finq/miniconda3/envs/adam/lib/python3.10/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/home/finq/miniconda3/envs/adam/lib/python3.10/site-packages/django/apps/registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. ` I tried everything from path ,run migrtaions ,migrate but nothing helped . Please help to reoslve this . Thanks I tried everything from path ,run migrtaions ,migrate but nothing helped . Please help to reoslve this . Thanks … -
Django | Only show foreign keys not already assigned in django form
Im making a booking system in django where the user picks a date and then is able to see what times are available on that date. Models.py class Slot(models.Model): title = models.CharField(max_length=50) def __str__(self): return f'There is a slot at {self.title}' class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slot = models.ForeignKey(Slot, on_delete=models.CASCADE, null=True, blank=True, related_name='all_times') booking_date = models.CharField(max_length=15, default='foo') def __str__(self): return f'{self.user} has booked a session at {self.slot.title} on {self.booking_date}' Where the Slot model is they times that are available to pick(e.g. 9-10, 1-2 etc.) Views.py def DateView(request): form = DateForm(request.POST or None) if form.is_valid(): request.session["dateSelected"] = str( form.cleaned_data["booking_date"]) return redirect('../create/') context = { 'form': form } return render(request, "bookingapp/date_form.html", context) def BookingView(request): instance = Booking(booking_date=request.session.get('dateSelected')) form = BookingForm(request.POST or None, instance=instance) if form.is_valid(): form.save() form = BookingForm context = { 'form': form } return render(request, "bookingapp/book_form.html", context) Forms.py class DateInput(forms.DateInput): input_type = 'date' class DateForm(forms.ModelForm): class Meta: model = Booking fields = [ 'booking_date', ] widgets = {'booking_date': DateInput()} class BookingForm(forms.ModelForm): class Meta: model = Booking fields = [ 'user', 'slot', 'booking_date', ] widgets = {'booking_date': forms.HiddenInput()} The first form lets the user select a date, which then brings them to the second form where they can choose what … -
In Linux, how to run Django custom management using crontab?
I have generated a bash script that activates virtaulenv and runs my custom management command in Django. I want to run the bash script every day at midnight. Bash Script : cd ~ cd path_to_virtualenv/ source virtualenv_name/bin/activate cd path_to_project/ python manage.py custom_command deactivate When I run this script using . or source it runs perfectly. I have configured crontab to run this bash script (For testing, I have set execution time per minute). But I am not getting desired output. crontab -e */1 * * * * source /path_to_bash_script/bash_script_filename -
Is django's SCRIPT_NAME applied to STATIC_URL?
I'm serving django with gunicorn and nginx. And I've observed a strange behavior, which looks like django is prefixing MEDIA_URL with SCRIPT_NAME but it is not prefixing the STATIC_URL. Am I handling it properly? My static's configuration: STATIC_URL = "backend/static/" # this looks odd but works STATIC_ROOT = "/var/www/static" STATICFILES_DIRS = [BASE_DIR / "static"] MEDIA_URL = "media/" # this looks fine MEDIA_ROOT = "/var/www/media" gunicorn configuration: [Service] User=www-data Group=www-data Environment="DJANGO_SETTINGS_MODULE=backend.settings.production" WorkingDirectory=/var/www/backend ExecStart=/var/www/backend/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ backend.wsgi:application nginx configuration: location ^~ /backend { proxy_set_header SCRIPT_NAME /backend; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; location ^~ /backend/static { alias /var/www/static/; } location ^~ /backend/media { alias /var/www/media/; } } -
Django 'DetailView' object has no attribute '_meta'
This has floored me. I'm building a model with Django & REST API, and I'm having trouble rendering the DetailView for individual cars to the browser. The ListView works fine, but I'll include the code too since they are interlinked. In particular, I can't get the get_object() function to work properly. The first approach I tried used this approach: views.py class CarDetailView(generics.RetrieveUpdateDestroyAPIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'car-detail.html' queryset = Car.objects.all() lookup_field = Car.id @action(detail=True, renderer_classes=[TemplateHTMLRenderer]) def get(self, request, *args, **kwargs): car = self.get_object() return Response({ 'car': car, }) While the page rendered properly with no errors, none of the template tags worked. Only {{ car.model }}, which returned None. So I changed the code to use a self.get_object() class CarDetailView(generics.GenericAPIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'car-detail.html' queryset = Car.objects.all() lookup_field = Car.id def get(self, request, id): serializer_class = CarSerializer car = self.get_object() id = Car.id return Response({ 'car': car, }) but that raises the Error: "AttributeError at /rentals/car/43c9b98d-9f2d-473f-9c34-7b2e25630278 'CarDetailView' object has no attribute '_meta'" Can you help with this? I've looked through most of the previous questions here (that's where I learned to pass the self into the get function etc...) but I'm still stuck. Here's the code: views.py … -
how to processing and loading data after rendering page in django
I have a dashboard page with some charts(image_link) For earning charts data, i'm using some queries but this queries are very heavy and take long time(for example 37 seconds!). Is exist a way for rendering page(with showing loading animation on charts) and after that start taking data process? -
Regarding BERT Arch during model deployment
I am begginer in NLP Transformers. I am facing this issue while deploying model using Django framework.Locally model is working fine but not when deployed. Here I am importing BERT model which was trained and saved using pytorch same procedure i follow to load the model but before I am defining the architecture which was defined during model training. But facing the issue after deploying the model. AttributeError: Can't get attribute 'BERT_Arch' on <module 'main' from '/home/ubuntu/kc_env/bin/gunicorn'> I tried couple of things: Like defining the BERT Architecture before model loading: ####Utils.py from django.apps import AppConfig # import torch import torch.nn as nn class BERT_Arch(nn.Module): def __init__(self): super(BERT_Arch, self).__init__() # dropout layer self.dropout = nn.Dropout(0.2) # relu activation function self.relu = nn.ReLU() # dense layer self.fc1 = nn.Linear(768,512) self.fc2 = nn.Linear(512,256) self.fc3 = nn.Linear(256,3) #softmax activation function self.softmax = nn.LogSoftmax(dim=1) #define the forward pass def forward(self, sent_id, mask): cls_hs = self.bert(sent_id, attention_mask=mask)[0][:,0] x = self.fc1(cls_hs) x = self.relu(x) x = self.dropout(x) x = self.fc2(x) x = self.relu(x) x = self.dropout(x) # output layer x = self.fc3(x) # apply softmax activation x = self.softmax(x) return x ###main.py from .utils import BERT_Arch model=BERT_Arch() def func(): model=torch.load('Path to load model.pt') -
How to Merge dictionaries in python from a for loop
I would like to merge two dictionaries this way below: dict1={ 'kl:'ngt', 'schemas': [ { 'date':'14-12-2022', 'name':'kolo' } ] } dict2={ 'kl':'mlk', 'schemas': [ { 'date':'14-12-2022', 'name':'maka' } ], } then I create a variable that will group the two dictionaries in this way all_dict={ 'kl':'ngt', 'schemas': [ { 'date':'14-12-2022', 'name':'kolo' } ], 'kl':'mlk', 'schemas': [ { 'date':'23-10-2022', 'name':'maka' } ] ...... } How to get this result. I'm stuck right now please help me if possible -
Mezzanine 6.0 shows unclear page history
I've been upgrading my application from python-2.7/django1.8/mezzanine4.2 to python3.8/django3.2/mezzanine6.0. Now I've met problem in page history; it user to show pretty page history in the original environment, but in the new environment it shows like in the attachment. I've repeated the problem in a small sample mezzanine project in git hub https://github.com/miettinj/mezzanine/tree/main/mezzanine_app, please let me know how to fix! -
Selenium doesn't show up my data after I submitted a form
The following test was written as a starting point for learning Selenium, the final test was added to ensure that the player's name appeared on the screen. While everything works great manually, the data I enter in Selenium doesn't show up on the screen. test.py from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys class PlayerFormTest(LiveServerTestCase): def testform(self): selenium = webdriver.Firefox() # choose the URL to visit selenium.get('http://127.0.0.1:8000/') # find the elements needed to submit form player_name = selenium.find_element('id', 'id_name') player_height = selenium.find_element('id', 'id_height') player_team = selenium.find_element('id', 'id_team') player_ppg = selenium.find_element('id', 'id_ppg') submit = selenium.find_element('id', 'submit_button') # populate the form with the data player_name.send_keys('Russel Westbrook') player_height.send_keys('6 feet 3 inches') player_team.send_keys('Los Angeles Lakers') player_ppg.send_keys('27.3') # submit form submit.send_keys(Keys.RETURN) # check if the player's name appears on the screen assert 'Russel Westbrook' in selenium.page_source Error: Traceback (most recent call last): File "/home/.../dj_selenium/main/tests.py", line 31, in testform assert 'Russel Westbrook' in selenium.page_source AssertionError Your help is much appreciated! -
what's the difference between Modelobject.id and Modelobject_id in django?
want to know the difference between Modelobject.id and Modelobject_id in Python django. Tried both and they both work the same. -
An issue while doing django orm
So here is my issue, instance.field_name or instance.save() not working on else condition. Below code: coupon = Coupon.objects.get(id=id) coupon_used = CouponUsedUser.objects.get(coupon=coupon, user=request.user, is_used=True) discount = coupon_used.coupon if coupon_used: coupon_price = total else: deduction = discount.discount_amount(total) coupon_price = total - deduction grand_total = coupon_price + delivery coupon_used.is_used = ---> #This won't work coupon_used.save() ---> #This won't work But if add those conditions inside if conditon it works. coupon = Coupon.objects.get(id=id) coupon_used = CouponUsedUser.objects.get(coupon=coupon, user=request.user, is_used=True) discount = coupon_used.coupon if coupon_used: coupon_price = total coupon_used.is_used = ---> #This works coupon_used.save() ---> #This works else: deduction = discount.discount_amount(total) coupon_price = total - deduction grand_total = coupon_price + delivery I exactly don't know why is this happening. Please explain it. -
Which version of Django rest framework for Django 2.1.5?
I am working with an old django version, and I can't identify which version of django rest framework I would need for a Django 2.1.5 I can't find this information in the official django-rest-framework documentation Thanks -
Form Validation passed but Model validation Failed and still the error is showing at form. Can anyone explain?
I have a model Books with one field 'name' and i have set max_length to 10. class Books(models.Model): name = models.CharField(max_length=10) However, in the modelform BookForm i have defined the max_length to 20. class BookForm(forms.ModelForm): name = forms.CharField(max_length=20) class Meta: fields = ['name'] model = Books Now while submitting the form with more than 10 length it gives me error saying that the field can at most 10 characters. def book(request): if request.method == 'POST': fm = BookForm(data=request.POST) print(fm.is_valid()) print(fm) if fm.is_valid(): fm.save() return render(request, 'enroll/books.html', {'form':fm}) fm = BookForm() return render(request, 'enroll/books.html', {'form':fm}) enter image description here Can anyone explain why this is happening and any specific article or link where i can read how the model form and models work with each other in terms of validation.