Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django capture agent's computer device info
In my web application, I want to capture complete info of agent's computer device and if user logs in my web application on a different device, system will trigger some function. I have already checked django-user-agents but it is not giving complete info, for ex. a user can have same browser(version) and same os family and version on two different computers. In this case my application will not be able to identify whether the user is using same computer device or different. -
Using MediaRecorder i stored video from web camera and than send data by an AJAX call to my django backend. But data is Currupted
Using MediaRecorder i stored video from web camera and than send data by an AJAX call to my django backend. Their im storing video in (mp4 or webM) format. The issue is that stored video is currupted because other than VLC player no other one is running file. The main issue is that than im sending this video to a python code which than extract audio from video. to do this pyhton script first take video duration to process it. As file is currupted, in VLC file is running but duration bar is not showing anything. So, what i think is that data is not storing the way i want. Im new to django and specially to frontend so please help me with this. Suggest me any alternative i just want my video to be stored correctly also with video there is an audio parameter as well. Im separetely sending audio so i somehow bypass the python script which extract audio from video file. But audio sent using AJAX is empty or i think currupted. Here is JS code at frontend side. const preview = document.getElementById("preview"); const startButton = document.getElementById("startButton"); const stopButton = document.getElementById("stopButton"); const recorded = document.getElementById("recorded"); const saveButton … -
How to separate legacy table from Django built-in models?
I have a legacy table that I would like to use in a database-first way. To achieve this, I executed the following command in my Django project directory: python manage.py inspectdb > models.py However, I do not want to modify this database or add any of the Django core models. Instead, I would like to set a local SQLite database for all built-in models, including Auth, User, and Group. In my settings.py file, I have configured two databases as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'admin.db'), }, 'legacy': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blahblah', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, } I understand that there is an option for automatic database routing, but I am unsure what else I need to configure to separate these databases and ensure that the separation works in the Django admin panel. Can you please provide guidance on how to accomplish this? Thank you in advance. -
Background image isn't showing in all apps
I created two apps named as admin and student, admin templates holds base.html and login.html. I set the background image and navbar in base.html. The background image is stored in static/admin/image/background.jpg the same path I gave to set the background for the body tag present inside base.html. Inside the login page I extends base class and override content block and background image shows as well for login.html which is present in same app. but after login i redirect to student apps registration.html page which also extends base.html present inside admin but the background image not shown for students apps any page and it gives error in terminal asNot Found: /display/static/admin/images/baloon.jpg. I added static path to urlpatterns as well but still didn't work I created two app admin, student under one project. admin template holds base.html,login.html. student holds registration.html and display.html. background image set inside base.html. all other web pages extends base.html. background image is shown for login.html but not for student apps HTML pages. It gives an error as Not Found: /registration/static/admin/images/baloon.jpg on the terminal. static file stored under the main project name as 'static' already mentioned in the settings STATIC_URL = '/static/' STATIC_ROOT=BASE_DIR/'static' STATICFILES_DIRS=( BASE_DIR/'staticfiles', ) -
Not Found 404 Error Django Crud Application
i am creating a Django Crud Application.i have it crudapplication while i testing through postman i ran into the problem with Not Found: / [29/Apr/2023 10:40:06] "GET / HTTP/1.1" 404 2272 Not Found: / [29/Apr/2023 10:40:06] "GET / HTTP/1.1" 404 2272 Not Found: /favicon.ico [29/Apr/2023 10:40:07] "GET /favicon.ico HTTP/1.1" 404 2323 Not Found: /users [29/Apr/2023 10:40:11] "GET /users HTTP/1.1" 404 2305 urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from Student import views` urlpatterns = [ url(r'^user$',views.userApi), url(r'^user$',views.userApi), url(r'^user/([0-9]+)$',views.userApi), path('admin/', admin.site.urls), ] -
How to add Tailwind to a React App in django?
I'm trying to build a django app with React and Tailwind. I have checked and tried countless tutorials, now I'm able to preview the react app on http://127.0.0.1:8000/ But the tailwind classes are not working, no matter what I do. I have followed https://tailwindcss.com/docs/guides/create-react-app this tutorial, the css i use is linked correctly because if i add regular css classes I can see the changes. But the tailwind classes are not applied. This is the structure of my django app with react: ┃ ┣ src ┃ ┃ ┣ components ┃ ┃ ┃ ┗ App.js ┃ ┃ ┗ index.js ┃ ┣ static ┃ ┃ ┣ css ┃ ┃ ┃ ┗ index.css ┃ ┃ ┣ frontend ┃ ┃ ┃ ┣ main.js ┃ ┃ ┃ ┗ main.js.LICENSE.txt ┃ ┃ ┗ images ┃ ┣ templates ┃ ┃ ┗ frontend ┃ ┃ ┃ ┗ index.html ┃ ┣ init.py ┃ ┣ admin.py ┃ ┣ apps.py ┃ ┣ models.py ┃ ┣ tests.py ┃ ┣ urls.py ┃ ┗ views.py Any suggestions? I noticed after I run npm run build, the tailwind 'className' is converted to 'class', I don't know if that's expected or a problem. If I change 'class' to 'className' in inspector, the style is still not … -
how to add limit of users in my django channels chat room
i wish to had not more than 2 users limit in my chat room from channels.consumer import SyncConsumer,AsyncConsumer from channels.exceptions import StopConsumer from asgiref.sync import async_to_sync class MySyncConsumer(SyncConsumer): def websocket_connect(self, event): chat_channel_name = self.scope['url_route']['kwargs']['channelname'] async_to_sync (self.channel_layer.group_add)(self.chat_channel_name,self.channel_name) self.send({ 'type':'websocket.accept' }) I want to add limited number of users in my chat room -
Including additional data in Django DRF serializer response that doesn't need to be repeated every entry?
Our Django project sends GeoFeatureModelSerializer responses and we want to include an additional value in this response for JS to access. We figured out how to do this in serializers.py: from rest_framework_gis import serializers as gis_serializers from rest_framework import serializers as rest_serializers from core.models import Tablename class MarkerSerializer(gis_serializers.GeoFeatureModelSerializer): new_value = rest_serializers.SerializerMethodField('get_new_value') def get_new_value(self, foo): return True class Meta: fields = ("date", "new_value") geo_field = "geom" model = Tablename JS can get this value with geojson.features[0].properties.new_value where const geojson = await response.json(), but it's unnecessarily added with every entry. We'd like for it to be included only once so JS can access it with something like newResponse.new_value and existing functionality can continue getting the same data via newResponse.geojson or similar. How can we include a single additional value in this response? We thought maybe wrapping our serializer in another, but they seem to be asking a different thing we don't understand. Can we append this somehow? In the serializer can we do something like newResponse = {'new_value': new_value, 'geojson': geojson} somewhere? We've had a dig through the Django Rest Framework serializers docs and couldn't work it out, so perhaps we're missing something. Other SO threads seem to only ask about adding … -
How do I fix SAML authentication on Heroku app which works fine on localhost?
I have a django app that uses SAML authentication to sign in .edu users. I recently upgraded my packages and after a lot of trial and error, I found a set of packages that all work with each other on Python 3.10. Here are the packages my requirements.txt currently holds that are related to SAML: python3-saml==1.15.0 xmlsec==1.3.13 isodate==0.6.1 six==1.11.0 lxml==4.9.2 SAML authentication for .edu users works fine on localhost but I get the following error when I run the application on Heroku Dev. SAML Response not found, Only supported HTTP_POST Binding I used the SAML tracer to check if I was receiving POST data upon sign in and this is what I found: The Summary tab shows the certificate / key values. On https://herokuapp/account/?acs this is the error: OneLogin_Saml2_Error at /account/ SAML Response not found, Only supported HTTP_POST Binding I have also observed that I can randomly log in using my .edu user sometimes. How can I go about fixing this? -
Django: How to get images from csv file and populate them in Django Image field?
I am trying to save image from CSV file to Product Image Field in Django, this images are already uploaded to an external website so i am finding it difficult populating the image field with the image from the url. Please i need some help to fix this issue This is how my CSV data looks like title price image Item 1 21 http://www.website.com/wp-content-7384/77984357987.jpg ! alt : image-alt Item 2 32 http://www.website.com/wp-content-7854/779534587987.jpg ! alt : image-alt Item 3 433 http://www.website.com/wp-content-2784/72347987987.jpg ! alt : image-alt Product Model class Product(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to=user_directory_path, default="product.jpg") price = models.DecimalField(max_digits=12, decimal_places=2, default=0.00) ... This is how i have been importing data so far from .csv file class Command(BaseCommand): def add_arguments(self, parser): pass def handle(self, *args, **options): df = pd.read_csv('products.csv') for title, image, price in zip( df.post_title, df.images, df.regular_price): product = Product( title=title, price=price, ) product.save() # How do i process and save image # From the URL in the csv above Some other thing that i have tried doing that did not work class Command(BaseCommand): def add_arguments(self, parser): pass def handle(self, **options): df = pd.read_csv('products.csv') for title, image, price in zip( df.post_title, df.images, df.regular_price): images = [] for row in image: product … -
SSL issue in Python Django Elasticsearch environment
I am running a local dockerised Elasticsearch instance for a Python Django project, which I set up by following the elastic docker guide. One of the steps involved downloading a CA cert file. When the container is running I can connect to it using this cert file, or by ignoring certs altogether # both of these work curl --cacert my_cert.crt "https://${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}@localhost:9200" curl -k "https://${ELASTIC_USERNAME}:${ELASTIC_PASSWORD}@localhost:9200" I have then added the ELASTICSEARCH_DSN details to my settings.py file as described in the elasticsearch dsl docs but there is no mention of certificates in the documents, and running commands gives an SSL error: python manage.py search_index --rebuild <snip> elasticsearch.exceptions.SSLError: ConnectionError([SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1002)) caused by: SSLError([SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1002)) I'm not sure of the best way to resolve this. Any advice would be appreciated. -
Server not starting because of error in accounts\urls.py
I have no idea what I'm missing, I can't even run the django server without getting an error. This is my accounts.urls and it seems like django cannot find it but I dont know the problem. from django.urls import path from . import views app_name = "accounts" urlpatterns = [ path("login/", views.login_view, name="login"), ] this is my project urls from django.contrib import admin from django.urls import path, include from django.views.generic import RedirectView urlpatterns = [ path("", RedirectView.as_view(pattern_name="list_projects"), name="home"), path("admin/", admin.site.urls), path("accounts/", include("accounts.urls")), path("projects/", include("projects.urls")), ] if i comment out the "path("accounts/", include("accounts.urls"))," line the server runs fine. can also post my views and forms if relevant! im new to django -
UnsupportedTokenTypeError when making request to Google Calendar API
I'm attempting to make a request to get a user's events for their calendar in the Google Calendar API using AuthLib and Django. When I get to the schedule view, I get a UnsupportedTokenTypeError stating nsupported_token_type: Unsupported token_type: 'access_token'. Relevant snippets from views.py are below. CONF_URL = "https://accounts.google.com/.well-known/openid-configuration" oauth = OAuth() oauth.register( name="google", server_metadata_url=CONF_URL, client_kwargs={ "scope": "openid email profile https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.readonly" }, ) # Function decorator that checks whether there is an active user def auth_required(func): @wraps(func) def wrapper(request): user = request.session.get("user") if user: return func(request) else: return redirect("/login") return wrapper def login(request): redirect_uri = "http://127.0.0.1:8000/auth/" # TODO: Change URL to match actual URL once hosted return oauth.google.authorize_redirect(request, redirect_uri) def logout(request): request.session.flush() return redirect("/") def auth(request): token = oauth.google.authorize_access_token(request) request.session["user"] = token["userinfo"] return redirect("/") @auth_required def schedule(request): token = request.session.get("user") email = token["email"] url = "https://www.googleapis.com/calendar/v3/calendars/%s/events" % email resp = oauth.google.get(url=url, token=token, request=request) print(resp) return redirect("/") The token when I make the request looks like this: {'at_hash': 'x', 'aud': 'x.apps.googleusercontent.com', 'azp': 'x.apps.googleusercontent.com', 'email': 'x@gmail.com', 'email_verified': True, 'exp': 1682721445, 'family_name': 'Last', 'given_name': 'First', 'iat': 0, 'iss': 'https://accounts.google.com', 'locale': 'en', 'name': 'First Last', 'nonce': 'x', 'picture': '', 'sub': '0'} Is there an additional, different token that I need to retrieve? -
How can I pass data from django to react at render time
The question is fairly simple. I need to pass data from django to a react component. In django, I have a json object being dumped: class PulseHome(TemplateView): template_name = "pulse_murasa/pulse_home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) efestos_queryset = Efesto.objects.filter(deleted=False).order_by('-id') efestos = EfestoSerializer(efestos_queryset, many=True) context['efestos'] = json.dumps(efestos.data) // THIS IS WHAT MATTERS return context In the html, I get the data like this, it logs correctly: <script id="efestos-data" type="application/json"> {{ efestos|safe }} </script> <script> const efestosData = JSON.parse(document.getElementById('efestos-data').textContent); // THIS IS WHAT MATTERS console.log(efestosData); </script> <script src="{% static 'js/main.de0443a6.js' %} "> </script> Then, in my React index.js file, I try to get the data but it is undefined: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import EfestoComponent from './components/pulseHome'; import reportWebVitals from './reportWebVitals'; const efesto_objects = window.efestosData; // THIS IS WHAT MATTERS console.log("efesto_objects: ", efesto_objects); const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <EfestoComponent objects={efesto_objects}/> ); I guess it has something to do with timing. I could try to tie everything to a DOMContentLoaded listener, but I wonder if there is a standard way to achieve this. -
Django Modeling relationships based on MultiSelectField
Trying to model this for a Django REST Framework project, and I don't know if this is even realistic to do. The idea is that a User can have one relationship with a Track, and it's defined by one of the three choices for relationship_type, which is a MultiSelectField type field, in a UserTrackRelationship instance. Below, I've mocked up the Track and User fields that I'm trying to define. Can this actually be coded? class Track(models.Model): # owner = ForeignKey relationship, based on instance of UserTrackRelationship, where relationship_type=user_owns_track and this track's ID matches class User(models.Model): # tracks_watching = ManyToMany relationship, all instances of UserTrackRelationship, where relationship_type=user_watching_track and this user's ID matches # tracks_copy_purchased = ManyToMany relationship, all instances of UserTrackRelationship, where relationship_type=user_purchased_copy and this user's ID matches class UserTrackRelationship(models.Model): REALTIONSHIP_CHOICES = (('user_owns_track', 'This User Owns This Track'), ('user_watching_track', 'This User Is Watching This Track'), ('user_purchased_copy', 'This User Has Purchased a Copy of This Track')) user = models.ForeignKey(User, related_name='usertrackrel_user', on_delete=models.CASCADE) track = models.ForeignKey(Track, related_name='usertrackrel_track', on_delete=models.CASCADE) relationship_type = MultiSelectField(choices=REALTIONSHIP_CHOICES, max_choices=1, max_length=1) -
Django - Attempting to deploy app on Heroku
I am attempting to deploy a Django app on Heroku. The instance appears to start and I see the following in the logs when it starts: 2023-04-28T15:36:03.694071+00:00 heroku[web.1]: Starting process with command `gunicorn config.wsgi -- logfile -` 2023-04-28T15:36:05.869274+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [2] [INFO] Starting gunicorn 20.1.0 2023-04-28T15:36:05.869477+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [2] [INFO] Listening at: http://0.0.0.0:14398 (2) 2023-04-28T15:36:05.869516+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [2] [INFO] Using worker: sync 2023-04-28T15:36:05.871197+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [7] [INFO] Booting worker with pid: 7 2023-04-28T15:36:05.908573+00:00 app[web.1]: [2023-04-28 15:36:05 +0000] [8] [INFO] Booting worker with pid: 8 2023-04-28T15:36:06.373542+00:00 heroku[web.1]: State changed from starting to up 2023-04-28T15:36:07.000000+00:00 app[api]: Build succeeded However, when I attempt to visit the site (at the Heroku provided URL) I see the following error in the browser: Not Found The requested resource was not found on this server. I see this in the Heroku logs: 2023-04-28T15:37:50.232938+00:00 app[web.1]: 10.1.55.214 - - [28/Apr/2023:15:37:50 +0000] "GET / HTTP/1.1" 404 179 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/112.0" 2023-04-28T15:37:50.233993+00:00 heroku[router]: at=info method=GET path="/" host=sitename.herokuapp.com request_id=77318e40-99f5-47bd-9f29-f828ab07097f fwd="71.81.213.118" dyno=web.1 connect=0ms service=293ms status=404 bytes=343 protocol=https 2023-04-28T15:42:26.163509+00:00 heroku[router]: at=info method=GET path="/" host=sitename.herokuapp.com request_id=b6490fc8-a242-4214-a39d-657f0e295f68 fwd="71.81.213.118" dyno=web.1 connect=0ms service=119ms status=404 bytes=343 protocol=https 2023-04-28T15:42:26.163514+00:00 app[web.1]: 10.1.50.56 - - [28/Apr/2023:15:42:26 … -
Logging out on django user authentication redirects to django admin logout page
I am learning to create a simple website using Django's LocalLibrary tutorial. I just used Django's authentication system to create a default view for logging in and logging out users on my page. However, when I log out, Django does not redirect to the template I created to display that the user has been logged out. Instead, it redirects to the Django admin logout page.There is also an issue where functions other than login, including the password reset form and the HTML for changing passwords, cannot be rendered correctly. Here is my base urls.py file. from django.contrib import admin from django.urls import path from django.urls import include from django.views.generic import RedirectView urlpatterns += [ path('catalog/', include('catalog.urls')) urlpatterns += [ path('', RedirectView.as_view(url='catalog/', permanent=True)), ] # Add Django site authentication urls (for login, logout, password management) urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ] Here is my base.html template. <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>Local Library</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-2"> {% block sidebar %} <ul class="sidebar-nav"> … -
How to debug a test in visual studio code?
Attempts to debug a test fail with Error discovering unittest tests: Failed to import test module: tests. Yet the only existing test file runs without error in the terminal. Testing is necessary - I'm just getting started with Python! The question is how do I configure either VSC and/or the Django code to allow debugging of tests? I've tried both unittest & pytest to no avail. Environment: Visual Studio Code 1.77.3, Python 3.11.3, Django 4.1, Windows 10 Pro Test objective: create a dictionary of dictionaries; includes access to test database Test Explorer: Error discovering unittest tests: Failed to import test module: tests Traceback: Traceback (most recent call last): File "C:\Python311\Lib\unittest\loader.py", line 407, in _find_test_path module = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python311\Lib\unittest\loader.py", line 350, in _get_module_from_name __import__(name) File "g:\workspace\python-land\diet\reaction\tests.py", line 4, in <module> from reaction.models import Reaction File "g:\workspace\python-land\diet\reaction\models.py", line 4, in <module> class Reaction(models.Model): File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\db\models\base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "g:\workspace\python-land\diet\.venv\Lib\site-packages\django\conf\__init__.py", line 72, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or … -
Rendering fields from separate apps in django
I have my main app, and a tags app, I have added the tags to my blogpost model and have made sure I have added them in the back end. My problem is getting them to render. My current code: MODEL class BlogPost(models.Model): tags = models.ManyToManyField(Tag, related_name='blog_posts', blank=True) class Tag(models.Model): label = models.CharField(max_length=255) def __str__(self) -> str: return self.label class TaggedItem(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveBigIntegerField() content_object = GenericForeignKey() VIEW def Blog(request): posts = BlogPost.objects.filter(date__lte=timezone.now()).order_by('-date') blog_paginator = Paginator(posts, per_page=4) page_number = request.GET.get('page') page = blog_paginator.get_page(page_number) tags = [] for post in posts: post_tags = post.tags.all() tags.extend(post_tags) context = { 'posts': posts, 'tags': tags, 'page': page, } return render(request, 'mhpapp/blog.html', context) HTML {% for post in page.object_list %} {% if post.published %} <span> {% for tag in tags %} {% if tag in post.tags.all %} {{ tag.label }} {% endif %} {% endfor %} </span> {% endif %} {% endfor %} -
How to create a discord bot that changes user role with django rest framework?
Im using React in the frontend to make a post request to my REST API in drf. The body of the post request sends the discord_userId. I have this code that runs perfeclty outside my drf application. @bot.slash_command(name="changerole", guild_ids=[DISCORD_CHANNEL], pass_context=True) async def changerole(ctx): member = ctx.author role = get(member.guild.roles, name="Human") await member.add_roles(role) await ctx.send(f"{member.name} has been giving a role called: {role.name}") bot.run(DISCORD_TOKEN) However I want to receive discord_userId in my request and execute the code above inside my drf application I tried this in my views.py from .utils.discord_utils import changerole class VerifyMembershipDiscord(generics.GenericAPIView): def post(self, request): changerole(request.data["discordId"]) return Response({"error": "false", "message": "ok"}, status=status.HTTP_200_OK) my change role function is import discord from discord.utils import get bot = discord.Bot() # Create a new role and assign it to the specified user ID @bot.slash_command(name="changerole", pass_context=True) async def changerole(ctx, user_id: int): guild = bot.get_guild('my_guild_id') member = guild.get_member(user_id) role = get(member.guild.roles, name="Human") await member.add_roles(role) await ctx.send(f"{member.name} has been giving a role called: {role.name}") bot.run(TOKEN) But this raises an error saying: File "/Users/.pyenv/versions/3.10.9/lib/python3.10/asyncio/events.py", line 671, in get_event_loop raise RuntimeError('There is no current event loop in thread %r.' RuntimeError: There is no current event loop in thread 'django-main-thread'. What can I do? -
Django Button Behavior within View that Handles POST and GET Requests
I've implemented the code on the site at the link below. I'm trying to understand what is happening with the log_message view. I understand that the view below handles both POST and GET requests. Note, in the template that this log_message calls (log_message.html), there is a form string/char field called message and a button to log the message. Django and VSCode So, on the first call to this view (view.log_message), the first if is passed and the render function is called where it passes the form to the template. The template contains a message field and log button. I insert some text into the message form, and then press the log button. While doing this in VSCode debugger, i notice that when i press the log button, the control is sent back to the start of the log_message function, but this time request.method=='POST'. There seems to be some underlying behavior that when the button is pressed it reloads the page and thus calls the log_message view again? But that doesn't seem very transparent in the code. Can someone explain what's going on here? def log_message(request): form = LogMessageForm(request.POST or None) if request.method == "POST": if form.is_valid(): message = form.save(commit=False) message.log_date … -
Get FK of previous formset and pass into the Next one
I'm Working on a project and i'm trying to make a product variation, I have a Product, a Color Variation (FK=Product) and a Size Variation (FK=Color Variation) I'm using inline formsets to acomplished that, but when i save more then one Color Variation, i get error saying that get() returned 2 objects. On my CreateView form_valid, first i save the product, then i loop into the variants and inside this loop i made another loop to save the sizes. So for example, if i have Color Red, it will save, then loop to all the sizes that belong to color red and save, and after will check for another Color variation.But this only works when i have only 1 color variation How can i get the fk of the variation that is beeing looped and pass to the size ? Here are my CreateView: def get_context_data(self, **kwargs): ctx = super(ProductCreate, self).get_context_data(**kwargs) if self.request.POST: ctx['variants'] = VariantFormSet(self.request.POST or None, self.request.FILES or None, prefix='variants') ctx['sizes'] = SizeFormSet(self.request.POST or None, self.request.FILES or None, prefix='sizes') else: ctx['variants'] = VariantFormSet(prefix='variants') ctx['sizes'] = SizeFormSet(prefix='sizes') return ctx def form_valid(self, form): form.instance.vendor = get_vendor(self.request) form.instance.product_slug = slugify(form.instance.product_name) context = self.get_context_data() variants = context['variants'] sizes = context['sizes'] with transaction.atomic(): … -
how to add a field for choose a directory in django model?
I need a field to specify the path of my backup file and I write this model: def backup_path(): return os.path.join(settings.BASE_DIR.parent, "backups") class Backup(Authorable, Publishable, models.Model): file_path = models.FilePathField( _("مسیر فایل"), path=backup_path, recursive=True, ) file_size = models.CharField(verbose_name=_("حجم فایل"), max_length=255, null=True, blank=True) class Meta: verbose_name = _("تهیه پشتیبان") verbose_name_plural = _("تهیه پشتیبان") def __str__(self): return f"{self.id} - {self.file_path} - {self.file_size}" def save(self, **kwargs): BackupService.run(self.file_path) return super().save(**kwargs) but in admin panel I can't choose a directory for save backup file. how can i choose a directory in admin? -
Django - Use postgres unaccent with django-filters library
I have a Django app that uses postgres. I know that if i have the unaccent extension from postgres installed in the database, I can use like it's described in the docs to apply filters ignoring the accents in the words: >>> City.objects.filter(name__unaccent="México") ['<City: Mexico>'] >>> User.objects.filter(first_name__unaccent__startswith="Jerem") ['<User: Jeremy>', '<User: Jérémy>', '<User: Jérémie>', '<User: Jeremie>'] In this app I'm also using the django-filter library. I was wondering if there is a way to use the unaccent extension in conjunction with django-filter to avoid rewriting all my search functions. Here is an example of the code used to filter: class BranchsFilter(django_filters.FilterSet): name = CharFilter( label='Filial', label_suffix='', field_name='name', lookup_expr='icontains', ) class Meta: model = Branchs fields = '__all__' Appreciate the help. -
how can i display data from a model that has a foreinkey relationship
I have a django shop model and a command model who has a foreinkey relationship to the model shop class Shop(models.Model): name= models.CharField(max_length=60, verbose_name='nom') adress= models.CharField(max_length=250, verbose_name='adresse') description=models.TextField(max_length=1000) logo=models.ImageField( blank= True ,null=True ) horaire=models.CharField(max_length=100) user= models.ForeignKey(User, blank= True , null=True ,verbose_name="utilisateur", on_delete=models.CASCADE) date= models.DateTimeField(auto_now_add=True, verbose_name='date de création') data=models.JSONField(null=True,blank=True) def __str__(self) -> str: return str(self.name) class Command(models.Model): class Status(models.TextChoices): PENDING = "PENDING" REJECTED = "REJECTED" CANCELED = "CANCELED" PROCESSING = "PROCESSING" READY = "READY" DELIVERED = "DELIVERED" user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) cart = models.ForeignKey( Cart, verbose_name="panier", on_delete=models.CASCADE) type = models.CharField(max_length=50) data = models.JSONField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=20, choices=Status.choices, default="PENDING") shop= models.ForeignKey(Shop, null=True , blank=True, verbose_name="boutique", on_delete=models.CASCADE) email = models.EmailField(max_length=50, null=True) phone = models.CharField(max_length=60) name = models.CharField(max_length=30) company = models.CharField(max_length=50, default='') address = models.CharField(max_length=100, default='') appartement = models.CharField(max_length=100, default='', null=True, blank=True) city = models.CharField(max_length=50, default='') country = models.CharField(max_length=50, default='') # payment = models.ForeignKey(Payment, verbose_name="Payment", on_delete=models.CASCADE) note = models.TextField(default='', null=True) home_delivery = models.BooleanField(default=False) def __str__(self): return str(self.user) or 'Anomyne' I want to display the order data and save when placing an order ,all give show except foreignkey part for model shop. how to manage to display this so that each order can then have a specific shop because …