Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configuring Apache as a Reverse Proxy for a Django App in a Docker Container: Serving Static Files
I have Django app that runs in docker container. I have a problem with serving static files with my Apache configuration. My django app works inside docker container and Apache correctly routes requests to it I made sure to set STATIC_URL = "/static/" and DEBUG = False settings properties I made sure to collect static to /var/www/my_app/static/ directory I made sure that directory /var/www/my_app has correct acccess rights for apache: drwxr-xr-x 3 www-data www-data 4,0K June 11 16:25 my_app This is my apache config: <VirtualHost 000.00.0.000:443> ServerName my_app.com SSLEngine on SSLProxyEngine on SSLCertificateFile /etc/apache2/certs/cert.pem SSLCertificateKeyFile /etc/apache2/certs/cert.key SSLCACertificateFile /etc/apache2/certs/DigiCertCA.crt CustomLog /var/log/apache2/my_app.log combined ErrorLog /var/log/apache2/my_app.log ProxyPass /static ! Alias /static/ /var/www/my_app/static/ <Directory /var/www/my_app/static/> Require all granted </Directory> <Location /> ProxyPass http://localhost:6000/ ProxyPassReverse http://localhost:6000/ ProxyPreserveHost on </Location> </VirtualHost> Could you help me please to resolve the issue? -
how to create a django form with names from the database
I have a sidebar with a drop-down menu that has categories and dishes. I want to create a checkbox for selection dishes models.py class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Dish(models.Model): category = models.ForeignKey(to=Category, related_name="children", on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=500) weight = models.IntegerField() cost = models.IntegerField() def __str__(self): return self.name in html format it looks like this: <div class="filter-content collapse show" id="collapse_1" style=""> <ul class="list-unstyled ps-0"> {% if category %} {% for cat in category %} <li class="mb-1"> <button class="btn btn-toggle d-inline-flex align-items-center rounded border-0 collapsed" data-bs-toggle="collapse" data-bs-target="#{{ cat.id }}" aria-expanded="false"> {{ cat.name }} </button> {% for dish in cat.children.all %} <div class="collapse" id="{{ cat.id }}" style=""> <ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small"> <li> <div class="list-group list-group-checkable d-grid gap-2 border-0"> <input class="list-group-item-check pe-none" type="checkbox" name="listGroupCheckableRadios" id="{{dish.name}}" value=""> <label class="list-group-item rounded-3 py-3" for="{{dish.name}}"> {{dish.name}} </label> </div> </li> </ul> </div> {% endfor %} </li> {% endfor %} {% else %} <p>no values</p> {% endif %} </ul> </div> to handle clicking on the checkbox, I create a form: class DishForm(ModelForm): class Meta: model = Basket fields = ['dish'] widgets = {"dish": CheckboxInput(attrs={ 'class': 'list-group-item-check pe-none', 'type': 'checkbox', }) } and added this form to html <div class="filter-content collapse show" id="collapse_1" … -
How to host 2 server in one Azure App Service?
I'm having a web app which is based on ReactJS (Frontend) + Django (Backend), I've integrated ReactJS with Django and make it as single server based application. I have 1 more server which is based on Express JS separately. I'm trying to host my web application in Azure app service and publisher is Docker Container. So, I am hosting React + Django based web app in 1 app services it is successfully getting hosted along with the SSL certificates. Now, I am trying to host Express JS in same web app in which I hosted React + Django based web app since Django + React is running on port 80 . I am not able to host Express JS in same app service and if I am trying to host Express JS on separate app service, it is getting hosted but now domain is changed or there need to be some subdomain which I don't want. PROBLEM: I want to host both Django+React server and Express JS server in same app service in which my main web-app is hosted. Any help or any leads are highly appreciated -
While activating the user in django using the token and uid, there getting the following error, why? [closed]
File "/home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages/django/utils/deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "/home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'str' object has no attribute 'get' [12/Jun/2023 06:25:59] "GET /active/MTI/bpo4iw-68499ed18b0290d6aae65a8b727abb33/ HTTP/1.1" 500 66953 and this is my page AttributeError at /active/MTI/bpo4iw-68499ed18b0290d6aae65a8b727abb33/ 'str' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:7000/active/MTI/bpo4iw-68499ed18b0290d6aae65a8b727abb33/ Django Version: 4.2.1 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'get' Exception Location: /home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages/django/middleware/clickjacking.py, line 27, in process_response Raised during: user.views.active Python Executable: /home/cybermate/Desktop/NewProject/env/bin/python3 Python Version: 3.10.6 Python Path: ['/home/cybermate/Desktop/NewProject/eshopy', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/cybermate/Desktop/NewProject/env/lib/python3.10/site-packages'] Server time: Mon, 12 Jun 2023 06:25:59 +0000 i tried a lot can you mension what should and why this happening. could you explain? -
How to view the progress of the django app in the browser
I want the process of the app to be dispayed in the browser so that suers know how much it has been done. However, in django, the view receives the event that occurred in the template(browser) and passes it back to the template, so I don't know how to pass it from the view itself to the template. For example, when the user clicks a button, a total of 3 fuctions are executed in trun. At this time, I want to show 'End of function1, start of function 2' when fuction 1 ends. it same way for fuction2,3. I'm not sure if I should do this in view or make it in JS. The functions runs in python. I'm not familiar with django, so this might be a very rudimentary question. Please Help me :) The fuctions are performed in the view in order, and when each function is completed, render or redirect is perfomed to template. but it is expressed only at the first fuction and does not proceed any further. -
Find out which field a file is being uploaded to
def _image_directory_path(instance, filename): pass class TreatyParagraph(CommentMixin, models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) english = models.TextField(blank=False, null=False, default="") english_img = models.ImageField(blank=True, null=False, default="", upload_to=_image_directory_path) spanish = models.TextField(blank=True, null=False, default="") spanish_img = models.ImageField(blank=True, null=False, default="", upload_to=_image_directory_path) I want to organize file storage like this: 253e8498-7859-4490-b8ff-644f928607e5 en.png sp.png Depending on the field I'd like to rename the file (english_img corresponds to en.png etc.). The problem is that I have failed to find out which field a file belongs to. If only I could determine which field a file is being uploaded to, I'd just sliced the first two letters. Could you help me? -
Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused
celery -A video_subtitle worker --loglevel=info ` -------------- celery@user-Inspiron-15-3520 v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.19.0-43-generic-x86_64-with-glibc2.35 2023-06-12 05:44:21 *** --- * --- ** ---------- [config] ** ---------- .> app: video_subtitle:0x7fbb41f5dde0 ** ---------- .> transport: redis://localhost:6379// ** ---------- .> results: *** --- * --- .> concurrency: 12 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery ` [tasks] . video.tasks.process_video . video_subtitle.celery.debug_task [2023-06-12 05:44:21,877: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 2.00 seconds... (1/100) [2023-06-12 05:44:23,883: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 4.00 seconds... (2/100) [2023-06-12 05:44:27,889: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 6.00 seconds... (3/100) [2023-06-12 05:44:33,898: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 8.00 seconds... (4/100) [2023-06-12 05:44:41,909: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 10.00 seconds... (5/100) [2023-06-12 05:44:51,924: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again … -
All static assets not loading - Django, Gunicorn, NGINX
I am running Ubuntu 22.04, gunicorn, django, and nginx. Everytime I load the main page: http://dev.api.afisado.com, none of the CSS is loaded and the js is executed. From the developer tab in chrome I see a 404 not found. I'm not sure what to do. Folder Structure is like this: `/home/devbackend_directory/core/static/ Inside static I have assets. Inside assets I have css, js, and img files. Here is what my settings.py looks like: STATIC_URL = '/static/' STATIC_ROOT = '/home/devbackend_directory/core/static/' MEDIA_ROOT = '/home/devbackend_directory' MEDIA_URL = '/media/' server listen 80; server_name dev.api.afisado.com; location = /favicon.ico { access_log off; log_not_found off;} location static/ { root /home/devbackend_directory/core/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } and here is my gunicorn service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ali Group=www-data WorkingDirectory=/home/devbackend_directory/core/ ExecStart=/usr/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ core.wsgi:application [Install] WantedBy=multi-user.target ` -
Im not able to get post values through my django view
I'm new to django and I made a custom view for logging in, but no matter my post request, The function never gets username nor password. Here is my view: @csrf_exempt def custom_login(request): if request.method == 'POST': username = request.POST.get("usuario") password = request.POST.get("clave") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return JsonResponse({'success': True}) else: return JsonResponse({'success': False, 'message': 'Invalid credentials', 'username': username, 'password': password}) Also here is my url patterns in urls.py urlpatterns = [ # asocia la raiz del proyecto con el index.html path("", views.index, name="index"), # asocia las rutas creadas previamente por el enroutador Router path('', include(router.urls)), # incluye rutas de autenticacion de usuario de Django path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('admin/', admin.site.urls), path('custom-login/', custom_login, name='custom_login'), ] I've tried using postman for making the request, I expect a successful login but always get unsuccesful. When I debug username and passwords values in python i always get None. If i change it manually to a real user string it logs in successfully -
Issue with exited containers named "django-run-{uuid}" when switching interpreters in PyCharm
I have connected PyCharm with a docker-compose container for debugging multiple services. However, changing the interpreter creates exited containers named "django-run-{uuid}". I have investigated and it doesn't seem to be a persistent issue with PyCharm. There are no syntax problems in the Dockerfile or docker-compose configuration files either. I'm curious to know if this is a natural occurrence during the interpreter refresh process in PyCharm or if it is an artificially induced problem. If it is artificially induced, I would like to know where to look for the source of the issue. -
Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'publicPath'
I've been trying to merge Vue and Django for a long time, but my efforts are even. Here is the error that I can't solve for a long time: ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'publicPath'. These properties are valid: object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? } Do you have any options for solving this problem? Maybe there is another way to combine them. Vue.config.js var BundleTracker = require('webpack-bundle-tracker') var WriteFilePlugin = require('write-file-webpack-plugin') module.exports = { outputDir: (process.env.NODE_ENV === "production" ? 'dist' : 'static'), publicPath: '/', devServer: { publicPath: "http://localhost:8080/", headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Access-Control-Request-Headers, Access-Control-Request-Method", "Access-Control-Allow-Credentials": "true" } }, chainWebpack: config => { config.optimization.splitChunks({ cacheGroups: { vendors: { name: 'chunk-vendors', test: /[\\\/]node_modules[\\\\/]/, priority: -10, chunks: 'initial' }, common: { name: 'chunk-common', minChunks: 2, priority: -20, chunks: 'initial', reuseExistingChunk: true } } }) }, configureWebpack: { output: { filename: 'js/[name].js', chunkFilename: 'js/[name].js' }, plugins: … -
JSONDecodeError at /send-notif/ Expecting value: line 1 column 1 (char 0) while sending notification using firebase in django
JSONDecodeError at /send-notif/ Expecting value: line 1 column 1 (char 0) code `def send_notification(registration_ids , message_title , message_desc): fcm_api = "" url = "https://fcm.googleapis.com/fcm/send" headers = { "Content-Type":"application/json", "Authorization": 'key='+fcm_api } payload = { "registration_ids" :['e1aLmMZPeegz36PP3KUw0t:APA91bGjoJBwraENbW9PHsE5IUVIh_lLhnPI99qqr_VewvRFLjbJbu_vcSfT0dk4Tu4CGbcvUfR-x8INAkqovEDuJB4OdQma2NrEPsGufjtrsizYskD_ANCpKjT5wltIAfzJkbjY0YAV'], "priority" : "high", "notification" : { "body" : "message desc", "title" : "message_title", "image" : "https://i.ytimg.com/vi/m5WUPHRgdOA/hqdefault.jpg?sqp=-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLDwz-yjKEdwxvKjwMANGk5BedCOXQ", "icon": "https://yt3.ggpht.com/ytc/AKedOLSMvoy4DeAVkMSAuiuaBdIGKC7a5Ib75bKzKO3jHg=s900-c-k-c0x00ffffff-no-rj", } } result = requests.post(url, data=json.dumps(payload), headers=headers ) print(result.json())` not able to send notifications to my user -
barcode reading with mobile camera in python django
I am trying to access mobile camera for bar code scanner for a project in python django and connect to mssql server. In which way I can use this. Anybody can guide me. I have tried Quagga and jquery. But it is not working. help in python django -
Django with False sending error message through email 10 times on a single error
Here is the code: server_error function in core url. def server_error(request): """ Custom error handler for reporting errors to the superuser via email and sending the detailed error response. """ if request.method in ('GET', 'POST'): subject = f"Error on {request.get_host()}" user = request.user if request.user.is_authenticated else None # Include username and user ID in the subject if the user exists if user: subject += f" - User: {user.username} (ID: {user.id})" # Generate the detailed error response response = technical_500_response(request, *sys.exc_info(), status_code=500) # Capture the HTML content html_content = response.content.decode('utf-8') # Send the email with the error details email = EmailMessage(subject, body=html_content, from_email='noreply@questionsbank.net', to=[settings.DEBUG_EMAIL]) # Set the content type to HTML email.content_subtype = 'html' # Send the email email.send() error_email_sent = True # Raise an exception to trigger the error handling (optional) raise Exception("Server Error") handler500 = 'project.urls.server_error' fake_error_view which is set to http://127.0.0.1:8000/fake-error/ def fake_error_view(request): raise ValueError("This is a fake error!") If debug is turned True, it shows one error page on the browser; when debug mode it turned False, I receive the same error through email, where the same email is sent 10 times instead of once. Can anyone help me understand the issue? -
django - Can't install the add-on django-bootstrap-form
I'm using the django-bootstrap-form addon in my few projects. I've never had a problem with the installation. I just tried and successfully installed it in a new project in Windows. However, I'm having trouble installing this on Linux. Below error: root@debian:/var/www/redprogram# python3 -m pip install django-bootstrap-form Collecting django-bootstrap-form Using cached django-bootstrap-form-3.4.tar.gz (4.4 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [10 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 14, in <module> File "/var/www/redprogram/venv/lib/python3.10/site-packages/setuptools/__init__.py", line 17, in <module> from setuptools.dist import Distribution File "/var/www/redprogram/venv/lib/python3.10/site-packages/setuptools/dist.py", line 42, in <module> from . import _entry_points File "/var/www/redprogram/venv/lib/python3.10/site-packages/setuptools/_entry_points.py", line 43, in <module> def validate(eps: metadata.EntryPoints): AttributeError: module 'importlib.metadata' has no attribute 'EntryPoints' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. I will add that I use django-bootstrap-form in a few other projects on the same computer but they were installed some … -
Problems with Python installation and Pycharm virtual environments
I've been using PyCharm for a while now, when I first started using it python 3.7 was the latest release so I used that, everything worked fine (~8 different projects). However, the latest version of Django requires python 3.8 or later so I finally updated and installed 3.11. I'm having some problems setting up my Pycharm projects with python 3.11 (my system can't import Django even though it's installed, I think it stems from the project not being in a venv but I've tried to add it into one).I've installed python 3.11 in the default location, the same place python 3.7 was installed but when I choose a python interpreter (screenshot below) many of them are invalid. I also notice that many of my other projects (FaceComparison as an example) are using a python 3.7 that itself is within a virtual environment, within the Scripts folder by the looks of it. Should I have installed python 3.11 in a virtual environment? Whenever I try and set up a new project and use a python 3.11 interpreter, a) it's got (DjangoTesting) in it - not sure why? and it also isn't in a virtual environment. I've read many questions about Pycharm, … -
Django Python: How to code a Social-Media-Explore Page?
Hey I am working on a Social Media Website, I have almost everything done, but I need a Explore Page with Posts based on their interests, everybodys Explore Page should look different. Where should I start? I have looked up the Internet for Projects, but i haven't found anything. I don't know where to start. Feel free to post links of Websites that could help me, thank you. -
Am trying to exclude from the GET request the parameters that does not contain values
I have this code in the search.html <h1>Property Search</h1> <hr> <form method="GET" action="/search/results/?{{ query_params }}" class="form-inline" style="display: flex; justify-content: center; align-items: center; "> <div class="form-group mx-sm-3 mb-2"> <label for="inputSaleRent" class="mr-2" style="margin-right: 10px; font-weight: bold;">Sale/Rent:</label> <select id="inputSaleRent" name="sale_rent" class="form-control" style="width: 150px; margin-right: 10px;"> <option value="">Choose...</option> <option value="sale">For Sale</option> <option value="rent">For Rent</option> </select> </div> <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;"> <label for="inputDistrict" class="mr-2" style="margin-right: 10px; font-weight: bold;">District:</label> <select id="inputDistrict" name="district" class="form-control" style="width: 150px; margin-right: 10px;"> <option value="">Choose...</option> <option value="District 1">District 1</option> <option value="District 2">District 2</option> <!-- Add more district options --> </select> </div> <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;"> <label for="inputMunicipality" class="mr-2" style="margin-right: 10px; font-weight: bold;">Municipality/Community:</label> <select id="inputMunicipality" name="municipality" class="form-control" style="width: 150px; margin-right: 10px;"> <option value="">Choose...</option> <option value="Municipality 1">Municipality 1</option> <option value="Municipality 2">Municipality 2</option> <!-- Add more municipality options --> </select> </div> <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;"> <label for="inputParish" class="mr-2" style="margin-right: 10px; font-weight: bold;">Parish:</label> <select id="inputParish" name="parish" class="form-control" style="width: 150px; margin-right: 10px;"> <option value="">Choose...</option> <option value="Parish 1">Parish 1</option> <option value="Parish 2">Parish 2</option> <!-- Add more parish options --> </select> </div> <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;"> <label for="inputPropertyType" class="mr-2" style="margin-right: 10px; font-weight: bold;">Property Type:</label> <select id="inputPropertyType" name="property_type" class="form-control" style="width: 150px; margin-right: 10px;"> <option … -
NoReverseMatch at /AddBid/1 Reverse for'addComment' withkeyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['addComment/(?P<id>[0-9]+)\\Z']
When I click on bid I receive the NoReverseMatch error. In my views, I pass different times and successfully the id as input to the view. When it comes to the AddComment function, the id seems not passed. Views: def listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) IsWatchlist = request.user in listing.watchlist.all() allComments = Comment.objects.filter(listing=listing) return render(request, "auctions/listing.html", { "listing": listing, "ItemisinIsWatchlist": IsWatchlist, "allComments":allComments }) @login_required def addwatchlist(request, id): listingData = Listing.objects.get(pk= id) current_user= request.user listingData.watchlist.add(current_user) return HttpResponseRedirect(reverse("listing", args=(id, ))) @login_required def removewatchlist(request, id): listingData = Listing.objects.get(pk= id) current_user= request.user listingData.watchlist.remove(current_user) return HttpResponseRedirect(reverse("listing", args=(id, ))) def addComment(request, id): currentUser = request.user listingData = Listing.objects.get(pk=id) message = request.POST["newComment"] newComment = Comment( author = currentUser, listing = listingData, message = message ) newComment.save() return HttpResponseRedirect(reverse("listing", args=(id, ))) @login_required def AddBid(request, id): listingBid = Listing.objects.get(pk=id) newBid = request.POST["newBid"] if int(newBid) > listingBid.bid.bid: updateBid= Bid(bid=int(newBid), user=request.user) updateBid.save() listingBid.bid.bid = int(newBid) listingBid.save() return render(request, "auctions/listing.html") else: return render(request, "auctions/listing.html") HTML: {% if user.is_authenticated %} <p> {% if ItemisinIsWatchlist %} <form action="{% url 'removewatchlist' id=listing.id %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-danger">Remove from watchlist</button> </form> {% else %} {% if listing.id %} <form action="{% url 'addwatchlist' id=listing.id %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-success">Add … -
How to add additional user data upon first social sign in with django-allauth?
In Django REST framework, when a user signs in via a social account, say Google, I post to 127.0.0.1/accounts/google with an 'access_token' from the frontend client. 'django-allauth' then pulls data like first name, last name, email from Google, and even creates a username. However, I want to enforce two additional required fields dob (date of birth) and gender, and allow for a custom username when the user first signs in via a social account. How can I POST to 127.0.0.1/accounts/google with additional data? Or are there other ways to do so? I tried changing allauth.socialaccounts.form.SignUpForm, but it doesn't seem to work with Django REST framework. -
Error: 'EventsRaw' has no ForeignKey to 'UserEvents' - Reverse-Related GenericForeignKey Inline Form in Django Admin
I'm encountering an error while attempting to add a reverse-related GenericForeignKey inline form to a model in Django admin. The specific error message states: "'EventsRaw' has no ForeignKey to 'UserEvents'." To provide better context and clarity, I have created simplified example files. By reviewing these files, you will have a clearer understanding of my intention: https://share.getcloudapp.com/v1uWyox0 Here's what I need assistance with: Displaying UserEvents in the Django admin dashboard. When navigating to the UserEvents page in the admin dashboard, I would like to see a list of all EventsRaw objects that are reverse-related. Thank you in advance for your help! -
Django: Format dates according to settings.LANGUAGE_CODE in code (e.g. messages)
In my Django 4.2 app's settings.py I have # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = "de-CH" TIME_ZONE = "CET" USE_I18N = True USE_TZ = True which works in templates, e.g. {{ training.date | date:"l, j. M." }} is displayed as Sonntag, 11. Jun.. However, if I use strftime in the code, e.g. self.success_message = ( f"Eingeschrieben für <b>{self.date.strftime('%A')}</b>, " f"den {self.date.strftime('%d. %B %Y')}.".replace(" 0", " ") ) I end up with Eingeschrieben für Thursday, den 15. June 2023.. How do I get get date strings according to settings.LANGUAGE_CODE from code? -
Django Async (uvicorn) is very slow
I have a boilerplate app and was playing around with Django Async(planning to add some GraphQL + subscriptions) and made a benchmark that shocked me. Gunicorn with async worker uvicorn is much more slower than gthread. Async Code: async def my_async_view(request): return JsonResponse( {"async accounts": "Test"}, status=200, ) Gunicorn Async command: gunicorn --worker-class uvicorn.workers.UvicornWorker banking_api.asgi --workers=8 --threads=2 Sync Code def my_sync_view(request): return JsonResponse( {"sync accounts": "Test"}, status=200, ) Gunicorn Sync command: gunicorn banking_api.wsgi --workers=8 --threads=2 Benchmark results: Async: Running 30s test @ http://localhost:8000/test/ 12 threads and 50 connections Thread Stats Avg Stdev Max +/- Stdev Latency 57.72ms 75.82ms 1.08s 97.25% Req/Sec 81.90 44.42 232.00 81.61% 29007 requests in 30.05s, 8.08MB read Requests/sec: 965.41 Sync: Running 30s test @ http://localhost:8000/test/ 12 threads and 50 connections Thread Stats Avg Stdev Max +/- Stdev Latency 24.26ms 44.37ms 865.76ms 92.37% Req/Sec 281.56 146.56 0.89k 66.32% 100051 requests in 30.08s, 30.25MB read Requests/sec: 3326.37 What is happening? Why the difference of Requests/sec of 3326.37 (sync) vs 965.41 (async) ? Am I doing something wrong here? Thanks -
regarding slashes using in urls pattern
i am learning django for some days and i feel overwhelm by slashes using in url pattern like path("login" , login , name='login') sometimes we use slash in the starting , sometime in the end and sometime we use at both side like this (/login, login/, /login/).it is really very confusing question = 1-what are these slashes and what does it do in my pattern 2 - when sould i use slash - in starting , in end or at both side i don't know exactly when to use these slashes in url pattern so please guide me -
Postgresql query error, ERROR: there is no unique constraint matching given keys for referenced table "app_user_user"
I am using Django version 4.2 and I am facing this error while executing the migration file. I made no changes to Django's standard tables "app_user_user_groups" and "app_user_user_user_permissions". In this migration, I changed the primary key(id) field in the "app_user_user" table from int to bigint I used the following command to get the sql output of the related migrate file; python manage.py sqlmigrate app_user 0002_auto_20230607_1447 output; BEGIN; -- -- Alter field extra on user -- -- (no-op) -- -- Alter field id on user -- ALTER TABLE "app_user_user" ALTER COLUMN "id" TYPE bigint USING "id"::bigint; ALTER SEQUENCE IF EXISTS "app_user_user_id_seq" AS bigint; ALTER TABLE "app_user_user_groups" ALTER COLUMN "user_id" TYPE bigint USING "user_id"::bigint; ALTER TABLE "app_user_user_user_permissions" ALTER COLUMN "user_id" TYPE bigint USING "user_id"::bigint; ALTER TABLE "app_user_user_groups" ADD CONSTRAINT "app_user_user_groups_user_id_d117580e_fk" FOREIGN KEY ("user_id") REFERENCES "app_user_user" ("id") DEFERRABLE INITIALLY DEFERRED; ALTER TABLE "app_user_user_user_permissions" ADD CONSTRAINT "app_user_user_user_permissions_user_id_ec2823c7_fk" FOREIGN KEY ("user_id") REFERENCES "app_user_user" ("id") DEFERRABLE INITIALLY DEFERRED; COMMIT; my user model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( _('email address'), unique=True ) is_staff = models.BooleanField( default=False ) is_active = models.BooleanField( default=True ) identity = models.CharField( max_length=20, unique=True, null=True, blank=True, verbose_name=_('Identity') ) name = models.CharField( max_length=50, null=True, blank=True, verbose_name=_('Name') ) last_name = models.CharField( max_length=50, null=True, blank=True, verbose_name=_('Last …