Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django website very slow using Apache and mod_wsgi
so today I tried to host a website using django on a Ubuntu vServer using Apache and mod_wsgi. First I tested it with a blank django project, and everything worked perfectly, but as soon as I put my django project on the server and set Apache up to run with that, the performance of the server dropped a lot. When accessing the website using apache, the response time is about 10 seconds per page, in contrast do about 100ms when using the django dev server. Does any body have any tips on what could be the cause of that? I've read that there may be problems with the some mpm workers, but i didnt really find the files i would need to adjust on my server. The apache server config looks like this(paths changed): <VirtualHost *:80> . . . Alias /static /home/sammy/myproject/static <Directory /home/sammy/myproject/static> Require all granted </Directory> <Directory /home/sammy/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/home/sammy/myproject/myprojectenv python-path=/home/sammy/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/sammy/myproject/myproject/wsgi.py I would really appreciate any help or tips in general. -
Django not taking users to the "password_change" url
I'm trying to add a functionality for users to change their current password. But, when I click on the link to take me to the password change form, it takes me to the default django password change form, which is in the admin site. But I had built out a template for changing the users password. I have two apps: one called pages, and another called users. I have a templates directory both in my users and pages app. My base.html is in my users app. And, here is my project structure: My pages app template contains the home.html file. My base.html and signup.html is in my users app templates I have another folder called registration in my users/templates folder. In this registration folder, I have login.html, password_change_form.html and password_change_done.html Here is the line that links my base.html to my password_change_form.html: <a class="dropdown-item" href="{% url 'password_change'%}>Change password</a> I believe this should work, but I might be wrong, as I'm still new. Any help would be appreciated. -
Django is_authenticated() always returns false on index page, but not on other pages
I use the same layout.html on different pages on my website, which includes a login check. {% if user.is_authenticated %} Signed in as <strong>{{ user.username }}</strong>. {% else %} Not signed in. {% endif %} If I log in, the statement returns true on all pages except my index page. I therefore suspect something is wrong with my registered urls. However, I can't find the problem. My site/urls.py: from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include("app.urls")), ] My app/urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name = "index"), path("login", views.login_view, name = "login"), path("logout", views.logout_view, name = "logout"), path("register", views.register, name = "register"), path("lobby/<str:lobby_name>/", views.lobby, name = "lobby") ] My site/settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '123' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'channels', 'app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF … -
How to loop for integer value in django template?
The integer value in obtained from context. So how do I loop for specific integer value? -
Django-Filter "contains" on related field
I have two simple models which are linked by a Foreign Key: models.py: class Operator(models.Model): operator = models.CharField(max_length=50, primary_key=True, verbose_name='Operator') operator_name = models.CharField(max_length=100, verbose_name='Operator Name', blank=False, null=False) class SubOperator(models.Model): operator = models.ForeignKey(Operator, on_delete=models.CASCADE) sub_operator = models.CharField(max_length=50, verbose_name='Sub Operator') sub_operator_name = models.CharField(max_length=100) start_date = models.DateField(blank=False, null=False, verbose_name='Start Date') end_date = models.DateField(blank=False, null=False, verbose_name='End Date') The User should be able to select the operator with a "like" which translates to "lookup_expr='contains'" in the Django-Filter Module but unfortunately I get the following Exception: "django.core.exceptions.FieldError: Related Field got invalid lookup: contains" filters.py: operator = django_filters.CharFilter(field_name='operator', lookup_expr='contains', label='Operator') -
Getting Identity provider login error when trying to authenticate user from Microsoft via keycloak
I am trying to authenticate the user from Microsoft-AD IDP using keycloak as an identity broker. Tech stack used: frontend- react, backend- django(python), IAM solution- keycloak, IDP- Microsoft I am redirecting the backend views to keycloak's authorization endpoint for getting code as per oauth2: ... def login(self, request): authorization_endpoint="http://keycloakIP:port/auth/realms/r1/protocol/openid-connect/auth" redirect_uri="http://localhost:8000/login/getAccessToken" *#django API url to get access token after getting authorization code* auth_request=authorization_endpoint+'?client_id='+client_id_var+'&response_type=code&scope=openid&redirect_uri='+redirect_uri return redirect(auth_request) ... When this login API is hit from frontend then it starts giving 400 bad request error at this redirect(auth_request) and type=IDENTITY_PROVIDER_LOGIN_ERROR, realmId=r1, clientId=null, userId=null, ipAddress=IP, error=invalid_code, identity_provider=M-AD error at keycloak logs. But when this login API is hit from the browser directly passing required query params like usernmae.... it works completely fine and redirects to the keycloak (which in turn redirect to Microsoft) and gets back the access token after succesful authentication... Questions: 1.whether issue is with the redirect urls put in the API or some keycloak config... bcoz its working in one way but not the other. 2.why is clientId=null shown in keycloak logs bcoz... its picking the correct realmId, IPAddress but not clientId.. -
Project structure for Django Application with multiple authentication type
I am new to Django although have done web projects using PHP/laravel. I am trying to learn Django by developing a simple project. My project will be a sample food delivery project. There are mainly two parts. Web Dashboard for Food Store Owners API for Customer APP for the Web Dashboard part, I am planning to use session-based authentication and templates. So owners/managers will register/login to the dashboard and manage orders. and For the Customer APP, It will be some rest APIs for the Mobile APP. Customers will be able to register/login to the Mobile APP and place orders. I am planning to use JWT token for this part. Now, I am a little bit confused about the project structure. Will I make two different apps for the Web and API part? How to manage two different types of authentication? I will be glad if someone can give me some tips and let me know the best practice for structuring this type of project. Thanks in Advance! -
Django send emails to Updates folder
Is there any way to make the emails sent with EmailMultiAlternatives() go to a specific folder/section in the email client? In my case, I would like it to go in the 'Updates' folder/section. It seems like I can't find an answer to this question. However I receive multiple emails that I guess are auto-generated in my 'Updates' category. -
Django CreateView not redirecting to success url
I'm implementing the following CreateView, which is supposed to redirect to a product list after a product has been added to my application. When the form is submitted, the product is successfully added, but the user is not redirected. Instead, the same product form is loaded. class ProductCreate(CreateView): model = Product fields = '__all__' template_name = 'catalog/product/add_product.html' def form_valid(self, form): form.instance.category = get_object_or_404(Category, form.instance.category) return super(ProductCreate, self).form_valid(form) def get_success_url(self): return reverse_lazy('product_detail', kwargs={'id': self.object.pk, 'slug': self.object.slug}) def get_context_data(self, **kwargs): context = super(ProductCreate, self).get_context_data(**kwargs) context['customers'] = Customer.objects.filter(company=self.request.user.profile.company) context['categories'] = Category.objects.filter(company=self.request.user.profile.company) return context Again, the data is successfully stored into the database, but the redirection is not working at all after the form is saved. Anyone can help me? -
Creating django groups
I have a webapp and all of my users are divided into 2 groups: Teachers and Students. How can I create groups and assign users to groups in order to identify which group a user belongs to in Django? Additionally, can I create views that only certain groups can access? -
Django rest framework and PostgreSQL best practice
I am using Django and PostgreSQL (psycopg2) for one of our web REST API projects. Basically, the app is driven by the django-rest-framework library for all REST API-centric tasks such as authentication, permission, serialization and API views. However, since our database tables are not created thru Django's migration system (rather created manually and directly thru DBeaver), our modeling and serialization can actually be considered as highly customized and is no longer following Django's ORM standard (although we try to write our custom ORM design to feel as close as Django's as possible so that the pattern will still feel familiar). The way I communicate CRUD actions to and from the database is by creating one (1) custom manager class mapped to each custom model class that it's supposed to manage. So in my manager I have like get(), insert(), update(), delete(), force_delete() methods which contain logic for actually sending queries to the database. For all methods responsible for fetching data i.e. get() all() filter(), they communicate through a database view instead of directly sending a query to the concerned table that may contain JOINs which may be too expensive for the DB server. This design works fine for us, but … -
How to communicate with Content Based filtering python code in Django web application or using javascript
I am a beginner and created a Food Ordering Web Application as my first Django Project now i have made a content based filtering program in jupyter notebook that uses cosine similarity to recommend user the food item. So i would like to deploy this program into my web application such that when the user orders "item X with id 1" using the html button in the front end it should communicate with my python program and pass id in recommend function and return the output to the front end.How should i approach this and what do i need to do the same? -
i need to understand how to code app like Balagram that exchanges instagram likes and comments
This is the app https://bala-gram.com/. I need to know the functionality of the app that i can code the backend working it use to be doing. I wonna code in Python and need guidance related to it. I wonna code a clone of above mentioned app. -
Paragraph under label in Crispy Forms, Django
How to render under every label in crispy form a paragraph eg. "optional field" My code: <div class="card-body formset-body"> {% for form in formset %} {% crispy form %} {% endfor %} </div> I tried to loop through every field but it doesnt work how i want, beacuse it doesnt keep the style, and paragraph "optional field" render under input not label as i wish. {% for field in form %} {{ field|as_crispy_field }} <p> optional field </p> {% endfor %} -
Make custom filtering, combining two fields
I have a django rest framework model with the following definition class Test(models.Model): id = models.IntegerField(primary_key=True, unique=True) username = models.CharField(max_length=256) I want a to generate a custom lookup method that will receive id OR username and return the same results. for example if i call the api like api/Test/?custom_lookup_method=12345 OR api/Test/?custom_lookup_method=john_smith to return the same filter results. Is that possible ? -
Is possible have an allert box like javascript alert() on Django when you're detateing a post?
I'm working on a Django site and I would create a simpler way to delate a post better than going in a new HTML page every time. There is a way to have an alert box like JavaScript alert("text") and you can click Ok to delate or the x to maintain the post and a way to not change the page? The code is: Urls.py code... path('dashboard/delate/<slug:slug>', PostDeleteView.as_view(), name="delatepost"), Views.py code... class PostDeleteView(DeleteView): model = Post template_name = "admin/deletepost.html" success_url = reverse_lazy("listpost") html code... {% extends "admin/layout.html" %} {% block title %} <title>Add Post</title> {% endblock title %} {% block content %} <form enctype="multipart/form-data" method="POST"> <center> <div class="addpost"> {% csrf_token %} <h1>delete {{ post.title }}?</h1> <button>Remove</button> </div> </center> </form> {% endblock content %} (Right now there are not auth things because in on testing on my computer) -
Django distinct with order by different column
I have such model class Product(models.Model): created_at = models.DateTimeField(default=timezone.now) cell = models.CharField(max_length=100, null=True) Now I need a queryset that must be ordered by creation date and unique cell, something like Product.object.order_by('created_at').distinct('cell') but I got an sql error. How should queryset be changed to get required result? -
can someone explain the following
can someone please explain why is {% for item in items %} and {{item.product.id}} written in the following code, I'm trying to put an add to cart functionality to my store: cart.html: {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="{% url 'store' %}">&#x2190; Continue Shopping</a> <br> <br> <table class="table"> <tr> <th><h5>Items: <strong>{{order.get_cart_items}}</strong></h5></th> <th><h5>Total:<strong> ${{order.get_cart_total|floatformat:2}}</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="{% url 'checkout' %}">Checkout</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div class="cart-row"> <div style="flex:2"></div> <div style="flex:2"><strong>Item</strong></div> <div style="flex:1"><strong>Price</strong></div> <div style="flex:1"><strong>Quantity</strong></div> <div style="flex:1"><strong>Total</strong></div> </div> {% for item in items %} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div> <div style="flex:2"><p>{{item.product.name}}</p></div> <div style="flex:1"><p>${{item.product.price|floatformat:2}}</p></div> <div style="flex:1"> <p class="quantity">{{item.quantity}}</p> <div class="quantity"> <img data-product="{{item.product.id}}" data-action="add" class="chg-quantity update-cart" src="{% static 'images/arrow-up.png' %}"> <img data-product="{{item.product.id}}" data-action="remove" class="chg-quantity update-cart" src="{% static 'images/arrow-down.png' %}"> </div> </div> <div style="flex:1"><p>${{item.get_total|floatformat:2}}</p></div> </div> {% endfor %} </div> </div> </div> {% endblock content %} and here is the template of my main store page: store.html: {% load static %} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 … -
How to put a django form ImageField to model ImageField
I´m trying to build a frontend where users can upload images (and some other data) via django form ImageField, and that should be saved in a separate admin model to review the upload. I handle the form in the views.py and create the review Model. It works fine so far, except of the images. The ImageFields of the review model stay empty in admin backend, and the uploaded images are also not stored in the defined upload folder. What am i doing wrong? -
How to Deploy a Django React App on Linux server up at hostus.us
I'm given a Task to deploy a web app with Django as back-end and react as front-end . I have my files on git-lab and a paid server up on Hostus.us . On googling i have found out that i have to use putty and connect with that server using ssh . But i don't have any idea how what to do after that and how can this be accomplished . Can anyone please help me with how should i do this? I'm doing it just the very first time. -
Show button only if word count is greater than 200 in django
I am trying to display a button only when the word count is greater than 200 For example: if a user writes a blog of more than 200 characters the button shows up that leads to the complete post. And if its less than 200 the button should not be there I am slicing my code with <p class="article-content">{{ post.content|slice:":200" }}</p> <a class="btn btn-primary" href="{% url 'post-detail' post.id%}">Read More &rarr;</a> But in the above code the button is being displayed even with blogs of less than 200 words -
Unable to located Package Daphne
I'm deploying a django app including django channels using nginx, gunicorn and daphne. But when i install daphne with sudo apt install daphne, it gives E: unable to locate package daphne. What Should I do? -
How to use matplot lib in Django with multiple users
I'm using matplotlib to generate the figures and graphs in my Django application. It has been working well in generating multiple graphs when I was testing it with only one user logged in. However, I have been encountering issues when I am generating graphs when there are more than 1 user using the app. Currently I have 4 figures that are graphed per user, I am clearing the plot using plt.close(fig) when I will go to the second graph to avoid overlapping. It throws an error Given element not contained in the stack when I am about to graph the next figure. Here is a sample snippet of the code (Note that I cut some unnecessary parts): fig = plt.gcf() #---do something to save figure--- plt.close(fig) plt.plot(x, y, 'ro', label='graph') I am guessing the Django clears the plot for both users and the moment another user is accessing the graph it is gone from the memory. Is there a way to reference plt exclusively so it only clears the plot specific to that user and not all plots? I am currently trying if I can use Django sessions to solve the problem. -
Image not rendering in django template
I have an aws account where I upload all my images but when I go to try to render each image by doing die.image.url nothing happens. My code currently looks like this. {% if dice %} <div class="dice-container"> {% for die in dice %} <div class="die-container"> <img src="{{ die.image.url }}" alt="{{ die.name }}" width="100%" /> <h6>{{ die.name }}</h6> </div> {% endfor %} </div> {% endif %} my Die model has a field image. The name of each die comes out but the image not. How do I render the image? -
Creating an array field in the Django Database Model
Hey guys I'm creating a primitive social media app and I'm trying to create an array in my table that has a list of usernames that the user will be following so that their feed shows only posts from users that they are following. How can I do this? Right now I only have integers and strings but what if I need an array or a data type that can store multiple values? Here is my code. I want "follows" to be the array (or multiple value) field. class User(AbstractUser): pass follows = models.CharField(max_length=64, default=0) followers = models.IntegerField(default=0)