Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - GenericForeignKey with BaseDatatableView
I'm having trouble using a generic foreign key in BaseDatatableView. Hello. I decided to use a generic foreign key in django. In orm I can do what I need, I can go through content_object to the instance that is connected to this field and easily read the field values of this instance. The problem occurs when I create tables using BaseDatatableView. [models.py] class Warehouse(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') quantity = models.IntegerField() def __str__(self): return f'{self.content_object.name} - {self.quantity}' class Meta: indexes = [ models.Index(fields=['content_type', 'object_id']) ] class Product1(models.Model): name = models.CharField(max_length=50) tag = models.SlugField() note = models.CharField(max_length=20) def __str__(self): return self.tag class Product2(models.Model): name = models.CharField(max_length=50) tag = models.SlugField() note = models.CharField(max_length=20) def __str__(self): return self.tag ( The model architecture is exemplary and only tests relationships ) [table.py] class Product1WarehouseDataTable(BaseDatatableView): model = Warehouse columns = ['content_object__name', 'content_object__tag', 'content_object__note', 'quantity'] def get_initial_queryset(self): ct = ContentType.objects.get_for_model(Product1) qs = self.model.objects.filter(content_type=ct) return qs BaseDatatableView throws an error: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. I want to display data from Product 1 in the table from the Warehouse model. … -
Django CORS configuration not working despite middleware setup
I'm encountering an issue with CORS (Cross-Origin Resource Sharing) configuration in my Django project. Despite configuring CORS settings in my settings.py and adding the CorsMiddleware to the MIDDLEWARE list, I still encounter CORS-related errors when making requests from my frontend application. Here's a summary of my configuration: settings.py (CORS and CSRF settings): # CORS CORS_URLS_REGEX = r"^/api/.*$" CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = config("CORS_ORIGIN_WHITELIST", cast=Csv(), default=["http://localhost:3000"]) CORS_ALLOWED_ORIGINS = config("CORS_ALLOWED_ORIGINS", cast=Csv(), default=["localhost:3000"]) CORS_ALLOW_ALL_ORIGINS = config("CORS_ALLOW_ALL_ORIGINS", default=True, cast=bool) CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) CORS_ALLOW_HEADERS = list(default_headers) + ["Set-Cookie"] # CSRF CSRF_TRUSTED_ORIGINS = config("CSRF_TRUSTED_ORIGINS", cast=Csv()) CSRF_USE_SESSIONS = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_SAMESITE = None settings.py (MIDDLEWARE): MIDDLEWARE = ( "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) Despite having these settings in place, when I attempt to make a request from my frontend application (https://example.com) to my Django backend (https://api.example.com/api/v1/), I receive the following error: Access to XMLHttpRequest at 'https://api.example.com/api/v1/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Failed to load resource: net::ERR_FAILED Also I get this result from Postman: Django version: 4.2.1 django-cors-headers version: 4.3.1 -
Django How to save image on my custom path when triggering signals
When I trigger this signal, the image is copied from my ImageModel and uploaded to my OrderItem model in the order_image_file field. The product image is being saved to its original ImageModel destination even though I have defined a custom path in my OrderItem model. def orderImage_upload_path(instance, filename): return f'order_image/{generate_sku()}_{filename}' class OrderItem(models.Model): product_image = models.ForeignKey(ProductImage, on_delete=models.SET_NULL,blank=True,null=True) order_image_file = models.ImageField(blank=True,null=True,upload_to=orderImage_upload_path) my signals @receiver(post_save, sender=OrderItem) def OrderItem_Signals(sender,created ,instance, **kwargs): if created: if not instance.order_image_file and instance.product_image: instance.order_image_file = instance.product_image.image instance.save() -
Passing instances to both model forms, one's model object is updated but about the next, a new object is made
I want to edit both a Drug object and a Bgt object; so I have used Django model forms and have passed instances of both models to it in view. It updates the Bgt object, but Drug object is not updated; instead a new Drug object is made, why? the relationship among both models: Bgt model has a drug field which is a foreignKey field to Drug In this image, 'kostery' was the previous bgt object, which is now changed to 'kostery3' But in the second image, Drug 'Kostery' still exists and a new Drug is created 'Kostery3' View function: The following image is view function: the following is bgt Edit form: this is the drug edit form: this is drug model: -
Django how to use post_save for upload image from another model
I am trying to copy image from my ProductImage models and upload it to my OrderItem models when any new order items will be crate but got this error AttributeError: 'NoneType' object has no attribute 'image' but you can see my ProductImage model have image fields. here my two models: #ProductImage Model class ProductImage(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE,blank=True,null=True) image = models.ImageField(upload_to=dynamic_upload_path) thumb_image = models.ImageField(upload_to=dynamic_upload_path,blank=True,null=True) #OrderItem models class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL,blank=True,null=True) product_image = models.ForeignKey(ProductImage, on_delete=models.SET_NULL,blank=True,null=True) order_image_file = models.ImageField(blank=True,null=True,upload_to=orderImage_upload_path) my signals: @receiver(post_save, sender=OrderItem) def OrderItemSignals(sender, instance, created,**kwargs): if created: instance.order_image_file = instance.product_image.image so basically when any order item will be crate I want to fire my post save for copy image from my product image models and upload it to my order item models image fields. -
The Like button does not change to Dislike, Django
When a user puts a Like, the reverse Dislike button should be displayed, but this does not happen. If you remove the if condition, then like and dislike work separately, the data is written to the database and deleted accordingly. But there is a problem with the if condition. When the user has already put a Like, the information is not taken from the database that they need to put a Dislike instead of a Like. Do not understand why. models.py: class PostLike(models.Model): userlikepost = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) likepost = models.ForeignKey(Userpublication, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('userlikepost', 'likepost') views.py: def show_post(request, post_slug): post = get_object_or_404(Userpublication, slug=post_slug) like_count = PostLike.objects.filter(likepost=post).count() liked_by_current_user = False if request.user.is_authenticated: liked_by_current_user = PostLike.objects.filter(likepost=post, userlikepost=request.user).exists() print(f'liked_by_current_user: {liked_by_current_user}') context = { 'post': post, 'like_count': like_count, 'liked_by_current_user': liked_by_current_user, } return render(request, 'pie/home.html', context) @login_required def like_post(request, post_id): try: post = Userpublication.objects.get(pk=post_id) like, created = PostLike.objects.get_or_create(userlikepost=request.user, likepost=post) like_count = PostLike.objects.filter(likepost=post).count() like_count = PostLike.objects.filter(likepost=post).aggregate(count=Count('id'))['count'] return JsonResponse({'liked': created, 'like_count': like_count}) except Exception as e: return JsonResponse({'error': str(e)}, status=500) @login_required def unlike_post(request, post_id): try: post = Userpublication.objects.get(pk=post_id) like = PostLike.objects.filter(userlikepost=request.user, likepost=post).first() if like: like.delete() like_count = PostLike.objects.filter(likepost=post).count() return JsonResponse({'unliked': True, 'like_count': like_count}) except Exception as e: return JsonResponse({'error': str(e)}, status=500) html: … -
I got an error when i tried to deploy my django app on vercel
I build my app on django, with all my dependencies especified on file "requirements.txt" i didn't make an enviroment on vercel to deploy cause i saw a tutorial where the man didn't it. I have tow files called: build_files.sh and vercel.json build_files.sh: pip install -r requirements.txt python3 manage.py collectstatic --noinput vercel.json: { "version": 2, "builds": [ { "src": "gestor_backend/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.8" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "gestor_backend/wsgi.py" } ] } requirements.txt: asgiref==3.7.2 backports.zoneinfo==0.2.1 certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 cryptography==42.0.5 defusedxml==0.8.0rc2 Django==4.2 django-cors-headers==4.3.1 django-templated-mail==1.1.1 djangorestframework==3.14.0 djangorestframework-simplejwt==5.3.1 djoser==2.2.2 idna==3.6 mysqlclient==2.2.4 oauthlib==3.2.2 pycparser==2.21 PyJWT==2.8.0 python3-openid==3.2.0 pytz==2023.3.post1 requests==2.31.0 requests-oauthlib==1.3.1 social-auth-app-django==5.4.0 social-auth-core==4.5.3 sqlparse==0.4.4 typing_extensions==4.9.0 tzdata==2023.4 urllib3==2.2.1 this is the entire error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Trying pkg-config --exists libmariadb Command 'pkg-config --exists libmariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, … -
How to integrate real-time computer vision code to django
I have this code for real-time action detection using MediaPipe and a deep learning model. I want to create a Django video streaming web app and integrate this code to detect actions from the frames. I have tried putting the entire code in a class (along with the function definitions of each function called in the code) in a separate python script (camera.py). I then imported the entire class into my views.py but the frames don't show when I run the server. This is the code I would like to integrate into the Django app: sequence = [] sentence = [] predictions = [] threshold = 0.5 cap = cv2.VideoCapture(0) # Set mediapipe model with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic: while cap.isOpened(): # Read feed ret, frame = cap.read() # Make detections image, results = mediapipe_detection(frame, holistic) print(results) # Draw landmarks draw_styled_landmarks(image, results) # 2. Prediction logic keypoints = extract_keypoints(results) sequence.append(keypoints) sequence = sequence[-30:] if len(sequence) == 30: res = model.predict(np.expand_dims(sequence, axis=0))[0] print(actions[np.argmax(res)]) predictions.append(np.argmax(res)) #3. Viz logic if np.unique(predictions[-10:])[0]==np.argmax(res): if res[np.argmax(res)] > threshold: if len(sentence) > 0: if actions[np.argmax(res)] != sentence[-1]: sentence.append(actions[np.argmax(res)]) else: sentence.append(actions[np.argmax(res)]) if len(sentence) > 5: sentence = sentence[-5:] # Viz probabilities image = prob_viz(res, actions, image, colors) cv2.rectangle(image, … -
How can I add customized CSS styles to django-ckeditor editor?
I wanna be able to add customized CSS styles that I've already defined on my CSS files. I read the documentation here and here, but it just does not work. **django-ckeditor version ** django-ckeditor 6.7.1 This is ckeditor configs CKEDITOR_CONFIGS = { 'default': { 'allowedContent': True, 'stylesSet':[ { 'name':'highlighted-text', 'element':'div', 'attributes':{'class':'highlighted-text'} }, ], 'toolbar': 'Custom', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink'], ['RemoveFormat', 'Source', 'Image', 'Table'] ], } } **This is how django-ckeditor is looking like ** Any thoughts? -
TypeError: Improper geometry input type: <class 'dict'>
I have this django model: from django.contrib.gis.db import models from django.contrib.gis.forms import PolygonField class Field(models.Model): boundary = PolygonField(srid=4326) asset_id = models.CharField(max_length=255, unique=True) Given a polygon, I need to check its intersections with what's in the database. So I do: from django.contrib.gis.geos import GEOSGeometry polygon = { 'type': 'Polygon', 'coordinates': [ [-72.35720634789077, 47.72858763003908], [-71.86027854004486, 47.52764829163817], [-72.37075892446839, 47.539848426151735], [-72.35720634789077, 47.72858763003908], ], } Field.objects.filter(boundary__intersects=GEOSGeometry(polygon)) and I get: GEOSGeometry(polygon) Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/IPython/core/interactiveshell.py", line 3508, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-16-a799be749a02>", line 1, in <module> GEOSGeometry(polygon) File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/geos/geometry.py", line 767, in __init__ raise TypeError("Improper geometry input type: %s" % type(geo_input)) TypeError: Improper geometry input type: <class 'dict'> What is the proper way of achieving this? I also tried this: >>> Field.objects.filter(boundary__intersects=GEOSGeometry(json.dumps(polygon))) Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/IPython/core/interactiveshell.py", line 3508, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-3-155b1b25302f>", line 1, in <module> Field.objects.filter(boundary__intersects=GEOSGeometry(json.dumps(polygon))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/geos/geometry.py", line 753, in __init__ ogr = gdal.OGRGeometry.from_json(geo_input) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/gdal/geometries.py", line 167, in from_json return OGRGeometry(OGRGeometry._from_json(force_bytes(geom_input))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/gdal/geometries.py", line 154, in _from_json return capi.from_json(geom_input) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/gdal/prototypes/errcheck.py", line 83, in check_geom raise GDALException( django.contrib.gis.gdal.error.GDALException: Invalid geometry pointer returned from "OGR_G_CreateGeometryFromJson". more details -
How to properly send response to React Frontend from Django Channels?
I am trying to use Django Channels to implement long-polling for a React frontend web app and Django REST backend. I believe that much of what I have is working to some degree, but some thing(s) must be incorrectly configured or coded to produce unexpected results. In short, the problem that I am receiving is that when the Django Channels Consumer sends back a response, it does not immediately go back to the frontend (per console.log(...)s in the code); rather, it seems the Consumer must send another response and then the previous or both responses appear in the frontend. I am trying to implement using AsyncHttpConsumer because Websockets are not possible in our use-case. Asgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": URLRouter( longpoll_urlpatterns + [re_path(r"", django_asgi_app)] ), } ) Routing.py longpoll_urlpatterns = [ # Tried using re_path but did not work path("analysisSubscription/<int:analysisId>/", consumers.AnalysisConsumer.as_asgi()), ] Consumers.py class AnalysisConsumer(AsyncHttpConsumer): async def handle(self, body): print("In Handle") print(self.scope) self.analysisId = self.scope["url_route"]["kwargs"]["analysisId"] self.analysis_group_name = f"analysis_{self.analysisId}" # Register with the appropriate channel await self.channel_layer.group_add(self.analysis_group_name, self.channel_name) await self.send_headers(headers=[ (b"Content-type", b"application/json"), (b"Access-Control-Allow-Origin", b"*"), (b"Access-Control-Allow-Headers", b"Origin, X-Requested-With, Content-Type, Accept, Authorization"),]) #The server won't send the headers unless we start sending the body await self.send_body(b"", more_body=True) … -
Django template svg rendering issue
I have a django html template that contains this svg element: <svg id="tower_layout" width="400" height="400" style="border: 1px solid black;" xmlns="http://www.w3.org/2000/svg"> <rect width="398" height="398" x="1" y="1" fill="#e4e4e7" /> <text x="200" y="20" stroke="black" font-size="15" text-anchor="middle">Tower Diagram</text> {% for i in val_range %} {% if i > 0 %} <line x1="{{ val[i-1].x_d }}" y1="{{ val[i-1].y_d }}" x2="{{ val[i].x_d }}" y2="{{ val[i].y_d }}" stroke-width="1" stroke="black" /> {% endif %} {% endfor %} I'm receiving "TemplateSyntaxError: Could not parse the remainder: '[i-1].x_d' from 'val[i-1].x_d'" when I try to render the template. I've paused the template and verified that all 4 val items are available using the debug console. I'm baffled as to the cause of this error. Any suggestions would be much appreciated! -
How to fix a url submit_function not working?
trying to make a rating system but i get this errorerror, here are my urls and views urls views i want it to send ratings into the database when rating is sent -
Cannot autopopulate date field in django template with widget_tweaks
I’m building a django app that basically is a service for legal guardians to automatically create invoices. For the necessary information about their patients that need to be printed on the invoice, I have a model Patient: class Patient(models.Model): address_as = models.ForeignKey('AddressAs', on_delete=models.PROTECT) first_name = models.CharField('First Name', max_length=120) last_name = models.CharField('Last Name', max_length=120) birthday = models.DateField('Birthday') guardian = models.ForeignKey('Guardian', on_delete=models.CASCADE) court = models.ForeignKey(Court, related_name='patients', on_delete=models.PROTECT) record_number = models.CharField('Record Number', max_length=50) first_billing_date = models.DateField('Start of Legal Care', null=True, blank=True) billing_start = models.DateField('Start of Billing', null=True, blank=True) billing_end = models.DateField('End of Billing', null=True, blank=True) last_billing = models.DateField('Last Billing Date', null=True, blank=True) dutyscope_financial = models.BooleanField('Dutyscope Financial Care') is_wealthy = models.BooleanField('Patient is wealthy', default=False) taken_from_volunteer = models.BooleanField('Taken from Volunteer', default=False) given_to_volunteer = models.BooleanField('Given to Volunteer', default=False) def __str__(self): return f'{self.last_name}, {self.first_name}, geb. {self.birthday}' and a very simple form class: class PatientForm(forms.ModelForm): class Meta: model = Patient fields ='__all__' and of course a view to create patients and a template. So far, so good. Everything works. But now I want to add the possibility to edit the patient’s data. I created a new view for that: def edit_patient(request, patient_id): patient = Patient.objects.get(id=patient_id) if request.method =='POST': form = PatientForm(request.POST or None, instance=patient) if form.is_valid(): updated_patient = … -
pandas read_sql using Django.db.connection
Is there a recommended way to utilize pandas read_sql from within a Django app? I was using a much older version of pandas and this worked: import django.db.connection import pandas as pd df = pd.read_sql("select employee.name from employee;", con=connection) Now, I'm getting this error from read_sql: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy. The query seems to work even with the warning but I don't want to take chances that it might break. I was using the Django.db.connection so that pandas makes use of the db connection pooling within Django. I can successfully use a connection string with the read_sql method but I don't want pandas opening up a bunch of connections in a multi-user system. Same with SQLAlchemy - I don't want to add another connection pool into the app. Any advice or workarounds? I haven't found anything in the pandas or Django documentation covering this. Django==3.2 pandas==2.2.1 mysqlclient==2.2.4 MySQL version 8 -
Is there a way to have SSO using Atlassian for our external Django application?
We created a Forge app and we have an existing Django/Python application. Our forge app app has a connect button and when the user clicks it we want the user to automatically login with the credentials from Jira. Is there a way of possibly doing that? We followed Django-OAuth-Toolkit documentation to build an OAuth 2.0 provider. We managed to get our access token using bash. We followed the documentation on the Atlassian website for External OAuth 2.0 for Forge apps. But we could not get that working. We were expecting some type of response using the Google provider but kept getting errors. We aren't sure exactly what to do after this. The documentation vague. -
Django makemigrations not detecting changes in models
I’m working on a Django project with an app called ‘spider’. I’ve made some changes to my models in models.py, but when I run python manage.py makemigrations spider, it doesn’t create a migration. Here’s the error message I’m getting: No installed app with label 'spider'. Code: Here’s what my INSTALLED_APPS looks like in settings.py: I'm having trouble with Django migrations. Here's what my INSTALLED_APPS looks like in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'spider', ] -
mysql issue with Xampp
I am getting this error on my windows vscode terminal after adjusting the database settings on my settings.py to Xampp settings in django : File "C:\Users\Admin\Desktop\ExPro\venexp\lib\site-packages\django\db\backends\mysql\base.py", line 17, in raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I get the error immediately I tried to runserver which is supposed to run smoothly and prime me to migrate unapplied migrations.. but instead I keep getting the above error no matter what I do.. -
Domain does not work without dot in the en
Why my domain works only when I type this: example.com. with a "dot" and without "www" and in any other condition I get 400 error: http://example.com./ - it works http://www.example.com/ - it doesn't work http://www.example.com./ - it doesn't work Error I get: GET http://www.example.com./ 400 (Bad Request) I use: django, aws, route53, ec2, ubuntu, nginx, gunicorn I followed this tutorial 1:1: I set up: elastic IP for my instance and connnect to my instance. In hosted zone I did like in tutorial: Record name: example.com Record type: A Value: my IP Alias: No TTL (seconds): 300 Routing policy: Simple and > Record name: > www.example.com > Record type: > A > Value: > example.com. > Alias: > No > TTL (seconds): > 900 > Routing policy: > Simple 3)Nginx conf: ``` server { listen 80 default_server; server_name example.com www.example.com myIP;} ``` then restart: ``` sudo systemctl restart nginx sudo service gunicorn restart sudo service nginx restart ``` Settings.py: ALLOWED_HOSTS = [ 'example.com','myIP', ] Thanks in advance! -
Estilos de panel de administracion django no carga
Subi mi proyecto a un servidor gratuito de pythonanywhere la version python es 3.10 y la version django es 5.0. Los estilos de mis templates cargan de manera correcta, pero los estilos de mi panel de administración que trae por deaful django se muestran sin estilos enter image description here Esta es mi configuracion en settings.py obviamnete tengo importada la libreria os STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = 'static/' MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' ¿Alguien sabe como poder solucionar esto? -
transaction.atomic() rolls back if another query is executed
I am having issues with Django's transaction.atomic. I have this app that users can update their information, but I will be giving an example here. So I want to prevent update to this field if more than one requests is received, so I want to lock the row which is why I am using transaction.atomic and select_for_update. So I have a UserProfile model that I want to update some information, the method which i use to update is is below Class Profile(models.Model): def get_queryset(self): return self.__class__.objects.filter(id=self.id) @transaction.atomic() def update_age( self, age: int, ) -> None: obj = self.get_queryset().select_for_update().get() obj.age = age obj.save() Below is the view class UserProfileView(APIView): def put(self, request): profile = rquest.user.profile profile.update_age(request.data["age"]) UpdateHistory.objects.create(user=request.user, updated_field="age") The issue is UpdateHistory object is created but the age update is rolled back, but when I remove the creation of the UpdateHistory, the age is actually updated successfully. So the above code only creates UpdateHistory, but doesnt update the UserProfile's age. But if I remove the line UpdateHistory.objects.create(user=request.user, updated_field="age"), the age is updated successfully. No exception is being raised at all, this has been confusing me for days. Hopefully I can get some help. Thanks in advance -
Django-Allauth Function Working Locally But Not When Deployed To Azure
I built a function using Django-allauth that after a user tries logging in with incorrect credentials three times, the program times them out for an hour. The code works locally, but when I deploy to an Azure Instance, the function has to impact at all. Any insights would be greatly appreciated :). -Tried verifying if it was a timezone issue in calculating the logout time -
running django tests --parallel and splitting log files per test-runner worker
I'm using manage.py test --parallel to run my tests and want to create a separate log file for each test runner. Currently, all the test runner worker write to the same log file, so I get a single log file with contents "striped" like this: [ForkPoolWorker-2] ... [ForkPoolWorker-1] ... [ForkPoolWorker-1] ... [ForkPoolWorker-3] ... [ForkPoolWorker-2] ... [ForkPoolWorker-4] ... [ForkPoolWorker-1] ... I create a custom configure_logging() method like this: import logging.config import os def configure_logging() -> None: """Custom logging configuration with process-id named files""" process_id = os.getpid() log_file_path = f"runner-{process_id}.log" LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "file": { "level": "DEBUG", "class": "logging.FileHandler", "filename": log_file_path, }, }, "loggers": { "django.log": { "handlers": ["file"], "level": "DEBUG", "propagate": True, }, }, } logging.config.dictConfig(LOGGING) I'm using a custom test-runner to wire things up: from django.test.runner import DiscoverRunner from myapp.tests.logging_config import configure_logging class ParallelTestRunner(DiscoverRunner): """Parallel test runner with separate log files for each worker""" def setup_test_environment(self, **kwargs): """Configure the test environment with our custom log setup""" super().setup_test_environment(**kwargs) # Configure logging with a unique file per test process configure_logging() I wire that up in settings.py like this: TEST_RUNNER = "myapp.tests.runners.ParallelTestRunner" However, when I look for the log files, it appears it's only creating a single … -
i need help regarding django in vs code?
I want to work on a Django project , but when i try to create a .html file inside templates , it doesn't recognize it as a django template even though i have installed all the django extensions. i also tried to change the file template by default method i.e (ctrl+k M) i also tried to change the file template by default method i.e (ctrl+k M) . -
Error response from daemon: invalid volume specification docker error
I'm using Docker Desktop for Windows on Windows 10. I wanted to run a very simple project from django on Docker locally. after the command "docker build ." everything was OK, but after the command "docker-compose up" I got an error: "Error response from daemon: invalid volume specification : 'C:\Users\elahe\postgre2:/code:rw" I've tried this project on two different windows 10. on one of them, I had no problem, but on the second one I got the mentioned error so I guess my problem is because of the windows or docker setting, is it right? #dockerfile: FROM python:3.9 ENV PYTHONDONTWRITECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ # docker-compose: version: '3.9' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000