Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React component not rendering in django index html template
Index html: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Babon</title> </head> <body> <div id="App"> <!-- React will load here --> </div> </body> {% load static %} <script src="{% static 'frontend/main.js' %}"></script> </html> Index.tsx: import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <App />, document.getElementById('App'), ); When I run my server I can see that the div is rendering with the "React will load here" message fine but my component doesn't seem to be rendering. Any ideas? -
No transactions shows in dashboard Razorpay TestMode
No records showing in my razorpay dashboard on TestMode. I have made so many successful transactions but those not displaying in the dashboard. Is there something I am missing to display transactions in dashboard. -
NameError: name 'Log_in' is not defined (How can I fetch email and password from my table Sign_up)
I want to make user is valid or not by matching the email id and password form sign_up table if correct then login other wise thy need to log_inenter code here -
Django LDAP using active directory service on AWS
I am trying to connect my Django app using AWS active directory service but it doesn't work for. The library I am using is this one https://github.com/etianen/django-python3-ldap, My aws active directory is under 1 public and 1 private subnet and my Directory name is ldap.xxxx.com, here xxxx=real name Existing Code: on my settings/base.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django_python3_ldap.auth.LDAPBackend', ] # LDAP Connection Settings LDAP_AUTH_HOST = 'ldap.xxxd.com' LDAP_AUTH_PORT = 389 LDAP_AUTH_URL = 'ldaps://{host}:{port}'.format( host=LDAP_AUTH_HOST, port=LDAP_AUTH_PORT, ) LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" LDAP_AUTH_CONNECTION_PASSWORD = 'mypassword' # Initiate TLS on connection. LDAP_AUTH_USE_TLS = True # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = "ou=users,dc=xxxx,dc=com" # The LDAP class that represents a user. LDAP_AUTH_OBJECT_CLASS = "user" # User model fields mapped to the LDAP # attributes that represent them. LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } # A tuple of fields used to uniquely identify a user. LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } When I comment out this line and try to authenticate, AUTHENTICATION_BACKENDS = [ #'django.contrib.auth.backends.ModelBackend', 'django_python3_ldap.auth.LDAPBackend', ] I get this error: LDAP bind failed: … -
Django: Sending email from user logged in
I have been reading on how to set up email in django. I want to have a page where I input a user's email, subject and message and the email gets delivered. The email should be from the user who has logged in. Is it possible to achieve this in Django? Please note that the system has multiple users. So the email shall be delivered from the logged in user -
Is there an alternative for to_field in django ManyToManyField?
Is there a direct alternative for tp_field (e.g. ForeignKey field) in ManyToManyFields without using through with another ForeignKey field? Example: class A(models.Model): name= models.CharField(...) class B(models.Model): a= models.ManyToManyField(A) I use my Model B in my REST Api and I want to have A.name displayed and not pk. Is there any way to make something like this? -
Django: OperationalError at /admin/ no such table: django_admin_log
I have created an app in django and after creating the app I tried to login to the django admin page, but I got an error message: OperationalError at /admin/ no such table: django_admin_log Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.2 Exception Type: OperationalError Exception Value: no such table: django_admin_log Exception Location: C:\gsData\Workspace\venv\django_ai\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\gsData\Workspace\venv\django_ai\Scripts\python.exe Python Version: 3.7.5 Python Path: ['C:\\gsData\\Workspace\\venv\\django_ai\\src', 'C:\\Users\\pc\\repos\\examples\\deploying-machine-learning-models\\packages\\regression_model', 'C:\\gsData\\Workspace\\venv\\django_ai\\src', 'C:\\gsData\\Workspace\\venv\\django_ai\\Scripts\\python37.zip', 'C:\\gsData\\Workspace\\venv\\django_ai\\DLLs', 'C:\\gsData\\Workspace\\venv\\django_ai\\lib', 'C:\\gsData\\Workspace\\venv\\django_ai\\Scripts', 'c:\\users\\pc\\appdata\\local\\programs\\python\\python37\\Lib', 'c:\\users\\pc\\appdata\\local\\programs\\python\\python37\\DLLs', 'C:\\gsData\\Workspace\\venv\\django_ai', 'C:\\gsData\\Workspace\\venv\\django_ai\\lib\\site-packages'] Server time: Sun, 13 Jun 2021 12:56:56 +0000 Error during template rendering In template C:\gsData\Workspace\venv\django_ai\lib\site-packages\django\contrib\admin\templates\admin\base.html, error at line 0 no such table: django_admin_log 1 {% load i18n static %}<!DOCTYPE html> 2 {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} 3 <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" dir="{{ LANGUAGE_BIDI|yesno:'rtl,ltr,auto' }}"> 4 <head> 5 <title>{% block title %}{% endblock %}</title> 6 <link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}"> 7 {% if not is_popup and is_nav_sidebar_enabled %} 8 <link rel="stylesheet" type="text/css" href="{% static "admin/css/nav_sidebar.css" %}"> 9 <script src="{% static 'admin/js/nav_sidebar.js' %}" defer></script> 10 {% endif %} I have tried doing, python manage.py makemigrations python manage.py makemigrations *appname* python manage.py migrate <app_name> python manage.py migrate --run-syncdb python manage.py migrate --database=<app_name> python manage.py … -
How I can return the email again to the form if the login is invalid
How I can return the register information again to the register Form if the email not valid because as default if the email invalid the form are resitting def register_view(request, *args, **kwargs): user = request.user if user.is_authenticated: return HttpResponse("You are already authenticated as " + str(user.email)) context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) destination = kwargs.get("next") if destination: return redirect(destination) return redirect('home') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form return render(request, 'account/my login/register.html', context) -
Django send_mail from custom username/email
I am trying to make the service for sending email to the user in django when some event is triggered. In my settings.py, I have the following: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'user' EMAIL_HOST_PASSWORD = 'mypassword' However, I would like to send the email from some custom username, as follows: send_mail( 'Subject', 'content', 'customname@myapp.com', ['receiver@gmail.com'], fail_silently=False, ) But when I check my receiver email, the sender is still user@gmail.com (from settings). Is it possible to change this and how would I go about it? -
django-admin rearrange fields inline?
A very simple model: class Store(models.Model): setting_1 = models.CharField(...) setting_2 = models.CharField(...) set_1_parameter_1 = models.PositiveIntegerField(...) set_1_parameter_2 = models.PositiveIntegerField(...) set_2_parameter_1 = models.PositiveIntegerField(...) set_2_parameter_2 = models.PositiveIntegerField(...) and a very simple admin: @admin.register(Store) class Storeadmin(admin.ModelAdmin): list_display = ["something",] this would result in this: setting_1 (charfield) setting_2 (charfield) set_1_parameter_1 (dropdown) set_1_parameter_2 (dropdown) set_2_parameter_1 (dropdown) set_2_parameter_2 (dropdown) but i want it to look like this in the admin: setting_1 | set_1_parameter_1 | set_1_parameter_2 setting_2 | set_2_parameter_2 | set_2_parameter_2 I think I can't do this with a admin.TabularInline, right? How do I do this? I actually have multiple settings with each like 5 options (just parameters) which would nicely fit in one line. -
Django redirect to previous/current URL after LOGOUT
Although the question is simple I can't figure a way out to make this work. I have many pages on a website and each page displays a button for the user to LOGOUT. If the user clicks on the button in some specific page the logout redirect should send them to the same page. Since I'm using the LOGOUT_REDIRECT_URL = '/' in my setting.py the Logout buttons always redirects me to my home page. Thanks in advance. -
Django ORM equivalent of SQL Sum
I have a django model as follows: class Order(models.Model): cash=models.DecimalField(max_digits=11,decimal_places=2,default=0) balance=models.DecimalField(max_digits=11,decimal_places=2,default=0) current_ac=models.DecimalField(max_digits=11,decimal_places=2,default=0) added_by = models.ForeignKey(User) There can be multiple Orders and multiple users can create orders. How can I get the sum of all orders for each columns for a particular user using Django queries, an SQL equivalent would be something like Select sum(cash), sum (balance), sum(current_ac) from Orders where added_by = 1 -
How can I add a link to another page of my site with Django. I am currently getting a Page not found error
Disquaire\urls.py from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from store import views urlpatterns = [ url(r'^$', views.index), url(r'^store/', include('store.urls')), url(r'^admin/', admin.site.urls), ] store.urls.py urlpatterns = [ url(r'^$', views.listing, name='listing'), url(r'^(?P<album_id>[0-9]+)/$', views.details, name="details"), url(r'^search/$',views.search,name='search'), ] list.html {% for album in albums %} <div class="col-sm-4 text-center"> <a href="/store/ {% url 'details' album_id=album.id %}"> <img class="img-responsive" src="{{ album.picture }}" alt="{{ album.title }}"> </a> <h3><a href="/store/ {% url 'details' album_id=album.id%}">{{ album.title }}</a></h3> {% for artist in album.artists.all %} <p>{{ artist.name }}</p> {% endfor %} </div> {% if forloop.counter|divisibleby:3 %}<div class="clearfix"></div>{% endif %} {% endfor %} views.py def details(request, album_id): album = Albums.objects.get(pk=album_id) artists = " ".join([artist.name for artist in album.artists.all()]) message = "Le nom de l'album est {}. Il a été écrit par {}".format(album.title, artists) return HttpResponse(message) index.html {% extends 'store\base.html' %} {% block content %} {% include 'store\list.html' %} {% endblock %} This is the error I get Page not found I have already tried many proposals from the site but nothing work, or maybe I didn't applied them well.I am new to Python and Django so I would appreciate all help. -
Nginx + uWSGI + Django too slow
I have django running on nginx and uwsgi. The cached response loads very fast but at other times the website takes more than 30s to load. I am unable to diagnose the root cause of slowing down. Here's what I can provide as info to help narrow down the issue - GTMetrix - I am observing a GTMetrix constant performance % of 49 (E Grade). Also, sometimes gtmetrix fails to load the website. From the waterfall chart, I can observe that images are taking a lot of time to load, however I am not sure about whether images are the cause. The size of image is maximum 372kb of all images. Here is a more detailed breakdown: Link to the lighthouse parameters Speed Visualization nginx.conf - Here is the nginx config file: user www-data; worker_processes 4; pid /run/nginx.pid; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 75; types_hash_max_size 2048; client_max_body_size 5M; sendfile_max_chunk 512; include /etc/nginx/mime.types; default_type application/octet-stream; log_format upstream_time '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"' 'rt="$request_time" uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"'; access_log /var/log/nginx/access.log upstream_time; error_log /var/log/nginx/error.log; gzip on; gzip_disable msie6; # And all the gzip mime types here include /etc/nginx/conf.d/*.conf; include … -
How to send the AWS s3 signed url rich text editor content to an email to render it in HTML format
I am new to using Django, python for backend development. I worked majorly with react. I'm using react-quill (Rich Text Editor) to store a Welcome Message in AWS S3 bucket from React App. I need to send that Welcome Message in the email from backend and the email needs to contain the Rich Text Editor in same format. I haven't worked on how to send the Rich Text Editor response as like HTML to the email. Below there are two functions one to get that WelcomeMessage stored in s3 using Signed Url When I tried to log the response of content I am receiving the content which I mentioned at the end of the question. I don't know how to convert this response before sending it to email and how to display the content like HTML code in Email. Please guide me. def get_welcome_attachments(obj): attachments = '[' if obj.attachments: image = obj.attachments if image.url: content = requests.get(image.url).content encoded = base64.b64encode(content) file_encoded = encoded.decode("UTF-8") attachments = str(file_encoded) return attachments def send_welcome_invitation_email(obj_id): welcome_obj = WelcomeMessage.objects.get(id=obj_id) attachments = get_welcome_attachments(welcome_obj) emails = ['john@example.com'] context = "{\"invitation\":\""+attachments+"\"}" send_mail(emails, context, config.EXAMPLE_TEMPLATE_ID, []) Response of content in get_welcome_attachments function is. "'<p>Hello</p><br/><p>This tex is from Rich Text Editor</p>"' -
Readonly SELECT field
In my form I have couple of 'select' fields, among others. Now, when I update form, I need to make some fields readonly. Since I can't disable fields because then I'll get no return value, I need to find a way how can I make 'Select' fields readonly. My idea is to somehow change field type to input/text, and then make that field readonly. Is that possible? Or is there a better way? What I use on text fields: document.getElementById('id_rn_number').readOnly = true; And I can't use (on any field type): document.getElementById('id_report_division').disabled = true; -
Django call DRF endpoint in another view and pass data into html template
I have created a Django REST Framework endpoint that returns all the data I need for my page. I am trying to call this endpoint in one of my views and pass the response to the html template as part of the render. when I print(response) it returns <function SetsIndividualData at 0x00000201656AB9D8>. All nothing is returned when I use {{ response.name }} in the html template. What am I missing here? urls.py path('sets/<str:setCode>/', setsIndividualPage), path('sets/<str:setCode>/sets-individual-data/', SetsIndividualData.as_view(), name='sets-individual-data'), views.py def setsIndividualPage(request, setCode): response = SetsIndividualData.as_view() print(response) return render(request, "magic/sets-individual.html", {'response': response}) class SetsIndividualData(ListAPIView): serializer_class = SetSerializers def get_queryset(self): SQL_EXPRESSION = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" setCode = self.kwargs.get('setCode', None) queryList = Set.objects.filter(code=setCode.upper()).prefetch_related(Prefetch('cards', queryset=Card.objects.extra(select={'int': SQL_EXPRESSION}).order_by('int', 'number'))) return queryList -
Login Required Mixin acting up on a view where i didn't even include it(django)
So, i want my website's content only to be visible to the registered users, so i have put "LoginRequiredMixin" amd "@login_required" tags on most of my views except login and register views. Now, for registration, i want to give the registrants a choice before registering (whether they are current university students or alumni/recent graduates), this is how i am doing this: class choice(View): template = "network/choice.html" def get(self, request): form = ChoiceForm() return render(request, self.template, { "form": form, "message": "Are you a curent student or an alumni/about to graduate" }) def post(self, request): form = ChoiceForm(request.POST) if form.is_valid(): current = form.cleaned_data["current"] if current: return HttpResponseRedirect('register/current') else: return HttpResponseRedirect('register/alum') where ChoiceForm just contains a boolean field, and "register/str:type" is my registration URL. But after i submit the Choice Form: <form action="{% url 'network:choice' %}" method="post"> {% csrf_token %} {{ form|crispy }} <br> <input type="submit" value="Proceed" </form> the url to which i am taken to is: /accounts/login/?next=/register/current (i have not included any authentication check on the registration view, that won't make any sense lol) Where i might have gone wrong is: because i want anyone truing to access a restricted page to be redirected to the login page, i have defined my … -
Order of fields for subclass of UserCreationForm not in the correct order
I'm currently trying to learn Django (coming from Rails) and loving it so far. Following an (older) tutorial - I know! - sees me making headway but stumped as to why the following is happening. I'm using Django 3.2 if that helps. I'm trying to add an email field to UserCreationForm. from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) class Meta: model = User fields = {'username', 'email', 'password1', 'password2'} Seems fairly straight forwards. I was assuming the fields would present in the order given, but they aren't: The interesting thing is, each time I restart the server, the order changes. I am reading documentation but can't seem to find how to ensure the order of the fields appears as per the fields in the class Meta. Thanks in advance for any help you might be able to offer. -
Stream value of video stream and detected plate numberin django
I am streaming a video feed from camera using Videocapture(0) in django and passing that frame to detect license plate and in return I get 2 values image with license number and license number as a string I am currently streaming frames using Httpstreamingresponse (django response library) but with that I can only stream frames from Videocapture. I want to stream 2 values frames and license plate number could anyone tell me how to go about that -
How to limit the pagination to fetch only 2 items via pagination at a time only and not all objects?
I have a pagination working on my posts. Here is my model:- class PostListView(ListView): model = PostForNewsFeed template_name = 'feed/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 2 # add this count_hit = True slug_field = 'slug' def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context.update({ 'popular_posts': PostForNewsFeed.objects.order_by('-hit_count_generic__hits')[:3], }) if self.request.user.is_authenticated: liked = [i for i in PostForNewsFeed.objects.all() if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked return context def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( Q(user_name=self.request.user) | Q(user_name__profile__friends__user=self.request.user) ).distinct() Here is my template:- {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/home?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="/home?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> {% endif %} I would like to have it fetch only 2 items at a time and fetch next 2 items instead of all the items in the table. -
Django Use multiple redis for caching
I have a Django project and i am using django-redis where I want to implement different types of caching, Caching search query Caching static pages Cache user Data (eg: online status) I can add different prefix for different kind of caching, but I want to use different redis server for all the different caching I have. I couldn't find anything on the docs how to do this My current settings CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://localhost:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PARSER_CLASS": "redis.connection.HiredisParser", "IGNORE_EXCEPTIONS": True, }, "KEY_PREFIX": "db_cache", } } What I would want CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://localhost:6379/", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PARSER_CLASS": "redis.connection.HiredisParser", }, "KEY_PREFIX": "db_cache", }, 'static_page': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://localhost:6378/", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PARSER_CLASS": "redis.connection.HiredisParser", "IGNORE_EXCEPTIONS": True, }, "KEY_PREFIX": "db_cache", }, 'user_data': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://localhost:6377/", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PARSER_CLASS": "redis.connection.HiredisParser", }, "KEY_PREFIX": "db_cache", } } -
Can't set a cross subdomain cookie in Django
I'm trying to use a subdomain cross site cookie with django but I cannot get it, I am in a valid subdomain but it doesn't seems to be useful. Thie is my conf: SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_DOMAIN = '.ngrok.io' This is the headers from the browser: But I get the message: This set-cookie domain attribute was invalid with regards to the current host url How can I do to make it work? -
Cannot pass current url parameter into Django REST Framework url
I have a page that have a dynamic url to filter data depending on the code that is passed into it. This looks like sets/<str:setCode>/. I have created a Django REST Framework that will return filtered data based on the setCode. This url looks like sets/<str:setCode>/sets-individual-data/ If I manually enter the url, for example sets/cc1/sets-individual-data/ I am presented with the DRF page and the correct filter data. However when I load the page, I am calling the url via javascript and I am getting the following error: Exception Value: context must be a dict rather than str. I believe this is because I and not passing setCode in the url correctly but not sure what the correct way is. urls.py path('sets/<str:setCode>/', setsIndividualPage), path('sets/<str:setCode>/sets-individual-data/', SetsIndividualData.as_view(), name='sets-individual-data'), views.py @login_required() def setsIndividualPage(request, setCode): return render(request, "magic/sets-individual.html", setCode) class SetsIndividualData(ListAPIView): serializer_class = SetSerializers def get_queryset(self): SQL_EXPRESSION = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" setCode = self.kwargs.get('setCode', None) queryList = Set.objects.filter(code=setCode.upper()).prefetch_related(Prefetch('cards', queryset=Card.objects.extra(select={'int': SQL_EXPRESSION}).order_by('int', 'number'))) return queryList sets-individual.html {% load static %} {% block content %} <div id="sets-individual-page" url="{% url 'magic:sets-individual-data' %}"> sets-individual.js var send_data = {} $(document).ready(function () { getData(); }) function putData(result) { console.log() } function getData() { let url = $('#sets-individual-page').attr("url") console.log(url) $.ajax({ method: 'GET', … -
django-rest-frameworks bad request in production for returning json
I want to show some data on the home page when user visits the app. So in development it works. but this returns bad request in production. App is deployed on heroku. I get this on the console: The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. So I added this setting: REST_FRAMEWORK = { 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata' } Still does not work for a simple json?