Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django: Reverse for '<WSGIRequest: GET '/index/'>' not found. '<WSGIRequest: GET '/index/'>' is not a valid view function or pattern name
I am getting the above error when i tried to redirect from my UserAuth app to UserArea app. It says 'NoReverseMatch at /index/'. UserAuth/views.py def loginUser(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # return render(request, 'home.html') return redirect('nsUserArea:urlUserHome') else: messages.info(request, 'User name or password is incorrect') return render(request, "Login.html") USerAuth/urls.py urlpatterns = [ path('', views.loginUser, name="urllogin"), path('logout/', views.logoutUser, name="urllogout"), path('register/', views.register, name="urlregister"), path('home/', views.home, name="urlhome"), ] UserArea/urls.py urlpatterns = [ path('', views.IndexPage, name="urlUserHome"), ] My main project urls.py file is this: urlpatterns = [ path('admin/', admin.site.urls), path('', include('UserAuth.urls', namespace="nsUserAuth")), path('index/', include('UserArea.urls', namespace="nsUserArea")), ] Can some one help? -
More than one cart returned
I am getting errors while doing cart work. When plus button is clicked, it says error in line 60 and says more than one cart returned enter image description here -
django about deleteview and view
I'm a super newbie, so please refer to this and read it. I am creating a bulletin board that communicates by DB <> API <> WEB method. I want to create a view to delete comments, but an Improperly Configured error occurs when I request to delete comments from the web. Can I define a query set without Model,DB? Or is my code a problem? Which view should I use? Improperly Configured Error with deleteview, Method not allowed with view generic.deleteview view WEB view.py class Commentapi_delete(generic.DeleteView): def delete(self, request, *args, **kwargs): datas = { 'pk': self.kwargs['pk'], 'id': self.kwargs['id'] } url = 'http://127.0.0.1:8080/boardapi/' + str(datas['pk']) + '/comment/' + str(datas['id']) + '/delete/' c_delete = requests.delete(url, params=datas) print(datas) print(c_delete) return redirect(reverse('board_detail', kwargs={'pk': self.kwargs['pk']})) API view.py class CommentUpdateDeleteView(generics.RetrieveUpdateDestroyAPIView): model = Comment queryset = Comment.objects.all() serializer_class = CommentSerializer -
Serverless Django app (AWS Lambda via Zappa) times out when trying to OAuth to Twitter
I've got a Django app setup to use django-allauth to connect to Twitter. The flow is all working locally and I've followed the same setup steps on Lambda to add my tokens, site, etc. When I try to access the login url (/accounts/twitter/login/) the request eventually times out with this message from AWS Lambda: {"message": "Endpoint request timed out"} The last message from zappa tail before the timeout event is: [1619019159940] [DEBUG] 2021-04-21T15:32:39.939Z 7f66a0e3-58de-4612-82c0-54590d69676f Starting new HTTPS connection (1): api.twitter.com:443 I've seen that the gateways have a 30 second timeout but I don't think it should be taking this long anyway. Locally, it's taking a couple of seconds. Does anyone with knowledge of these platforms have an idea where the bottleneck might be and where the issue could be? Or have any pointed questions to help debug? Things I've already checked and (tentatively) ruled out: The database backend is AWS Aurora Serverless, and I did worry that the double-serverless setup might be causing the slow speeds. However, a simple call of the Django management command (zappa manage dev migrate returns takes less than a second so I've ruled that out for now. Plus the Admin dashboard loads fine which is … -
Testing request.resolver_match in a Django context_processor
I have a Django context processor that puts the name of the current URL into the template context: def url_name(request): url_name = False if request.resolver_match: url_name = request.resolver_match.url_name return {"url_name": url_name} This works - if I visit / then {{ url_name }} in the template will display "home" because I have a URL pattern like: path("", HomeView.as_view(), name="home"), I would like to write a unittest for this context processor. I could do it like this: from django.test import Client, RequestFactory, TestCase from myapp.context_processors import url_name class URLNameTestCase(TestCase): def test_url_name(self): response = Client().get("/") self.assertEqual(response.context["url_name"], "home") That succeeds, but I'd like to unitttest the url_name() method on its own, outside of the response cycle. I've tried this: class URLNameTestCase(TestCase): def test_url_name(self): request = RequestFactory().get("/") context = url_name(request) self.assertEqual(context["url_name"], "home") But that fails because, in this situation, within url_name(), request.resolver_match is None. Why is that? -
Filtering data based on a condition in django template
I want to count total objects based on a condition in django template. Lets suppose my model is below: class Vote(models.Model): election = models.ForeignKey(Election, on_delete=models.CASCADE) candidate = models.ForeignKey(UserProfile, on_delete=models.CASCADE) voting_booth = models.ForeignKey(Booth, on_delete=models.CASCADE) Here i want total, votes based on each voting_booth. I can filter it in views but want to show all the votes with its respective booth. Template is: {% for v in vote %} <div class="col-md-6 col-sm-6 col-lg-6 col-xl-4"> <div class="dash-widget" style="box-shadow: 5px 5px lightblue;"> <div class="dash-widget-info"> <h5>Total Voters:{{v.**???**.count}}</h5> <h5>Voting Booth:{{v.voting_booth}}</h5> <h5>Total Vote Earned:{{v.**???**.count}}</h5> </div> </div> </div> {% endfor %} Thanks in Advance..