Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
request BETWEEN in fastapi orm
async def get_all( self, session: AsyncSession, order_field: str | None = 'created_at', is_desc: bool | None = False, **param ): if order_field is not None: if is_desc: k = desc(order_field) else: k = order_field else: k = 'created_at' objs = await session.scalars(select(self.__model).filter_by(**param).order_by(k)) return objs.all() I have legacy code that returns all objects from the database. Im need to change the code, or create a new method to return objects whose registration date is between two datetime dates. At the moment, I'm just clinging to all the objects and cutting off unsuitable data in the code, but this option is clearly not optimal at all. In django orm, everything is somehow simple, but here I have scoured the entire Internet and have not found any built-in options in order to implement this. Thank you in advance for your help <3 -
ModuleNotFoundError at /accounts/login/ No module named 'allauth.forms'
Iam trying to add allauth login and signup in my project and getting this error *ModuleNotFoundError at /accounts/login/* *No module named 'allauth.forms'* This is the traceback ` Traceback (most recent call last): File "/var/data/python/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/utils/decorators.py", line 48, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/decorators.py", line 12, in wrap resp = function(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/utils/decorators.py", line 48, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/decorators/debug.py", line 143, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/utils/decorators.py", line 48, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/decorators/cache.py", line 80, in _view_wrapper response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/views.py", line 84, in dispatch return super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/mixins.py", line 40, in dispatch response = super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/mixins.py", line 59, in get response = super().get(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/django/views/generic/edit.py", line 142, in get return self.render_to_response(self.get_context_data()) ^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/views.py", line 102, in get_context_data ret = super().get_context_data(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/data/python/lib/python3.11/site-packages/allauth/account/mixins.py", line 122, in … -
Strange Behavior with Django Serializers [closed]
Hey i'll try to summerize the current situation: i believe the higher level scope of this method isn't really required to understand the situation as the problem lays between syntax? or just bad programming on my part: i have this method: it's exact working are not really useful as it is being created to make an unclear request possible, on a poorly written structure (not my doing) in the first part i am creating an instance of FasiPrestazionali via the Serializer, subsequently i save that instance and copy it inside a variable fase_instance as fase_id late i successfully use it here: commessa.fase_prestazionale.add(fase_id) now i want to know why i by repeating the same thing with just a different model fase_id = fase_instance.id django tells me that fase_instance.id does not exist? class PreventivoStudioForm(generics.ListCreateAPIView): queryset = PreventivoStudio.objects.all() serializer_class = PreventivoStudioSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] #primo caso in presenza di commessa_id : creare un PreventivoStudio con i dati forniti e ciclare le fasi rendendole ciascuna una fasePrestazionale legata alla commessa fornita def post(self, request, *args, **kwargs): studio_id = request.data.get("id") commessa_id = request.data.get("commessa_id") if commessa_id: commessa = Commesse.objects.get(id=commessa_id) studio = Studio.objects.get(id=studio_id) #riassociazione di 'fasi' dentro la request per ciclarli come FasiPrestazionali fasi … -
Django model's relationships and fetching related data from database
I'm having a hard time finding a decent explanation about this in django's official documentation, so I'll ask my question here. in django 5.0 if two models have a relationship (let's call them Model1 and Model2) with whether a OneToOneField, ForeignKey or ManyToManyField , when you fetch some objects from the database with a query like this : data = Model1.objects.filter(field1=value) do the Model2 objects related to the objects in data (which are of the type Model1) get fetched and joined to the queryset automatically? note that the relationship might be of any type (one-to-one , many-to-one, many-to-many) and can be a reverse or forward relationship. if the answer to my question depends on the type of relationship between two objects, please explain all the possible cases. if you know where exactly I can read about this, please leave me a link. I've tried asking a bunch of AIs about this but they just confused me with contradictory answers. -
how to override a google auth screen with a custom template
I want a custom template in the url http://accounts/google/login. How do I do it.I just want some stying in it with CSS. Suggest a stepwise solution.Should I try custom template but where do i place it and what to name it. I want to remove the menu div. I have no idea what to do. so i tried nothing -
Django Form request.POST.get() returning None in terminal
So I'm trying to retrieve one element from a form but everytime I get None as value instead of a name for example. Below the form html : <form method="post" action="/contact"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" aria-describedby="name" placeholder="Enter your name"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="Phone">Phone</label> <input type="phone" class="form-control" id="Phone" placeholder="Enter your phone number"> </div> <div class="form-group"> <label for="text">Text</label> <input type="text" class="form-control" id="Description" placeholder="Enter your message"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> And my view.py : def contact(request): if request.method =='POST': print(request.POST.get('name')) return render(request, 'contact.html') Any tips or ideas on how to solve this ? Thanks -
Hosting Django Web Application as an application on an existing website
I hosted a django web app on IIS using wfastcgi and it was successful when hosted as a new website using the configuration details below. What would I need to do differently on these configurations if I want to host the very app as an application to an existing IIS website on production. I have tried copying the very configuration and placing it it in the root of the IIS application but finding error 500 - internal server error. The IIS user already has read, execute and edit permissions on the app folder. <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="WSGIHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\pathtopython\Scripts\python.exe|C:\pathtowfastcgi\Scripts\wfastcgi.py" resourceType="Unspecified" /> </handlers> <rewrite> <rules> <rule name="Django" stopProcessing="true"> <match url=".*" /> <action type="Rewrite" url="http://localhost:8000/{R:0}" /> </rule> </rules> </rewrite> </system.webServer> </configuration> -
pytest Database access not allowed
I am trying to run my tests with access to an existing database to reuse it. Here is the error: ERROR drf/tests/test_auth.py - RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. here is the pytest.ini [pytest] DJANGO_SETTINGS_MODULE = drf.tests.test_settings python_files = test_*.py django_debug_mode = true pythonpath = .venv/bin/python addopts = --reuse-db --create-db here is the test_settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR + '/tests', 'dump_test.sql'), } } Here is a simplified version of the test: @pytest.mark.django_db class AuthTestCase: def test_two_step_authentication(self): user = UsersFactory.create() # Initialize the API client client = APIClient() # Step 1: Authenticate the user to get the initial token url_step1 = reverse('token-auth-s1') credentials = { 'email': user.email, 'password': 'password123' } response_step1 = client.post(url_step1, credentials, format='json') # Assert the response status code assert response_step1.status_code == 200 The directory structure: drf ├── drf │ ├── __init__.py │ ├── settings.py │ ├── tests │ │ ├── __init__.py │ │ ├── dump_test.sql │ │ ├── factory_boy │ │ │ ├── __init__.py │ │ │ ├── factory_models.py │ │ │ └── languages_factory.py │ │ ├── test_auth.py │ │ └── test_settings.py ├── manage.py └── pytest.ini List of things I have … -
It becomes to array when sending djang nested dict to API
I sent the dict data with this in python data = { "test":{ "A":"Adata", "B":"Bdata", "C":"Cdata" } } response = self.client.post("/api_patch/",data,follow=True) then receive this as @api_view(["POST","GET"]) def api_patch(request): print("request.data",request.data) print("request.data type",type(request.data)) However this shows, request.data <QueryDict: {'test': ['A', 'B', 'C']}> request.data type <class 'django.http.request.QueryDict'> some how A B C is treated as array. Where am I wrong?? -
Foreignkey Django separator
There is a model: class Categories(models.Model): name = models.CharField(max_length=150, unique=True, verbose_name='Name') slug = models.SlugField(max_length=200, unique=True, blank=True, null=True, verbose_name='URL') class Products(models.Model): name = models.CharField(max_length=150, unique=True, verbose_name='Name') slug = models.SlugField(max_length=200, unique=True, blank=True, null=True, verbose_name='URL') category = models.ForeignKey(to=Categories, on_delete=models.PROTECT, verbose_name='Categoy') I don't understand how to make it so that in Products I could write category_id separated by commas. That is, so that one product would have different categories. Are there any separator arguments for Foreignkey? For example, I will show my idea with pseudocode category = models.ForeignKey(to=Categories, on_delete=models.PROTECT, separator=';') -
Manually Adding Swagger Documentation Does Not Show Example Values in Responses Section
I have a simple django rest API project with some endpoints. I have installed swagger API documentation for viewing and testing APIs. as you know the APIs that are dependent on models and serializers will be added to the swagger documentation automatically and there is no problem with them. I have another view which is not related to a model or serializer so I wrote the swagger code for it manually. now the problem I faced is that the example values of the Responses section in this endpoint are not loaded and a circle is just turning! here is the code and the image of swagger: import requests from django.shortcuts import render from store.models import Customer from .serializers import CustomerSerializer from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema class Verification(APIView): @swagger_auto_schema( request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'phone': openapi.Schema(type=openapi.TYPE_STRING, description='Phone number to verify'), 'token': openapi.Schema(type=openapi.TYPE_STRING, description='Verification token sent via SMS') }, required=['phone', 'token'] ), responses={ 200: openapi.Response( description='Successful verification', examples={ 'application/json': { 'status': True, 'detail': '200, your entered token matched.', } } ), 400: openapi.Response( description='Invalid input or verification failed', examples={ 'application/json': { 'status': False, 'detail': … -
Django: Base template does not render content from {% block content%} on HTML page
I am trying to use a template to be able to reuse a flexbox across multiple pages; rather than reuse the code on each page. However, rather than getting the flexbox I get: If I just render the html as a page to be sure the flexbox works I get the expected output: My html templates are all located in: /Resilience_Radar/Resilience_Radar_App/templates/Resilience_Radar_App/ I setup the layout.html file to include the stylesheet defining the container and added teh templates tags: <!DOCTYPE html> <html lang = "en"> <meta name="viewport" content="width=device-width, initial-scale=1"> <head> <link rel="stylesheet" href="styles.css"> <title>Resilience</title> </head> <body> <h1>Risk Resilience</h1> {% block linesofoperation %} {% endblock %} </body> </html> I the created a file linesofoperation.html that contained the desired code to use in the block: {% extends "layout.html" %} {% block linesofoperation %} <div class="container" style="top: 10%;"> <div class="item_LoO_Name"> <div class="t1">LoO</div> <div class="t2">Implement, maintain and improve a business countinuity management system</div> </div> <div class="space"></div> <div class="item">Context of the Organization</div> <div class="space"></div> <div class="item" style = "background-color:gray">Leadership</div> <div class="space"></div> <div class="item" >Policy</div> <div class="space"></div> <div class="item">Planning</div> <div class="space"></div> <div class="item">Support</div> <div class="space"></div> <div class="item">Operation</div> <div class="space"></div> <div class="item">Management Review</div> <div class="space"></div> <div class="item">Improvement</div> <div class="space"></div> <div class="triangle-right"></div> <div class="spaceblank"></div> <div class="item_LoO_Name" style="background-color: white; color: … -
How to use django/jinja tags to extend an html with a javascript snippet from another .js file
I am developing a django app. There is a file templates/index.html file having some javascript snippets at its footer, such as ... </body> </html> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <!-- load jquery. I put this after leaflet --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- import a library leaflet.browser.print from local folder lib placed in the staticfiles folder --> <script src="{% static './lib/leaflet.browser.print.min.js' %}"></script> There is also a file templates/publish_layers_in_html_page.html which contains a javascript snippet using jinja tags, the content is the following <script> var overlayMaps = {}; // Shapefile wms {% for s in shp %} var {{ s.name }} = L.tileLayer.wms('http://localhost:8080/geoserver/wms', { layers: '{{s.name}}', transparent: true, format: 'image/png', }) overlayMaps['{{ s.name }}'] = {{ s.name }} {% endfor %} L.control.layers(baseMaps, overlayMaps, {collapsed: false, position: 'topleft'}).addTo(map) </script> Is it possible to use django tag {% extends %} to insert this javascript snippet into the index.html file? I have tryed to change the two files as follows, but with no success. index.html ... </body> </html> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <!-- load jquery. I put this after leaflet --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- import a library leaflet.browser.print from local folder lib placed in the staticfiles folder --> <script src="{% static './lib/leaflet.browser.print.min.js' %}"></script> {% block scripts %}{% endblock %} publish_layers_in_html_page.html {% extends … -
Jdango arm join the same table twice using alias
We are using jango models. I'd need to add one more condition to join the same table twice with different conditions. Sample query: select shop_id from shop_to_warehouse_mapping inner join warehouse w1 on w1.id = shop.warehouse_id inner join warehouse w2 on w2.id = shop.warehouse_id where w1.type='daily_life' and w2.type='produce' We have shop to warehouse mappings, that's many to many. I'd like to get the shop ids that are working with both warehouse 1 and 2. In the Django models, we have the foreign key of warehouse on the shop to warehouse mapping model. How can I use filter method to represent this? If I could using alias somehow in the filter, that'd be great. Any help's appreciated! (I'd love to write the query directly, but this query's complex having many other conditions already). thanks! -
Elegant way to add a link next to the APP name in Django Admin
See photo below, I want to add a link next to "APP1", I had searched google and seems only one way to do it by overriding the admin template app_list.html then see if app name is "APP1" then add the link. <caption> <a href="{{ app.app_url }}" class="section" title="{% blocktranslate with name=app.name %}Models in the {{ name }} application{% endblocktranslate %}">{{ app.name }}</a> </caption> I've tried the verbose_name approach but it didn't want render properly even with mark_safe(), let alone what else this verbose_name will be used and cause more issues, so I am opting out this approach. verbose_name = mark_safe('APP1 <a href="/somehwere">link</a>') So apart from overriding the template, is there anything else I can do? -
Cron is not inheriting environment variables in Docker container
I am trying to run cron inside a Docker container to periodically update my database, perform backups, etc. Here is my cron job configuration: */1 * * * * (. /app/.env.development; echo $DJANGO_COLOR) >> /var/log/cron.log 2>&1 */1 * * * * (. /app/.env.development; /usr/local/bin/python3 /app/src/manage.py command) >> /var/log/cron.log 2>&1 */1 * * * * (export $(cat /app/.env.development | grep -v "^#" | xargs); /usr/local/bin/python3 /app/src/manage.py command) >> /var/log/cron.log 2>&1 The problem: The cron job does not inherit the environment variables from my Docker container. I tried loading the environment variables with . /app/.env.development, which works for the first line, but for some reason, the Django server runs without the environment variables in the second and third lines. The cronjob Dockerfile: FROM app as cron RUN apt-get update && apt-get -y install cron # Copy hello-cron file to the cron.d directory COPY cron/app-cron /etc/cron.d/app-cron # Give execution rights on the cron job RUN chmod 0644 /etc/cron.d/app-cron # Apply cron job RUN crontab /etc/cron.d/app-cron # Create the log file to be able to run tail RUN touch /var/log/cron.log Entrypoint: /bin/bash -c "cron && tail -f /var/log/cron.log" Can you please explain why this is happening? How can I ensure that the cron job … -
CSS not working after applying collectstatic in Django
I just deployed my django project on nginx server. I have connected with domain and everything, site is live. However, the issue occured when I used python3 manage.py collectstatic. Everything still works, but css is not loaded and site is not looking how it supposed to be. Here is some code and options that I tried. parts from settings.py BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['my-wow-site.com', 'www.my-wow-site.com', 'xx.xx.xxx.xx'] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] urls.py urlpatterns = i18n_patterns( path(_('admin/'), admin.site.urls), path('rosetta/', include('rosetta.urls')), path('', include('main_app.urls', namespace='main_app')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('ckeditor/', include('ckeditor_uploader.urls')), ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) I have everything uploaded/deployed in root folder... and I have set up this by using command sudo nano /etc/nginx/sites-available/default content is... server { listen 80; server_name my-wow-site.com www.my-wow-site.com; return 301 https://$host$request_uri; root /root/wow_site/ location /static/ { alias /root/wow_site/staticfiles/; } location /media/ { alias /root/wow_site/media/; } } server { listen 443 ssl; server_name my-wow-site.com www.my-wow-site.com; ssl_certificate /etc/nginx/ssl/nginx.crt; ssl_certificate_key /etc/nginx/ssl/nginx.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { proxy_pass http://localhost:8000; # Adjust as necessary for your application proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Usually sources … -
Django wizard form and htmx partials
I am building a django wizard form with multiple form, however in one of the forms i have a field of small list of sectors, and when the user select a sector i trigger a function that fetches the sub-sectors of that particular sector. the problem is when i tested the form in a separated html template it works fine, but when i use it in my wizard form it does not update the ui even though in the console i can see that the request was successful. #urls.py from django.urls import path # type: ignore from django.utils.translation import gettext_lazy as _ # type: ignore from core import views app_name = 'core' urlpatterns = [ path('', views.OnboardingSessionWizardView.as_view(views.FORMS), name='start'), path('sub-sectors/', views.get_subsectors, name='get-sub-sectors'), path('get-started/', views.OnboardingSessionWizardView.as_view(views.FORMS), name='get-started'), ] here is my view.py: from core.forms import * from formtools.wizard.views import SessionWizardView # type: ignore from django.http import HttpResponse, JsonResponse, HttpRequest # type: ignore from django.utils.translation import gettext_lazy as _ # type: ignore from django.shortcuts import render,get_object_or_404 # type: ignore from django.core.serializers import serialize # type: ignore from core.models import * from core.forms import * # Create your views here. FORMS = [("contact", EntryInformationForm), ("information", PersonalInformationForm), ("business", BusinessActivityForm), ("address", BusinessAddressForm), ] TEMPLATES = { "contact": … -
How to implement follow/unfollow functionality without reloading the page in Django
I am building a web application using Django where users can follow or unfollow items (e.g., photos) from a list. Currently, I have implemented the follow/unfollow functionality, but it reloads the page every time the user clicks on follow or unfollow. I want to achieve this without reloading the page, so the user stays on the same page and the state changes (follow/unfollow) are reflected immediately. models.py class UserProfile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) follows = models.ManyToManyField(Photo, related_name='followers') def __str__(self): return self.user.username views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from .models import Photo, Episode, UserProfile def viewPhoto(request, pk): photo = get_object_or_404(Photo, id=pk) episodes = Episode.objects.filter(photo=photo) if request.user.is_authenticated: user_profile, created = UserProfile.objects.get_or_create(user=request.user) is_following = photo in user_profile.follows.all() else: is_following = False context = { 'photo': photo, 'episodes': episodes, 'is_following': is_following, } return render(request, 'photos/photo.html', context) @login_required def follow(request, pk): photo = get_object_or_404(Photo, id=pk) user_profile, created = UserProfile.objects.get_or_create(user=request.user) user_profile.follows.add(photo) return redirect('photo', pk=pk) @login_required def unfollow(request, pk): photo = get_object_or_404(Photo, id=pk) user_profile, created = UserProfile.objects.get_or_create(user=request.user) user_profile.follows.remove(photo) return redirect('photo', pk=pk) html {% if is_following %} <div class="btn follow"> <a href="{% url 'unfollowPhoto' photo.id %}">Unfollow</a> </div> {% else %} <div class="btn follow"> <a href="{% url 'followPhoto' photo.id %}">Follow</a> </div> {% endif %} … -
Django RF deserialization
In django rest framework when we call post request in which we send json data to be saved in database.so how django RF handle this request and how will it receive json data how will it convert into python native and then complex data type? What's the role of Bytes io function in this? I just can't understand process. -
In Django with DjangoCMS how do I reverse an URL when using the sites framework (the URL is on a different site)?
I have a Django install with DjangoCMS and ~20 sites (with Djangos sites framework). I would like to create a link from one site (https://a.example.com/) to another site (https://b.example.com/). For example I have an CMSApp called persons and a single URL for example https://a.example.com/en/person/aaa/ and https://b.example.com/de/team/aaa/. If I try to reverse it like this on a.example.com: reverse("persons:canonic-person", kwargs={"person_slug": self.slug}) I get: /en/person/aaa/ But I want to be able to switch to b.example.com and get /de/team/aaa/ or even better: https://b.example.com/de/team/aaa/. How do I achieve that? -
How to resolve that after searching request a property name has changed to a property id?
I am using a React Native Expo web app for the frontend and Django for the backend. I have a search function that works fine. But the problem I am facing is that after a search term the property name of a specific animal has changed to a property id (number). What I mean with this is that in the accordion the category name is shown. But after the search the category id is displayed. In the frontend I have an accordion with some properties. The property for category looks: export const AccordionItemsProvider = ({ children }) => { const [categoryExpanded, setCategory] = useState(false); const accordionItems = (item) => { return ( <> <List.Accordion title="Familie" expanded={categoryExpanded} onPress={() => setCategory(!categoryExpanded)}> <Text>{item.category}</Text> </List.Accordion> </> ); }; return ( <AccordionItemsContext.Provider value={{ accordionItems, }}> {children} </AccordionItemsContext.Provider> ); }; So the name of category will be displayed. But after the search the id of category will be displayd. And not the name. The search context of animal looks: /* eslint-disable prettier/prettier */ import React, { createContext, useEffect, useState } from "react"; import { fetchAnimalData } from "./animal/animal.service"; import useDebounce from "../hooks/use-debounce"; export const SearchAnimalContext = createContext(); export const SearchAnimalContextProvider = ({ children }) => { … -
Error processing file n.mp4: int() argument must be a string, a bytes-like object or a real number, not 'list'
i am trying to convert and compress the given videos to the given video format but getting the following error: Error processing file n.mp4: int() argument must be a string, a bytes-like object or a real number, not 'list'. i don't know why the function convert_video_to_video is taking compression_percentage as a list. following is my django view: import os import io import zipfile import re import logging import subprocess from concurrent.futures import ThreadPoolExecutor from django.conf import settings from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from moviepy.editor import VideoFileClip import boto3 from moviepy.video.fx import all as vfx from asgiref.sync import async_to_sync from channels.layers import get_channel_layer logger = logging.getLogger(__name__) class CompressVideoView(APIView): def post(self, request, *args, **kwargs): logger.debug("Received video conversion request") files = request.FILES.getlist('files') s3 = boto3.client('s3') bucket_name = settings.AWS_STORAGE_BUCKET_NAME folder = 'videos/' video_formats = request.data.getlist('formats') screen_size = request.data.getlist('screen_size', 'no-change') frame_rate = request.data.getlist('frame_rate', 'no-change') rotate = request.data.getlist('rotate', 'no-change') flip = request.data.getlist('flip', 'no-change') subtitle = request.data.getlist('subtitle') copy_subtitles = request.data.getlist('copy_subtitles') remove_subtitles = request.data.getlist('remove_subtitles') volume = request.data.getlist('volume') fade_in = request.data.getlist('fade_in') fade_out = request.data.getlist('fade_out') remove_audio = request.data.getlist('remove_audio') trim_start_h = request.data.getlist('trim_start_h', 0) trim_start_m = request.data.getlist('trim_start_m', 0) trim_start_s = request.data.getlist('trim_start_s', 0) trim_end_h = request.data.getlist('trim_end_h', 0) trim_end_m = request.data.getlist('trim_end_m', 0) trim_end_s = request.data.getlist('trim_end_s', 0) # … -
Request.session in django doesnt pass through ajax unless i refresh the page
Request.session in django doesnt pass through ajax unless i refresh the page request.session remains the old one unless i hit refresh to the page any help would appreciated ` $(document).ready(function () { $("#specialty_form").on('change', function (event) { event.preventDefault(); function getCSRFToken() { return $('meta[name="csrf-token"]').attr('content'); } $.ajaxSetup({ headers: { 'X-CSRFToken': getCSRFToken() } }); $.ajax({ type: 'POST', url: '/specialty', data: { specialty: $("#specialty").val(), csrfmiddlewaretoke: $('input[name="csrfmiddlewaretoken"]').val(), }, }) }) });` -
Django and SQL Server GIS error create point
i'm using django and sql server database when i try to create point to my model it keep giving me this error ProgrammingError at /api/common/v1/location/ ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]No column name was specified for column 1 of 'subquery'. (8155) (SQLExecDirectW)") this is my model class Location(TimeStampedWithNamesModel): """this class for general Location model.""" district = models.ForeignKey( District, on_delete=models.CASCADE, related_name="district_locations", null=True, blank=True, ) city_id = models.IntegerField(null=True, blank=True) region_id = models.IntegerField(null=True, blank=True) country_id = models.IntegerField(null=True, blank=True) polygon = models.PolygonField(null=True, blank=True) point = models.PointField(null=True, blank=True) area = models.FloatField(null=True, blank=True) is_polygon = models.BooleanField(default=False) diameter = models.FloatField(null=True, blank=True) class Meta: """this Meta class for the location model.""" ordering = ("-created_at",) unique_together = UNIQUE_TOGETHER_NAME_WITH_COMPANY verbose_name = _("Location") verbose_name_plural = _("Location") and for my setting DATABASES = { "default": { "ENGINE": config( "SQL_ENGINE", default="mssql" ), "NAME": config( "SQL_DATABASE", default="xxx" ), "USER": config("SQL_USER", default="admin"), "PASSWORD": config("SQL_PASSWORD", default="xxxx"), "HOST": config("SQL_HOST", default="xxxxx"), "PORT": config("SQL_PORT", default="1433"), "ATOMIC_REQUESTS": True, "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", } }, } note that another models are work fine I can create and list and update them