Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve integer from database objects
I'm fairly new to Django and try to get a database for scientific reviews up and running. One of the things I would like to show is how many reviews have been published in each year. In this example I used the following data: | year | number of reviews published | | ---- | --------------------------- | | 1999 | 1 | | 2019 | 4 | | 2022 | 5 | models.py class Review(models.Model): title = models.CharField(max_length=100,null=True) doi = models.URLField(max_length=200,unique=True,null=True) author = models.CharField("First author",max_length=100,null=True) year = models.PositiveIntegerField(null=True) views.py from django.shortcuts import render from .models import Review from django.db.models import Count def about(response): reviews_year_count = Review.objects.values('year').annotate(Count('year')) context = {'reviews_year_count':reviews_year_count} return render(response, "main/about.html", context) reviews.html <html> <body> {{reviews_year_count|join:", "}} </body> </html> output on localhost Currently: {'year': 1999, 'year__count': 1}, {'year': 2019, 'year__count': 4}, {'year': 2022, 'year__count': 5} Aim: 1, 4, 5 What I can't figure out is how to get rid of the {'year': 1999, 'year__count': } and only have the integer value there. I looked at Django documentation pages. One of the things I tried was add defer() behind reviews_year_count = Review.objects.values('year').annotate(Count('year')) but calling defer()after values() doesn’t make sense according to documentation. My aim is to use the data as … -
Why is the csrf cookie set when sending POST request to localhost:8000, but not when sending POST request 127.0.0.1:8000?
Why is the csrf cookie set when sending POST request to localhost:8000, but not when sending POST request 127.0.0.1:8000? Django then complains that the CSRF cookie is not set. (Assuming I open the frontend using localhost:3000, then same phenomenon occurs when opening the frontend script using 127.0.0.1:3000 but this time POST requests go through only to 127.0.0.1:8000). Basically, I'm interested on how to configure things in order to be able later on to serve the frontend (React in my case) and the backend (Django) from two different domains. For now I have no login feature etc. so CSRF protection makes no sense. However I'm interested, why with the current configuration, I'm not able to do cross origin requests (POST) with the CSRF token being in the header. So here is my code: Frontend: export async function post_request_to_backend_with_csrf(url : string, data: {[key: string] : string}, headers: AxiosRequestHeaders | undefined = undefined) : Promise<AxiosResponse<any, any>> { // get csrf token var csrftoken = getCookie('csrftoken'); if (csrftoken === null) { await getCSRFToken().then( (response) => { csrftoken = getCookie('csrftoken'); } ). catch((e) => console.log(e)) } var headers_arg : AxiosRequestHeaders = {'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken!, 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'}; for (let key in headers) { … -
Recuperar dados do Banco de Dados com Python [closed]
Bom dia. Não consigo retornar para o templete as informações que estão no Banco de dados, ou seja quando carrego o html, não aparece as informações do bd que estão sendo chamadas. Tô fazendo essa aplicação em Python utilizando o Django. Models.py `from django.db import models cursos = ( ('1','Técnico em informática para Internet'), ('2','Técnico em Agropecuaria'), ('3','Técnico em Agroindustria') ) class Postagem(models.Model): titulo = models.CharField(max_length=100) descricao= models.TextField() imagem = models.ImageField(blank = True) cursos = models.CharField( max_length= 3, choices = cursos, ) def __str__(self): return self.titulo def __str__(self): return self.descricao def __str__(self): return self.imagem def __str__(self): return self.cursos` Views.py from multiprocessing import context from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render,redirect from .models import Postagem 'def listar(request): postagens = Postagem.objects.all() context = { 'postagens': postagens} return render(request,'post/listar.html', context)' urls.py from django import views from django.contrib import admin from django.urls import path from .import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.listar, name = 'listar') ] listar.html <h1> Suas postagens </h1> {{postagem.titulo}} { % for postagem in postagens % } <span> <a href="/editar/{{postagens.id}}"> {{postagens.titulo}}</a> </span> <span> <a href="/excluir/{{postagens.id}}"></a> </span> <span> <a href="/nova/{{ppstagens.id}}"></a> </span> { % endfor % } como aparece na tela: post/ -
Django deployment(Elastic Beanstalk) Following services are not running: web
Hi I got error like this: Django deployment(Elastic Beanstalk) Following services are not running: web. When trying to deploy my web app to elastic beanstalk, everything is ok, logs are clear. Can u help me? -
Problems with static files django, IIS and windows 10
Problems with static files django, IIS and windows 10 Hi I have Python 3.10.4, Django 4.0.4 and wfastcgi 3.0.0 installed. This on windows server 2016 and the latest version of IIS as of 05/20/2022. I have already run the command manage.py runserver collectstatic. Does not show static files when viewing the web application on the internet. This file is web.config which is outside the project folder. <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python35\python.exe|C:\Python35\lib\site-packages\wfastcgi.py" resourceType="Unspecified" /> <add name="Proyectoqr" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python35\python.exe|C:\Python35\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python35\python.exe|C:\Python35\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\proyectoqr" /> <add key="WSGI_HANDLER" value="proyectoqr.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="proyectoqr.settings" /> </appSettings> </configuration> This is the content of the web.config file in the static folder <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <clear/> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read"/> </handlers> </system.webServer> </configuration> I already added the virtual directory of the static folder with direction to the static folder of the project as shown in the following image. Add virtual directory image If you need more information tell me to show you the code or configuration -
Annotate a query with Django
Hello I am trying to annotate a query but it does not work ... Here is my query : animal = Animal.objects.first() test = Test.objects.filter(a=3).annotate(name=Case(When(animal in test.user.all(), then=Value('withanimal')), default=Value('notwithanimal'),)) But I got 'QuerySet' object has no attribute 'user'. I precise the field user is a ManyToManyField. Could you help me please ? Thank you very much ! -
how to assign an id to an item when clicking on a link beside it in Django?
I'm trying to assign an id to a CSV file's name so that when I click on a link beside I can access the CSV file itself on another web page to view it. but I keep getting this error 'QueryDict' object has no attribute 'objects' Note: the CSV files are taken from a form and saved in a file on the PC, I'm trying to retrieve the file from the PC itself. This is the views.py def read_datasets(request): file = request.POST.objects.get(id=id) # print(file) path = r"C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/" # csv_file = request.FILES['file2'] # csv_file = request.POST.get('file2') path1, dirs, files = next(os.walk(path)) file_count = len(files) print(file_count) # dataframes_list_html = [] file_names = [] # file_name = csv_file.name for i in range(file_count): temp_df = pd.read_csv(path+files[i]) print(files[i]) # dataframes_list_html.append(temp_df.to_html(index=False)) file_names.append(files[i]) # print(dataframes_list_html) return render(request,'blog/view_datasets.html',{'names': file_names}) def one_dataset(request): path = r"C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/" path1, dirs, files = next(os.walk(path)) file_count = len(files) print(file_count) dataframes_list_html = [] for i in range(file_count): temp_df = pd.read_csv(path+files[i]) print(files[i]) dataframes_list_html.append(temp_df.to_html(index=False)) return render(request, 'blog/single_dataset.html', {'dataframes':dataframes_list_html}) and the HTML File <body> {% for dataframe in dataframes %} <div id="customers"> {{ dataframe|safe }} <hr> </div> {% endfor %} </body> -
Resolving Delete event failure in Django
This is error I have been trying to solve for last 7 days. I am a newbie to Django Page not found (404) Request Method: POST Request URL: http://localhost:8000/projects/delete-project/ce4c5177-eb8f-44b9-9734-04adafd75414/ Using the URLconf defined in devsearch.urls, Django tried these URL patterns, in this order: admin/ projects/ projects/ [name='projects'] projects/ project/<str:pk>/ [name='project'] projects/ create-project/ [name='create-project'] projects/ update-project/<str:pk>/ [name='update-project'] projects/ delete-project/<str:pk>/ [name='delete-project'] This message appears after clicking the submit button on my delete-object form which correctly refers to the object being deleted name attribute...which in my mind means the object has been found in the database and is being correctly referenced. Here is the Code: url.py of the application from django.urls import URLPattern, path from . import views urlpatterns = [ path('projects/', views.projects, name='projects'), path('project/<str:pk>/', views.project, name='project'), path('create-project/', views.createProject, name='create-project'), path('update-project/<str:pk>/', views.updateProject, name='update-project'), path('delete-project/<str:pk>/', views.deleteProject, name='delete-project'), ] View Function Code: @login_required(login_url='login') def deleteProject(request, pk): profile = request.user.profile project = Project.objects.get(id=pk) if request.method == 'POST': project.delete() return redirect('account') context = {'object': project} return render(request, 'delete-object.html', context) Confirmation HTML Page <form class="form" method="POST" action="'"> {% csrf_token %} <p>Confirm deletion of '{{object}}'</p> <button class="btn btn--sub btn--lg my-md"><a href="{{request.GET.next}}">Go Back</a></button> <a href="delete-object" ><Input class="btn btn--sub btn--lg my-md" type='submit' value='DELETE' style="color: red;" /></a> </form> Create, Read, and Update … -
Keycloak and Django 4 (DRF)
everyone! This is the last hope to understand how django and keycloak works together? The main problem is: I read a lot of documentation about authorization through jwt-token, I know everything what it is. So, but I can't imagine, how to integrate keycloak authorization in a django project. There are 5 or more libraries to work with keycloak. Which one I should use? I already have all configurations in a keycloak by admins, all env variables like KEYCLOAK_CLIENT_SECRET, KEYCLOAK_PUBLIC_KEY etc. What is the algorithm to work with KK in Django? I know, that I need to create 3 additional URL's to work with: First one gonna to check the credetionals to check, that user could authorize before and if not - redirect him to the second URL ↓ Second - user authorizes in KK and goes to third URL Third - I meet user on this URL and get the scope and some info here After that, I'm going to KEYCLOAK_ACCESS_TOKEN_URL, where I got the token Next - decode this token and get the roles and some data Can someone show me how it goes on practice? At this moment I should to register the user in django and do … -
Is there a way to know if related objects have been prefetched?
Is there any way to know whether related objects have been prefetched from inside a model instance? Suppose one has class Order( models.Model): ... def is_all_in_stock( self): # how to do this? class LineItem( models.Order): order = models.ForeignKey( Order, ..., related_name='line_items') stock = models.ForeignKey( Stock, ...) ... And one wants to generate some report of all orders that are delayed for assorted reasons for order in orders: # orders is a queryset ... out_of_stock = any([ line.stock.status != IN_STOCK for line in order.line_items.all() ]) This is efficient if one is iterating over a queryset that did .prefetch_related( "line_items", "line_items__stock). It doesn't hit the DB at all. It hammers the DB if not. On the other hand, using a queryset like out_of_stock = order.line_items.exclude( stock__status = IN_STOCK ).exists() hits the DB only once for each order, the classic N+1 problem Is it possible to write the method order.is_all_in_stock(self) to take advantage of what has been prefetched if it has been prefetched, and to fall back on running a query each time it is called if not? -
Django and Django rest framework + email
How could i achieve email functionality using drf as backeend and django to hit these apis.What i need how will user be confirm from django while using drf to send activation link. -
How to get(access) foreign key's member instance in django?
articles/models.py class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) user/models.py class User(AbstractUser): username = models.CharField(max_length=20) email = models.EmailField(_('email address'), unique=True) profile_image_url = models.TextField() Is there any other way to include or access user's member instance (username, email, profile_image_url) into class Article?? I'd like to make class Article into this class Article(models.Model): User.username User.email User.profile_image_url FYI,my Serializer are these class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['emotion', 'location', 'menu', 'weather', 'song', 'point', 'content', 'image', 'user', 'created', 'liked', 'num_liked'] class UsersSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'date_joined', 'email', 'profile_image_url', 'followings', 'followers') Is there any other way to make my ArticleSerializer to include UserSerializer's fields? or Is there any other way to include or access user's member instance (username, email, profile_image_url) into class Article?? -
Django: Leaflet map does not render when adding new item in admin inline
I am using the django-leaflet package to display the maps in the admin. I have a model that I am inserting as TabularInline, where one of the fields is a PointField. model.py class Occurrence(models.Model): name = models.CharField(max_length=254) location = models.PointField(null=True, blank=True) # ....... admin.py class OccurrencesInline(LeafletGeoAdminMixin): model = Occurrence fields = ('name', 'location') show_change_link = True extra = 1 formset = AtLeastOneFormSet The map appears correctly in the extra rows that appear initially. However, when I add a new item, instead of the map, a text box appears. Any idea why this is happening and how to fix it? -
How to fix Django's Internal Server Error on their latest release?
I am setting up the base html page that I will use to extend for the rest of my project. I am finished setting it up (The same way I always do, besides a few minor html and wording changes) but I keep getting ValueError at / dictionary update sequence element #0 has length 1; 2 is required Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.3 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 1; 2 is required Exception Location: /home/blackhood/.virtualenvs/djangoenv/lib/python3.9/site-packages/django/urls/resolvers.py, line 421, in resolve Python Executable: /home/blackhood/.virtualenvs/djangoenv/bin/python3 Python Version: 3.9.7 Python Path: ['/home/blackhood/Apps/sobriety_app', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/blackhood/.virtualenvs/djangoenv/lib/python3.9/site-packages'] Server time: Fri, 20 May 2022 08:14:33 -0500 It seems like there is an issue inside Django's code base, but I know it's more likely that I am making an error somewhere. I will post the HTML code first and then the code for each script in the landing app. __landing/templates/landing/base.html__ <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- Font Awesome Link --> <script src="https://kit.fontawesome.com/216d1cce07.js" crossorigin="anonymous"></script> <title>App Title</title> </head> <body> {% include 'landing/navbar.html' %} {% block content %} {% … -
No UID when using Django admin page to create objects
So I have created a custom User model and a common model as base for all other models that adds a created_by field. If I now use the Django admin page to create an object(just for testing) then I get the error that the UID is Null. class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new User""" if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """creates and saves a new superuser""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CommonModel(models.Model): """Common fields that are shared among other models""" created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, editable=False, related_name="+", ) So it seems like when using the admin page to create objects the UID cannot be resolved. Any ideas? -
Django user.authenticate always returns None
Models.py class User(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(_('email address'), unique=True) password = models.CharField(max_length=50) phone_number = models.CharField(max_length=100) last_login = models.DateTimeField(auto_now=True) is_confirmed = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email Managers.py class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) Settings.py AUTH_USER_MODEL = 'users.User' My django app is named as 'users'. So basically I'm trying to implement my own users using the AbstractBaseUser and I want authentication using email & password, tried everything still unable to get the … -
Javascript : QuerySelector fail and can not add an inner tag
My goal is to display a pdf from a blob Url. I want to add a tag to the html code <iframe src='${blobUrl}' type="application/pdf"></iframe> to diplay the pdf file. Here is the full code : html {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {{ encodedstring | json_script:'mydata' }} <div class="pdfdisplay"></div> <script> function b64toBlob(b64Data, contentType, sliceSize) { contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = atob(b64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } var blob = new Blob(byteArrays, {type: contentType}); return blob; } var contentType = 'application/pdf'; var b64Data = JSON.parse(document.getElementById('mydata').textContent); var blob = b64toBlob(b64Data, contentType); var blobUrl = URL.createObjectURL(blob); const target = document.querySelector('div.pdfdisplay'); target.innerHTML = <iframe src='${blobUrl}' type="application/pdf"></iframe>; </script> </body> </html> When I inspect the page generated, nothing is added to <div class="pdfdisplay"></div> and the page is blank. I know that the error comes from ther queryselector but I do not see what … -
NoReverseMatch at /accounts/confirm-email/
when i try to create account ( signup ) it show this error ( i am using django alluth ) django.urls.exceptions.NoReverseMatch: Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name. In template /home/qq/Desktop/earnapp/templates/account/base.html, error at line 15 urls.py : path( "confirm-email/", views.email_verification_sent, name="account_email_verification_sent", ), re_path( r"^confirm-email/(?P<key>[-:\w]+)/$", views.confirm_email, name="account_confirm_email", ), base.html : <!DOCTYPE html> {% load static %} <html dir="rtl"> <head> <title>{% block head_title %}{% endblock %}</title> {% block css %} {% endblock css %} {% block extra_head %} <!-- booststrap link js + ajax + css --> <script src="{% static "js/jquery.min.js" %}"></script> <script src="{% static "js/bootstrap.min.js" %}"></script> <script src="{% static "js/site.js" %}"></script> <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"> <link rel="stylesheet" href="{% static "css/site.css" %}"> <meta name="viewport" content="height=device-height, initial-scale=.82, maximum-scale=2, user-scalable=no"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript"> error in line 15 is <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> -
cannot iterate through payload to get the desired output
I'm trying to the iterate through the payload where there is a Qstan I want it to get in the desired output like 12|Yes&&13|Yes&&14|Yes&&15|Yes&&16|Yes&&17|Yes&&18|Yes&&19|Yes&&. I have tried to get in separate like 12|Yes&& 13|Yes&&. All I wanted is to concatenate QId and Answer before it saves to the database. How could I achieve this browser payload 0: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 150…} 1: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 151…} 2: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 152…} 3: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 153…} 4: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 154…} 5: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 155…} 6: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 156…} Here, what I tried @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': data = [] cursor = connection.cursor() for ran in request.data: auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = ran.get('SID') print('sid--', sid) TicketType = ran.get('TicketType') TypeSelected = ran.get('TypeSelected') agents = ran.get('Agents') supervisor = ran.get('Supervisor') Comments = ran.get('Comments') action = ran.get('Action') subfunction = … -
How to get azure subscriptionid from subscription name using python
I am trying to create a azure resource id in python script using information of provider and resourcegroup name. which will be used for rest api calls. But the problem is I have only name of subscription. How can I fetch subscriptionId in my prog? -
Is there a way to improve the health of EB environment?
I tried to create a new application with a new environment in AWS Elastic Beanstalk and the it ran ok to begin with. But once I uploaded and deployed (successfully) my Django app on it, it degraded in health to severe. The error is : Environment health has transitioned from Degraded to Severe. 100.0 % of the requests are failing with HTTP 5xx. My application runs fine on my machine. I have set up the requirements and remove pywin32 and pypiwin32 from it coz this is a linux instance on AWS. Also here is my django.config file in .ebextensions: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: employee_records.wsgi:application I have added all changes (including the virtual env) to staging area in github. I have chosen the application load balancing (default 2). So please help as to why this error occurs. -
Creating custom fields with django-filters
I have a model as shown below. The model has the attribute type as a foreign key. class YachtGeneralInfo(models.Model): type = models.ForeignKey( YachtTypes, related_name="yachts_in_type", on_delete=models.PROTECT, blank=False, null=False, ) .... .... I wrote a view class like this - class YachtGeneralInfoView(ListAPIView): pagination_class = PageNumberPagination serializer_class = YachtGeneralInfoSerializer filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend] filterset_fields = [ "status", "is_professional", "chartered_with__id", "harbour__id", "harbour__city__id", "model__id", ] search_fields = ["name", "company_name", "website", "owner__name"] I would like to add another filter for field type. However, I want to provide multiple values for this query parameter like [1,2,3]. If I do that directly with queryset then it would be like this - queryset = YachtGeneralInfo.objects.filter(type__in=[1,2,3]) Is there a way I could write a custom filter set field to accomplish this instead of having it directly in the queryset? -
Django model field setting to NoneType after objects.create
Im using objects.create to create object o my model. Using the following logic. But payment_quantity (somehow) is setting to NoneType. And not setting to the value i passed into objects.create class PrizesExchangeModeResourceBMR(resources.ModelResource): @transaction.atomic def create_exchange_mode(self, code, points, price): cuotas = [1,3,6,12] # array de cuotas prize = Prize.objects.filter(code = code) # busca el premio if len(prize) != 0: # si existe el premio PrizesExchangeMode.objects.create( #crea puntos al 100%, 0 cuotas prize = prize[0], payment_amount = 0, points_value = points, payment_quantity=0, price_value = 0 ) puntos = round(points/2) for cuota in cuotas: # crea con puntos al 50% y [1,3,6,12] cuotas valor = round(price/cuota) PrizesExchangeMode.objects.create( prize = prize[0], payment_amount = valor, points_value = puntos, payment_quantity = 0.0, price_value = 0.0) else: print("Premio no encontrado") # no existe el premio def get_instance(self,instance_loader, row): self.get_queryset().get(prize__code=row.get('prize')) def save_instance(self, instance, using_transactions, dry_run): code = instance.prize.code #guarda el codigo points = instance.points_value # guarda puntos price = instance.payment_amount # guarda precio self.create_exchange_mode(code, points, price) # se lo pasa a la funcion anterior class Meta: model = PrizesExchangeMode fields = ("prize", "points_value", "payment_amount") # Campos que queremos importar -
Is there a way too attach another django db in a SQL query?
Like the title says, is there a way to use the following SQL code with the ATTACH: attach "..\directory...\database1.sqlite3" as input; select columnx, columny from (select column1, column2 from input.sites) I am selecting column x and y from database2 and i want to attach database1 so that I can query it in the select statement while also querying database2. I have both database1 and 2 in my settings.py file with routers and models which all works great. At the moment I am bypassing the ORM (Sqlite) and using SQL query like so which works great: database='C:/... database1.sqlite3' db=sqlite3.connect(database) c=db.cursor() sql_command='SELECT * FROM customers' customer = c.execute(sql_command) customer = c.fetchall() I could'nt find anything int he django docs about ATTACH so any advice is appreciated! -
No module named 'django_redis' even imported
I have the error ".InvalidCacheBackendError: Could not find backend 'django_redis.cache.RedisCache': No module named 'django_redis'" Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\cache\__init__.py", line 39, in create_connection backend_cls = import_string(backend) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_redis' File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\cache\__init__.py", line 43, in create_connection ) from e django.core.cache.backends.base.InvalidCacheBackendError: Could not find backend 'django_redis.cache.RedisCache': No module named 'django_redis' I installed django_redis I ping my redis_cli in my setting.py, I add the code CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", 'TIMEOUT': 60 * 60 * 8, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, "KEY_PREFIX": "lkd" } } But the error still appear that no module named django_redis Please help me to solve my issue