Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mod_wsgi - Permission denied - Unable to start Python home
I am attempting to run django on an unmanaged VPS running Ubuntu 20.04. I connected to the freshly installed server, installed Django and Postresql. Apache was already installed. I then installed mod_wsgi. I then attempted to configure my .conf file. Edited file etc\apache2\sites-available\000-default.conf to include the following: Alias /static /root/django-apps/dmsemapping/staticfiles <Directory /root/django-apps/dmsemapping/staticfiles> Require all granted </Directory> <Directory /root/django-apps/dmsemapping/dmsemapping> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess dmsemapping python-path=/root/django-apps/dmsemapping python-home=/root/django-apps/env WSGIProcessGroup dmsemapping WSGIScriptAlias / /root/django-apps/dmsemapping/dmsemapping/wsgi.py dmsemapping is the name of my django project /root/django-apps/dmsemapping is the path to my project /root/django-apps/env is the path to my environment variable for python When I run this I get a 403 error. In the error.log file I get: Current thread 0x00007f84dde19c40 (most recent call first): <no Python frame> [Tue Oct 26 22:55:44.887129 2021] [wsgi:warn] [pid 12089:tid 140208634960960] (13)Permission denied: mod_wsgi (pid=12089): Unable to stat Python home /root/django-apps/env. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/root/django-apps/env' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/root/django-apps/env' sys.base_exec_prefix … -
Django REST framework is changing object values when request method is GET
i have problem with (not wanted) objects values setting. I have viewset where serialiser is chosen by request.method. I want to update DateTimeField only WITH POST/PUT method, and then can check this value with GET method but.. after posting new object I got json like this { "datetimefield": "2021-10-26 23:01:53.272194" } and after GET method I got this (for the same object): { "datetimefield": "" } my code: class SomeViewSet(viewsets.ModelViewSet): queryset = SomeModel.objects.all() def get_serializer_class(self): if (self.request.method == 'POST'): return FirstSerializer else: return SecondAppSerializer class FirstSerializer(serializers.HyperlinkedModelSerializer): datetimefield = serializers.SerializerMethodField() def get_datetimefield(self, obj): return str(datetime.today()) class Meta: model = SomeModel fields = ('datetimefield') class SecondSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SomeObject fields = ('datetimefield') class SomeModel(models.Model): datetimefield = models.CharField(max_length=100) Anyone know how to solve this? -
Django serializers methods
I have model called SecondAddress with fields like street, apartment, number, city. For this model I have serializer second_address - with the same fields. This models and serializer are using in Client and Recipient modelserializer as a basic field but not required, it can be null. In the client and Recipient client I have basic_address and this is required. The idea is that if basic_address fields are incorrect, client must to provide second_address fields. Everything works and for checking the status of second_address field I have folowing serializer: matching_address = serializers.SerializerMethodField() And fucntion: def get_matching_address(self, client): return client.second_address is None If basic_address fields is correct there no needed second_address fields and field matching_address will have True. If second_address is provided matching_address field show False. I would like to create function that if matching_address field is True and second_address fields are provided the data must to be deleted from second_address. And if False need to provide second_address fields. Please help me with this function and method -
RegEx length range not working for Django/Python? (re.error: multiple repeat at position)
I'm trying to add a custom Validator with a regex for a-z, A-Z, 0-9, _ and between 3 and 20 characters. class Validator(validators.RegexValidator): regex = r"^[A-Za-z0-9_]{3,20}+\Z" flags = re.ASCII RegEx works fine when there's no character range i.e. r"^[A-Za-z0-9_]+\Z" And I think {3,20} is the correct way of specifying the length... so I'm not sure why the regex isn't working. I get this error re.error: multiple repeat at position 19 regardless of the string that I'm trying to validate. Full traceback: backend-web-1 | Traceback (most recent call last): backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner backend-web-1 | response = get_response(request) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response backend-web-1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view backend-web-1 | return view_func(*args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view backend-web-1 | return self.dispatch(request, *args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper backend-web-1 | return bound_method(*args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper backend-web-1 | return view(request, *args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/dj_rest_auth/registration/views.py", line 47, in dispatch backend-web-1 | return super().dispatch(*args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch backend-web-1 | response = self.handle_exception(exc) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", … -
Caching in django-pytest
In an API Client Library that supports Django, I am implementing a way for users to configure Django Cache when the API Client gets used in a Django application. How do I test the caching behavior without an actual Django app in the Client Library? I have tox set up with pytest-django as a test requirement, and I am getting this error when I run test_django_cache.py: django.core.cache.backends.base.InvalidCacheBackendError: The connection 'django.core.cache.backends.dummy.DummyCache' doesn't exist. # test_django_cache.py import django from django.conf import settings from .django_cache import DjangoCache settings.configure() django.setup() def test_set_get(settings): cache_name = 'django.core.cache.backends.dummy.DummyCache' cache = DjangoCache(cache_name=cache_name) vals = { "status": "live", "configuration": { "name": "features", "value": ["bi_connector", "google_tag_manag Blockquote er"] } } cache_key = 'client.040e0ec3-2578-4fcf-b5db-030dadf68f30.live' cache.set(key=cache_key, value=vals) assert cache.get(key=cache_name) == vals # django_cache.py class DjangoCache: def __init__(self, cache_name, cache_timeout=60): self.cache_name = cache_name self.cache_timeout = cache_timeout self._django_cache = None def get_django_cache(self): if not self._django_cache: from django.core.cache import caches self._django_cache = caches[self.cache_name] return self._django_cache def set(self, key, value): kwargs = {} if self.cache_timeout is not None: kwargs['timeout'] = self.cache_timeout return self.get_django_cache().set(key, value, **kwargs) def get(self, key): return self.get_django_cache().get(key) -
Django LRU_Cache with API Calls
I'm trying to use the Reddit API via PRAW (https://praw.readthedocs.io/en/stable/) with Django, and am thinking of trying to use functools lru_cache decorator to implement some kind of caching so I can cache the results of similar API calls to reduce overall calls being made. I've never done anything like this so I've been mainly following examples of implementing the @lru_cache decorator. I have 3 files that are primarily involved with the API calls / display here. I have: account.html {% extends 'myapp/base.html' %} <h1> {{ name }} </h1> <h3> {{ comment_karma }} </h3> <h5> Top Posts </h5> <table> <tr> <th> Post </th> <th> Subreddit </th> </tr> {% for s in top_submissions %} <tr> <td> {{ s.title }} </td> <td> {{ s.subreddit }} </td> </tr> {% endfor %} </table> views.py from . import reddit reddit = reddit.Reddit() def account_page(): context = reddit.details(request.user.reddit_username) return render(request, 'stats/dashboard.html', context) reddit.py from functools import lru_cache class Reddit: def __init__(self): self.praw = praw.Reddit( client_id = CLIENT_ID, client_secret = CLIENT_SECRET, user_agent = USER_AGENT ) @lru_cache(maxsize = 256) def details(self, redditor): redditor = self.praw.redditor(redditor) overview = { 'name': redditor.name, 'comment_karma': redditor.comment_karma, 'top_submissions': redditor.submissions.top(limit=10), } return overview Here's the problem: when I don't have the lru_cache, then everything works … -
Reverse for 'dome_view' with no arguments not found. 1 pattern(s) tried: ['dome2/(?P<id>[0-9]+)/$']
I have try to send request to external API in order to perform PATCH method. I have a view defined as below: def dome_view(request, id): ...... I need id in order to pass it to form action and make necessary update on other endpoint which is external.My url pattern is like that path('dome2/int:id/', views.dome_view, name='dome_view'), When I put id to my form action like below, i got an error "Reverse for 'dome_view' with no arguments not found. " But when i put the exact id that i want to update, then PATCH method succeded. For example: form action="{% url 'dome_view' 5 %}" method="post"> How can i achieve to successfully send PATCH request without specifiying exact id to form action? I just want to do it like What am i missing? Thanks -
Store multiple files in dabatase, django
I have a model that will contain multiple files. Is it better to create a new model and as a foreign key to set to which object of other model it belongs or is it better to save a object in database in that model, not creating new one. Thanks in advance -
Making all fields in the model formset required in HTML - Django
I have looked at pretty much all questions on Stack Overflow relating to Django Formsets. None of them answer my question in a realistic manner. I have a page that uses an inlineformset_factory. The goal is to have parents add their information and then their students information. I need ALL of the student fields to be required in HTML. So far, only the parent information has the required attribute in HTML. The number of students is passed in as part of the url - example.com/register/3 would be if a parent has 3 students to register. So, if a parent chooses 3 students on the previous page, they would be sent to example.com/register/3 and it would show the parent form with the 3 student forms. THIS IS WORKING. What is not working is making ALL three of the student forms required in the HTML. My view: def homeschoolRegister(request, num): parent_form = ParentInformationForm() StudentFormSet = inlineformset_factory(ParentInformation, StudentInformation, fields=('student_first_name', 'student_last_name', 'grade'), can_delete=False, extra=int(num)) if request.method == 'POST': parent_form_post = ParentInformationForm(request.POST) if parent_form_post.is_valid(): parent = parent_form_post.save(commit=False) parent.save() student_form_post = StudentFormSet(request.POST, instance=parent) if student_form_post.is_valid(): student_form_post.save() try: if int(num) <= 0: return redirect(reverse('home')) if int(num) > 15: return redirect(reverse('home')) context = {'parent_form':parent_form ,'formset':StudentFormSet} return render(request, 'home/home-register.html', … -
Django and uvicorn throwing `closing handshake failed` errors on page load
I am trying to follow some tutorials to set up a Django server on Heroku and add websockets to pass information to and from my front end pages. I think I did everything correctly, however I am getting the following errors when my websocket on the page tries to connect: 5:06:07 PM web.1 | [2021-10-26 21:06:07 +0000] [36593] [ERROR] Exception in ASGI application 5:06:07 PM web.1 | Traceback (most recent call last): 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 203, in run_asgi 5:06:07 PM web.1 | result = await self.app(self.scope, self.asgi_receive, self.asgi_send) 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__ 5:06:07 PM web.1 | return await self.app(scope, receive, send) 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/channels/routing.py", line 74, in __call__ 5:06:07 PM web.1 | raise ValueError( 5:06:07 PM web.1 | ValueError: No application configured for scope type 'websocket' 5:06:07 PM web.1 | [2021-10-26 21:06:07 +0000] [36593] [INFO] connection open 5:06:07 PM web.1 | [2021-10-26 21:06:07 +0000] [36593] [ERROR] closing handshake failed 5:06:07 PM web.1 | Traceback (most recent call last): 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/websockets/legacy/server.py", line 232, in handler 5:06:07 PM web.1 | await self.close() 5:06:07 PM web.1 | File "/Users/bslaght/Library/Python/3.8/lib/python/site-packages/websockets/legacy/protocol.py", line 779, in close 5:06:07 PM web.1 … -
NoReverseMatch at... (Django)
Getting error: Reverse for 'topping' with arguments '('',)' not found. 1 pattern(s) tried: ['topping/(?P<toppings_id>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/pizzas/ Django Version: 3.2.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'topping' with arguments '('',)' not found. 1 pattern(s) tried: ['topping/(?P<toppings_id>[0-9]+)/$'] admin.py: from django.contrib import admin from .models import Pizzas, Toppings admin.site.register(Pizzas) admin.site.register(Toppings) models.py: from django.db import models class Pizzas(models.Model): """A Pizza for the menu.""" pizza = models.TextField() def __str__(self): """Return string of model.""" return self.pizza class Toppings(models.Model): """A topping for each pizza.""" pizza = models.ForeignKey(Pizzas, on_delete=models.CASCADE) topping = models.TextField() class Meta: verbose_name_plural = 'toppings' def __str__(self): return f"{self.topping}" views.py: from django.shortcuts import render from .models import Pizzas def index(request): """The home page for pizzeria.""" return render(request, 'pizzas/index.html') def pizzas(request): """Show all pizzas.""" pizzas = Pizzas.objects.all() context = {'pizzas': pizzas} return render(request, 'pizzas/pizzas.html', context) def topping(request, toppings_id): """Show each topping for a pizza.""" pizzas = Pizzas.objects.get(id=toppings_id) toppings = pizzas.topping_set.all() context = {'pizzas': pizzas, 'toppings': toppings} return render(request, 'pizzas/toppings.html', context) project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('pizzas.urls')), ] app urls.py: from django.urls import path from . import views app_name = 'pizzas' urlpatterns = [ # Home page path('', views.index, name='index'), # Pizza menu path('pizzas/', views.pizzas, name='pizzas'), # Detail page for … -
Implementing SSE with DJANGO and REACT
I'd like to send the log of operations happening on the server to the client, but I'm not sure how. I'm trying to use django channels, but I'm having a hard time detecting DB changes. -
How to fix TemplateDoesNotExist Error on Windows10?
I have been following the tutorial for [Writing your first Django app][1] In part 3, I was trying to use a template. I am working with Python 3.1, Django 3.2 on a Windows10. Below is the error that I get: Django tried loading these templates, in this order: Using engine django: - django.template.loaders.app_directories.Loader: C:\Users\KKK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\admin\templates\polls\index.html (Source does not exist) - django.template.loaders.app_directories.Loader: C:\Users\KKK\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\templates\polls\index.html (Source does not exist) Below is my file structure: mysite +-- mysite | +--settings.py | +--other files +-- polls | +--templates | | +--polls | | | +--index.html | +--views.py | +--other files +-- db.sqlite3 +-- manage.py` I added a reference to polls configuration class in the INSTALLED_APPS setting. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Any help would be appreciated. -
Django post_migrate signal been called multiple times
I have created a post_migrate with the goal to sync all the data inside the table whenever a migration runs. This is the snippet of the post_migrate file: # signals.py @receiver(post_migrate) def full_sync_if_model_change(plan, **kwargs): if plan: models_set = set() for file, _ in plan: for model in file.operations: try: model = SyncModel.objects.get( app_name=file.app_label, model_name=model.model_name ) models_set.add(model) except ObjectDoesNotExist: pass print(models_set) if models_set: for model in models_set: model.set_full_sync() run_update_sync(model, False) return However, when I run a migration, it is called 6 times; as you can see in the output of migration: evandro@evandro-340XAA-350XAA-550XAA:~/Desktop/.../test_service$ python3 manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, django_cron, lakehouse_sync, sessions, test_models Running migrations: Applying test_models.0019_auto_20211026_2052... OK set() set() set() set() set() set() I'll add here also the apps file: class LakeSyncConfig(AppConfig): name = "lake_sync" def ready(self): """Import signals""" import lakehouse_sync.core.delete_action from . import signals I have no idea what to do, I tried to add this return statement, but it doesn't work, because the function is called all the time. -
django form input not showing on frontend/html
so I'm working with django forms to create a software for an ice cream company and I'm having trouble with my django forms to show up on the front end of my website. I was able to have customer information show up but the customer's order won't show and I am confused what's going on. orderentry.html <!--Basic Customer Information--> <form method = "post"> {% csrf_token %} {{ form.as_p }} {{ newOrder}} <button type = "submit">Place your order!</button> </form> views.py from django.http.response import HttpResponseRedirect from django.shortcuts import render, redirect from django.http import HttpResponse import orderentry from orderentry.forms import customerForm, customerInformation def getCustomerInfo(request): form = customerForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save() orderentry.forms.customer_first_name = form.cleaned_data['customer_first_name'] orderentry.forms.customer_last_name = form.cleaned_data['customer_last_name'] orderentry.forms.shipping_address = form.cleaned_data['shipping_address'] orderentry.forms.billing_address = form.cleaned_data['billing_address'] return redirect('/orderentry') else: form=customerForm() return render(request, 'orderentry.html', {'form' : form}) def getCustomerOrder(request): newOrder = customerInformation(request.POST) if request.method == 'POST': if newOrder.is_valid(): newOrder.save() #orderentry.forms.order_Item_Flavor = newOrder.cleaned_data['order_Item_Flavor'] orderentry.forms.half_Pint_Count = newOrder.cleaned_data['half_Pint_Count'] orderentry.forms.one_Quart_Count = newOrder.cleaned_data['one_Quart_Count'] orderentry.forms.pint_Count = newOrder.cleaned_data['pint_Count'] orderentry.forms.half_Gallon_Count = newOrder.cleaned_data['half_Gallon_Count'] orderentry.forms.gallon_Count = newOrder.cleaned_data['gallon_Count'] orderentry.forms.cost = newOrder.cleaned_data['cost'] return redirect('/orderentry') else: print("error") else: newOrder=customerInformation() return render(request, 'orderentry.html', {'newOrder' : newOrder}) forms.py from django import forms from django.forms import ModelForm from orderentry.models import customerInfo, orderInfo class customerForm(forms.ModelForm): customer_first_name = forms.CharField(max_length=30) customer_last_name = forms.CharField(max_length=30) … -
change rendered form html in views django rest-framework
Hi i don't know react yet so i create panels using DRF with swagger and html render using Serializer and in serializer i need data token but in login panel i don't need. I want change it but in views but i dont know now how change meta data in create field: in if request.accepted_renderer.format == 'html': my views: class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer style = {'template_pack': 'rest_framework/vertical/'} template_name = "accounts/login_panel.html" def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] if user is not None and user.tokens is not None: login(request, user) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get_queryset(self): if self.request is None: return CreateUser.objects.none() return CreateUser.objects.all() def get(self, request): serializer = LoginSerializer() if request.accepted_renderer.format == 'html': return Response( {'serializer': serializer, 'style': self.style, 'messages': 'Logging'}, template_name=self.template_name) elif request.accepted_renderer.format == 'json': new_data = { 'messages': 'Logged in successfully' } new_data.update(serializer.data) return Response(new_data, status=status.HTTP_200_OK) else: return Response({'error': 'Invalid format'}, status=status.HTTP_400_BAD_REQUEST) -
How to send selected files in DJANGO
if (window.FileList && window.File && window.FileReader) { document.getElementById('file-selector').addEventListener('change', event => { console.log(window.FileList, window.File, window.FileReader) // output.src = ''; status.textContent = ''; const file = event.target.files[0]; const size = event.target.files[0].size / 1e+6 var name = event.target.files[0].name; var file_html = `<div class="col-6"> <div class="d-flex border file-upload-box p-3"> <div class="col-10 info d-flex flex-column justify-content-center"> <h3 class="size-10 font-weight-500">${name}</h3> <p class="text-label size-10 m-0">${size}MB</p> </div> <div class="col-2 close d-flex align-items-center"> <i class="fas fa-times bg-gray" role="button" onclick="removeFile(this)"></i> </div> </div> </div> `; document.getElementById('files').innerHTML += file_html; if (!file.type) { status.textContent = 'Error: The File.type property does not appear to be supported on this browser.'; return; } if (!file.type.match('text.*|image.*|application.*')) { status.textContent = 'Error: The selected file does not appear to be an image.' return; } const reader = new FileReader(); reader.addEventListener('load', event => { // output.src = event.target.result; }); reader.readAsDataURL(file); }); } <form method="POST" enctype="multipart/form-data" id="accept-offer-form"> <input type="file" id="file-selector" /> <div class="files"></div> </form> This is working, but how can I send this files using javascript. I'm trying to do this document.getElementById("accept-offer-form").addEventListener("submit", function (e) { let form = $("form");.serialize(); $.ajax({ url: window.location.origin + "/maca/macaok/" + maca_id + "/accept-maca/", success: function (response) { window.location.href = response.url }, error: function (err) {} }); }) I want to accept files in views.py as request.FILES … -
Deploy django app from gitlab ci/cd to heroku
I'm trying to deploy a django web app to heroku from gitlab ci/cd pipeline. Here's my the deploy part of my .yml deploy: type: deploy script: - apt-get update -qy - apt-get install -y ruby-dev - gem install dpl - dpl --provider=heroku --app=$HEROKU_APP_NAME --api-key=$HEROKU_API_SECRET_KEY only: - main And here's the pipeline error: Deploying application uploading application archive triggering new deployment -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/usr/lib/python3.8/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input ) is not available for this stack (heroku-20). It laments about an encoding error... I'm a bit lost -
Django Static url not working with {% static %}
I have my static files being stored in DigitalOcean CDN. I have multiple spaces 1 for clients and 1 for static assets and I use django-storages. Here is my config: AWS_S3_REGION_NAME = 'nyc3' AWS_S3_ENDPOINT_URL = f'https://{AWS_S3_REGION_NAME}.digitaloceanspaces.com' AWS_DEFAULT_ACL = 'private' AWS_DEFAULT_BUCKET = 'exactestate-staging' AWS_RESOURCE = session.resource('s3', region_name=AWS_S3_REGION_NAME, endpoint_url=AWS_S3_ENDPOINT_URL, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) AWS_CLIENT = boto3.client('s3', region_name=AWS_S3_REGION_NAME, endpoint_url=AWS_S3_ENDPOINT_URL, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) # Django’s STATIC_URL must end in a slash and the AWS_S3_CUSTOM_DOMAIN must not. It is best to set this variable independently of STATIC_URL. AWS_S3_CUSTOM_DOMAIN = f'{AWS_DEFAULT_BUCKET}.{AWS_S3_REGION_NAME}.digitaloceanspaces.com' STATIC_URL = f'https://{AWS_DEFAULT_BUCKET}.{AWS_S3_REGION_NAME}.digitaloceanspaces.com/static/' STATICFILES_STORAGE = 'storage_backends.StaticStorage' For some reason if I do not have: AWS_S3_CUSTOM_DOMAIN = f'{AWS_DEFAULT_BUCKET}.{AWS_S3_REGION_NAME}.digitaloceanspaces.com' set, my {% static %} tag uses the AWS_S3_ENDPOINT_URL as the value...but I need it to use what I set for AWS_S3_CUSTOM_DOMAIN. Normally setting AWS_S3_CUSTOM_DOMAIN would be fine but now all file.url calls also go to static instead of my client space...how can I fix this? -
How to get the value of input on button click in django
I have a django template as follows <table class="table"> <thead> <tr> <th>#</th> <th>Master Title</th> <th>Retailer title</th> <th>To add</th> </tr> </thead> <tbody> {% if d %} {% for i in d %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{i.col1}}</td> <td>{{i.col2}}</td> <td> <input type="hidden" name='row_value' value="{{i.col1}}|{{i.col2}}"> <a class='btn btn-success' href="{% url 'match' %}">Match</a> <a class='btn btn-outline-danger' href="{% url 'mismatch' %}">Not a Match</a> </td> </tr> {% endfor %} {% endif %} </tbody> </table> When the match button is clicked, I want to retireve the value of the hidden input in the views. Here is my views.py def match(request): print(request.GET.get('row_value')) print('match') But this returns None. I want the values of col1 and col2 to be printed as follows col1|col2 I am not sure where I am going wrong. -
serializer_action_class not working in modelviewset in DRF
I am trying to make serializer class dynamic, but its not working. I have a default serializer class where as a dynamic serializer class for different actions. Here it is my modelviewset. My view: class ClassView(viewsets.ModelViewSet): queryset = Class.objects.all() serializer_class = ClassSerializer serializer_action_classes = { 'put': AddStudentstoClassSerializer, } def get_serializer_class(self): """ returns a serializer class based on the http method """ try: return self.serializer_action_classes[self.action] except (KeyError, AttributeError): print("iam ClassSerializer") return super(ClassView, self).get_serializer_class() My function inside the same modelviewset above @action(detail=True, methods=['put']) def add_remove_students(self, request, *args, **kwargs): ................ MY url is as below: urlpatterns = [ path("class/<int:pk>/<slug:slug>/",views.ClassView.as_view({"put": "add_remove_students"}), ), ] Here in the above code snippet, I try to get AddStudentstoClassSerializer inside the add_remove_students function but it is not working. As we can see the print("iam ClassSerializer") code is working, however what i wanted or AddStudentstoClassSerializer. -
Django limit next post and previos post on Detail view to only active
I currently have a model view as such from django.db import models from django.contrib.auth.models import User from django.utils import timezone STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blog_posts" ) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("post_detail", kwargs={"slug": str(self.slug)}) and my view looks like so class PostDetail(DetailView): model = Post template_name = 'post_detail.html' and my template looks like so <ul class="text-center"> {% if post.get_previous_by_created_on_active %} <li class="prev"> <a rel="next" href="{{ post.get_previous_by_created_on.get_absolute_url}}"> {{ post.get_previous_by_created_on_active}}</a> </li> {% endif %} {% if post.get_next_by_created_on %} <li class="next"> <a rel="next" href="{{ post.get_next_by_created_on.get_absolute_url}}"> {{ post.get_next_by_created_on}} </a> </li> </ul> Is there any way I can pass the status == 1 to the get_next_by_created_on so it always shows the next active post, not the next draft post? -
SystemCheckError: System check identified some issues: (models.E006)
I'm trying to make a Tic Toc Toe game with Django but I have a problem with models. you can see the error here. two lines are marked here. they are error lines and the code worked without these lines, but I need these fields. note: I'm using python3.10 and before starting the project I checked to see if django works for it. ALSO see here for more information about the TextFields. players/models.py scripts: from django.db import models as m from json import dumps, loads class Match(m.Model): player1 = player2 = m.ForeignKey('Player', on_delete=m.CASCADE) started_at = m.DateTimeField() tables = m.TextField() class Player(m.Model): points = m.IntegerField(default=0) matchs_played = m.IntegerField(default=0) speed_average = m.FloatField(null=True) last_game = m.ForeignKey(Match, on_delete=m.CASCADE) class Table(m.Model): starter = rival = m.ForeignKey(Player, on_delete=m.CASCADE) match = m.ForeignKey(Match, on_delete=m.CASCADE) raw_items = m.TextField(default=dumps([[[0, .0] for _ in range(3)] for _ in range(3)])) # [[[0, .0] * 3] * 3] def __init__(self, *, starter, rival, match, items: list[list[list[int]]]): # TODO: convert list to json object super().__init__(starter=starter, rival=rival, match=match, raw_items=loads(items)) @property def items(self) -> list[list[int]]: return loads(self.raw_items) @items.setter def items(self, value: list[list[int]]) -> None: self.raw_items = dumps(value) ... # other methods and error: (venv) X:...>py manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: players.Match.player1: (models.E006) … -
If-statement in a for loop in Django disappears when executing
I am building a chatbot using Django that can take survey's preset answer choices and give different scores to different answer choices. After that, the chatbot will sum all the scores accordingly and print out the results. This is a sample question with preset answer choices <select name="survey1-q" data-conv-question="Bạn có hay nghĩ về một điều sẽ xảy ra trong tương lai theo hướng tồi tệ, thậm chí rất tiêu cực?"> <option value="survey1-never">Không bao giờ</option> <option value="survey1-rarely">Hiếm khi</option> <option value="survey1-sometimes">Đôi khi</option> <option value="survey1-often">Thường xuyên</option> <option value="survey1-veryoften">Rất thường xuyên</option> </select> This is my if-statement inside a for loop <!--looping and getting the survey's result--> {% for i in survey1-q%} {% if survey1-q is "Không bao giờ"%} {{score}}={{score + 0}} {% elif survey1-q is "Hiếm khi" %} {{score}}={{score + 1}} {%elif survey1-q is "Đôi khi"%} {{score}}={{score + 2}} {%elif survey1-q is "Thường xuyên"%} {{score}}={{score + 3}} {%elif survey1-q is "Rất thường xuyên"%} {{score}}={{score + 4}} {%endif%} {% endfor %} <p>Điểm của bạn là {{score}}</p> However, after the survey's questions are finished, the chatbot automatically load back to the beginning stage and ask the first question instead of printing the {{score}} I am afraid I had been wrong in calling out the variables in … -
Automatic login in Django
Hi I'm writing app in Django and I thougt about automatically login "user 0" just for convinience, and when someone tries to log in or register it automatically logs out of "user 0" and lets login to normal user, but I'm not sure how to implement that.