Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ElasticSearch DSL: how to filter by a value in ListField
I have a number of fields in an ElasticSearch document MovieDocument created using django-elasticsearch-dsl. One of the fields is: actors = fields.ListField(fields.TextField()) This field in the ElasticSearch index contains a list of names, e.g.: ['Sylvester Stallone', 'Bruce Willis', 'Arnold Schwarzenegger']. And there are a number of other fields in the Document and the underlying Model. When a user performs a query searching 'Sylvester Stallone', I would like to retrieve this values from the ListField in a must clause. I.e. the search results should display only the movies featuring Sylvester Stallone, regardless of the other actors included in the actors list. I have tried dozens of combinations of queries and filters of django-elasticsearch-dsl but to no avail: I either get movies without Stallone or no movies at all. How can I achieve the desired result? -
How to return empty queryset from serializer.data Django Rest Framework
view.py class User_ListView(APIView): permission_classes = [DjangoCustomModelPermissions] queryset = User.objects.none() def get(self, request): param1 = request.query_params.get('param1',None) param2 = request.query_params.get('param2',None) try: db_data = User.objects.get(param1 = param1, param2=param2) serializer = User_Serializer(db_data) return Response(serializer.data) except Closing_Stock_List_Trans.DoesNotExist: db_data = User.objects.none() serializer = User_Serializer(db_data) return Response(serializer.data) serializer.py class User_Serializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' I want the serializer to return an empty response when no User DoesNotExist in the User Model, however I get the following error. How can i achieve this? AttributeError: Got AttributeError when attempting to get a value for field `param1` on serializer `User_Serializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'param1'. -
Django-React-Webpack Integration does not output updated React Components when I refresh the page
I have been trying to integrate React to a Django app using Babel and Webpack, but am having a hard time running the updated .js output file. I believe my problem comes from the main.js file Webpack outputs does not reflect the updated come from my React components. What I mean by that is that my server does not load the main.js file with the updated code when I refresh the page . What happens is that when I refresh the page only this runs on my python terminal (most of the time): [20/Apr/2021 22:01:02] "GET / HTTP/1.1" 200 1509. While sometimes my static files run too, but that seems to be random: [20/Apr/2021 22:00:20] "GET /%20static%20/frontend/main.js HTTP/1.1" 304 0. So what is happening is that the python server is rarely running GET for the static files when I refresh the page. I would like to understand why this happens and how I can fix it. Here is my folder structure: dist bundle.js main.js src components index.js static frontend main.js templates frontend index.html babel.config.json package.json webpack.config.js Here is my code: index.js - import App from "./components/App/App"; index.html <!DOCTYPE html> <html> <head> {% load static %} <link rel="icon" href="{% static 'imgs/acmLogo.ico' … -
How do I update a user created from another model though that model edits?
My question is based on this here. Now that User.objects.update_user() does not work, how would I update a user if the the teacher whose details created the user are updated. Below is the view that created the user. class NewTeacherView(LoginRequiredMixin,CreateView): model = TeacherData form_class = TeachersForm template_name = 'new_teacher.html' success_url = reverse_lazy('teachers') def form_valid(self, form): context = super().form_valid(form) teacher_data = self.object username = (teacher_data.first_name + teacher_data.last_name).lower() password = (teacher_data.first_name + str(teacher_data.code)).lower() user = User.objects.create_user( username=username, password=password, school_id=self.request.user.school.id, is_teacher=True) return context HHow would I create the view that edits the user when the teacher is edited???? -
KeyError in dictionary but key exists
I am having a problem with a keyerror, I know the key exists but i still get an error. Iam a beginner and i do not quite understand previous code examples of this question curr_coin = get(coin_url).json() keys in curr_coin.keys(): print(keys) PRINT RESULTS: id symbol name asset_platform_id platforms description description = curr_coin['description']['en'] Then i get this error Traceback (most recent call last): File "C:\Users\dan_t\anaconda3\envs\dtfinance\lib\site-packages\django\core\handlers \exception.py", line 47, in inner response = get_response(request) File "C:\Users\dan_t\anaconda3\envs\dtfinance\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Desktop\Algo\Django\dtfinance\website\views.py", line 255, in coins description = curr_coin['description']['en'] KeyError: 'description' I used : curr_coin.get('description') which fixed the problem but then key errors continue for the rest of that dictionary, why can i not access this dictionary like i usually have? Even through it is giving me a keyerror the description data is still output just fine and code works as it should. -
Python Social Auth - Ask user to type email if on facebook login
If facebook account have an email addres it's working fine and saving user with correct email address. I want to ask users while login with facebook to type their email address if the Facebook account is made with phone number. The users should type an email address in a form and then save the user account. How can I do that? -
Infrequent Heroku H10 Crashes on a deployed Django app that otherwise runs smoothly
I've been doing a lot of searching, and everything I can find regarding this error are deployment issues, which isn't my issue in this case. About 20 times a day, I will get a notification (I use Logentries) of a crash following the pattern of: 21 Apr 2021 12:42:05.218340 <158>1 2021-04-21T16:42:04.670611+00:00 heroku router - - at=error code=H10 desc="App crashed" method=PUT path="/api/warehouse/updateclient/" host=<HOST> request_id=cf9e8b49-d05c-4fca-a8ea-e07c93b888ce fwd="<IP ADDRESS>" dyno= connect= service= status=503 bytes= protocol=http I omitted sensitive information above. Now a few things to note: This app is running successfully and 99% of requests to this route work correctly (it receives 50K+ requests a day). This specific route /api/warehouse/updateclient/ is what is usually logged as the crash as it's the main endpoint for my API's client's updates (via Django Rest Framework), but this has also been logged on other routes as well, for example, an AJAX GET request on another route to update a status page. The Dyno does not reboot/restart during this, and all log entries before and after these crashes show the app to be running correctly (at the same endpoint), including the celery worker and the database updates. Often times within a second or so, it's responding to another request … -
python django latitude longitude filter in queryset
I have a field like class MyModel(models.Model): latitude = models.CharField(max_length=100, db_index=True) longitude = models.CharField(max_length=100, db_index=True) Lets say I have lat long value like myval = (27.66469717424158, 85.30983049711507) Here I want to find all the objects in MyModel which are less than 10 KM in distance from myval I looked into geopy library. I think it is useful after I get the data from queryset. How to achieve this ? -
How to add vertical bootstrap cards in django templates?
I want to add Bootstrap cards vertically, i am sending data from views.py and rendering it on template by iterating it using {% for %} loop. But I want those cards vertically card they are being placed one below another. Here's my html: <div class="card mb-3" style="max-width: 540px;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="media/{{i.thumbnail}}" class="card-img" alt="thumbnail"> </div> <div class="col-md-8"> <div class="card-body"> <p class="card-title"><b>Title:</b> {{i.title}}</p> <p class="card-text"><b>Venue:</b> {{i.venue}}</p> <p class="card-text text-truncate"><b>Description:</b> {{i.description}}</p> </div> </div> </div> </div> I want output to be something like this -
Render html and load its css/js files without using static files from Django
I am trying to render a html using a local directory but I keep getting the error: The resource from "/path/to/js/" was blocked due to MIME type ("text/html") mismatch (X-Content-Type-Options: nosniff)". I believe I am getting this error because I am not using the staticfiles that django says to use. But that is exactly what I want to not do. Basically, I have an app that exports presentation slides in HTML format, but it puts the js files and css files in its own directory which has a completely different structure than Django's staticfiles. I wanted to know if there was a way I could render the page and get its js/css to make it work. I was able to get the html from the other directory but that's where it stops and gives me an error. Thanks. -
can't access views with IsAuthenticated even if logged in (django rest framework + simple jwt)
iam trying to make DRF working with Simple-jwt. so far it is working , register users and logging except if i try to access a view with IsAuthenticated permission it still ask for credentials, and i can't put my hand on what i am missing here. if i want to acces ListUsers view i get : "detail": "Authentication credentials were not provided." views: class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request, format='json'): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: json = serializer.data return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class LoginAPIView(APIView): permission_classes = (AllowAny,) serializer_class = LoginSerializer def post(self, request, data=None): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) class ListUsers(APIView): permission_classes = (IsAuthenticated,) def get(self, request, format=None): usernames = [user.user_name for user in NewUser.objects.all()] return Response(usernames) serializers: class CustomUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) user_name = serializers.CharField(required=True) password = serializers.CharField(min_length=8, write_only=True) class Meta: model = NewUser fields = ('email', 'user_name', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) # as long as the fields are the same, we can just use this instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) user_name = serializers.CharField(max_length=255, read_only=True) password = … -
'TemplateDoesNotExist' can't get the solution
I am starting in Django, but I am stuck with this problem I have this structure in my VSCode Workspace -Project1 __pycache__ __init__.py asgi.py settings.py urls.py views.py wsgi.py -templates mytemplate.html db.sqlite3 manage.py I am trying to use a template that I built urls.py from Project1.views import salute urlpatterns = [ path('admin/', admin.site.urls), path('salute/', salute), ] views.py from django.template.loader import get_template from django.shortcuts import render class Persona(object): def __init__(self, nombre, apellido): self.nombre = nombre self.apellido = apellido def salute(request): p1=Persona('Peter', 'Parker') temas_del_curso = ['Plantillas', 'Modelos', 'Formularios', 'Vistas', 'Despliegue'] fecha_de_hoy = datetime.datetime.now() return render(request, 'miplantilla.html', { 'nombre_persona' : p1.nombre, 'apellido_persona' : p1.apellido, 'fecha_de_hoy' : fecha_de_hoy, 'temas' : temas_del_curso }) They suggest I copy the directory path where my template is saved settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['C:/Users/machine/Desktop/Django/Project1/templates'], 'APP_DIRS': True, } Someone please help me, I have tried everything and still can't find the solution. Also use the form Django suggests 'DIRS': BASE_DIR / 'templates' and the form [os.path.join (BASE_DIR, 'templates')] but the error continues -
Django Environ: SMTPServerDisconnected when managing email password
I just installed Django-Environ to store my email password (more specifically, Sendgrid's API key). Sending emails worked well before but I now get an error SMTPServerDisconnected at /... Connection unexpectedly closed. Settings.py import environ env = environ.Env() environ.Env.read_env() ... EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = env.str('SENDGRID_API_KEY') .env file in the same directory as my settings.py project_name/ .env asgi.py settings.py urls.py wsgi.py .env SENDGRID_API_KEY=SG.TUU5oTWg...... The weird thing is if I print(EMAIL_HOST_PASSWORD) in my settings, the value imported is not even the same as the one stored in my .env file; as if it was distorted during the import. I've also tried to stringify the output with .str but the outcome is the same. Any thoughts as to what is causing this? -
Django-Debug-Toolbar is not showing
I am building BlogApp and I am trying to run Django-Debug-Toolbar BUT it is not showing. I have seen many answers BUT nothing worked for me. I have installed it correctly according to the Documentation I have added in installed apps , middlewares and urls and also collecstatic. BUT still not showing when i go to Browser. settings.py if DEBUG: MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += [ 'debug_toolbar', ] INTERNAL_IPS = ['127.0.0.1', ] # this is the main reason for not showing up the toolbar import mimetypes mimetypes.add_type("application/javascript", ".js", True) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } urls.py if settings.DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] Any help would be Appreciated. Thank You in Advance -
How efficient is Django Core Pagination?
I have a query set of some 500 objects... which I get after running the initial query set in some loops and checking a few conditions and excluding the objects that do not meet the criteria... and I am displaying these objects using Django core pagination.. how efficient is this and if not, what are the alternatives. -
IntegrityError at /admin/product/product/add/ FOREIGN KEY constraint failed
I was trying to make a product model and when i tried to add it for testing from my admin panel i got this error but i have not used any foreignkey in this model.Thanks for helping.I am writing just because stack overflow is not allowing me to post by saying you have very less description Exception Type: IntegrityError at /admin/product/product/add/ Exception Value: FOREIGN KEY constraint failed My Model.py class Product(models.Model): name=models.CharField(max_length=100,null=False,blank=False) price=models.DecimalField(max_digits=10,decimal_places=2) excerpt=models.CharField(max_length=150) description=models.TextField() stock=models.IntegerField() discount=models.FloatField(null=True,blank=True) slug=models.CharField(max_length=255,null=True,blank=True) brand=models.CharField(max_length=100) featured=models.BooleanField(default=False) main_image=models.ImageField(upload_to='product/') sub_image_1=models.ImageField(upload_to='product/',null=True,blank=True) sub_image_2=models.ImageField(upload_to='product/',null=True,blank=True) sub_image_3=models.ImageField(upload_to='product/',null=True,blank=True) uploaded_at=models.DateTimeField(auto_now_add=True) class Meta: ordering=['-uploaded_at'] def __str__(self): return self.name # def save(self,*args,**kwargs): # if self.slug is None: # self.slug=slugify(self.name) # super(Product, self).save(*args, **kwargs) def featured_8_products(self): return self.objects.filter(featured=True)[:8] def latest_8_products(self): return self.objects.all()[:8] -
When running my Django application on a Docker container: psycopg2.OperationalError: could not translate host name
Some is either wrong with my docker-compose or Docker in general. When running python manage.py runserver it works perfectly. But when after I build my docker-compose, and run it with docker-compose up, I get the following error: psycopg2.OperationalError: could not translate host name "<AWS_DB_URL>" to address: Name does not resolve This is my Dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN apk add postgresql-dev RUN apk add jpeg-dev zlib-dev RUN python -m pip install -U --force-reinstall pip RUN pip install -r /requirements.txt RUN apk del .tmp RUN mkdir /app COPY ./backend /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static CMD ["entrypoint.sh"] This is my docker-compose.yml: version: '3.7' services: app: build: context: . ports: - "8000:8000" volumes: - ./backend:/app command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 - AWS_ACCESS_KEY_ID=<AWS_ACCESS_KEY_ID> - AWS_SECRET_ACCESS_KEY=<AWS_SECRET_ACCESS_KEY> This is my entrypoint.sh #!/bin/sh set -e python manage.py collectstatic --noinput uwsgi --socket :8000 --master --enable-threads --module app.wsgi This is my error: app_1 | Watching for file changes with StatReloader app_1 | Exception in thread django-main-thread: app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", … -
'base' template between Django and Bokeh
I am learning Bokeh and want to embed it in a Django app. Particularly, I want to insert a series of charts created with Bokeh into a Django website. Bokeh templates look similar to Django. But all of them are supposed to extend a base template inherent to Bokeh. And on Django site, its templates are also supposed to extend a base.html created by ourselves. How should I handle this, or what to make of this situation? Thanks. -
ValueError: The view curd.views.emp didn't return an HttpResponse object. It returned None instead
ERROR:The view curd.views.emp didn't return an HttpResponse object. It returned None instead -
how to display pdfs in webpage using html in django
how to retreive multiple pdfs from database and display it in webpage using html in django? this is my function in views.py def PdfView(request): pdf = EbookModel.objects.all() form=SearchForm() context ={ 'pdf':pdf, 'form':form, } here's my html file: {% extends 'basic.html' %} {% block content %} {% for pdfs in pdf %} <a href="">{{pdfs.title}}</a> {% endfor %} <form method ='post'> {% csrf_token %} {{form}} <input type="submit" value = "Submit"> </form> {% endblock %} -
Can I access channel layer consumers in django channels?
I am working with django channels and got a resource intensive task which due to hardware limitations I try to run as little as possible. I run this task only when 1 consumer is connected to the channel layer, but I also need to run it when a new consumer connects (the data new consumers need is at the other consumers not on the main server). This might sounds a bit vague, but the how and why is not really import for this question. In short: whenever a new user joins I'd like 1 of the already connected users to send a message, (doesn't matter which user). Is there a way to access channel layer consumers and use consumer.send() that he needs to send a message? -
What is Token Claim In JWT?
I have been learning JWT authentication in Django Rest Framework I came across customizing Token claims I am pretty new to token based authentication https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html And I also saw certain custom token claims example from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super(MyTokenObtainPairSerializer, cls).get_token(user) # Add custom claims token['username'] = user.username return token For what purpose are we using this? Any summarized details will be helpful :) -
Restricted login from WordPress main site to Django web app
I am looking to integrate a wordpress website at mydomain.com with a django web app set up at analytics.mydomain.com. The wordpress website is the main website, where payments are accepted, a user area are that contains the link to the Django analytics tools. The Django app is hosted on another site (e.g Heroku) but is set up as a subdomain. I would like the database and user authentication and information on WordPress to act as a master to the Django slave rather than vice versa. How can I integrate authenticated users on the wordpress site, who have paid for analytics functionality, to have access to the django app without requiring login in again, or how can I share the user logins automatically - like an single sign on or something similar? What is the best way to go about this? -
Passing parameters to links in a many to many field
I am trying to pass a parameter to the link so that when the user do click to one of the categories he will be redirected to a page listing all the posts with the clicked categor -
I have a question about making a POST request with Django rest api with uploading multiple images
enter image description here I have a question about making a POST request with Django rest api with uploading multiple images. My question : To get the images from a post Request i am using this : files_list = request.FILES.getlist('homeworkimage_set') the images are created in the database correctly. but in the response : i am not getting this : homeworkimage_set :{'image': url},{'image':url}. i don't know if i am missing something. my homeworkimage_set(image below) is empty in the response even though the images are correctly created in the database. Is it necessary to get the images urls in the response even though i the images are saved in the database? If you have any idea how can i get the images urls in the response could please help me on that. Thanks in advance.