Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework model viewset extra action responding always "Not found" error
why does setting customize actions for the model view set is not working well? from topbar.models import TopBar this is the relevant part in viewset code: from rest_framework import viewsets from rest_framework.decorators import action from rest_framework import permissions from rest_framework.exceptions import NotAcceptable from rest_framework.response import Response from rest_framework.decorators import action from topbar.serializers import TopBarSerializer class TopBarSet(viewsets.ModelViewSet): """ API endpoint from top bar content """ queryset = TopBar.objects.all() serializer_class = TopBarSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['get', 'post', 'put'] @action(detail=True, methods=['get']) def set_topbar(self, request): return Response({'status': 'topbar set'}) I'm using routing exactly like the documentation: router = routers.DefaultRouter() router.register(r'topbar', TopBarSet, basename='topbar') -
Pushing a Django Python App to Heroku for web hosting. Creating superuser gets an Operational Error and could not connect to server
I am pushing a Django Python App to Heroku for web hosting. I am following a tutorial, the build was successful, and loads up fine as a Heroku app. Django Admin page loads up, but superuser cannot log in as the next step is database configuration. The tutorial then goes: heroku run python manage.py makemigrations heroku run python manage.py migrate heroku run python manage.py createsuperuser This creates the following error: psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Before running these commands, the tutorial attempted to login as superuser in the heroku app. The tutor got a 'programming error', but I had an 'operational error'. Now, somehow, I managed to make the database changes in settings.py for the next tutorial video already. I hope it's not this that has fudged things? -
running multiple tasks (ffmpeg) at the same time in a django app
at the title says it, I made a django app that cuts and merge files with ffmpeg while testing (me being the only user), it looks fine, but later when using the app from different browsers running tasks at the same time, looks like it's a queue of tasks and other users will wait for their turn, what I'm thinking about is, is there a possibility to run multiple tasks simultaneously at the same time, like (screens on linux) under django framework? thanks a lot -
how to mock a method which has both post and get api calls in django
This my actual code which performs get and then post api call to external service. And I have to write unit test for 'senduserdata'. Foo.py from requests_futures.sessions import FuturesSession def senduserdata(): usernames = getusername() postdata() def getusername: with FuturesSession() as session: futures = session.get() return futures.response def postdata(): with FuturesSession() as session: futures = session.post() return futures.response What I tried in unit test: Unittest.py from concurrent.futures import Future from unittest import mock from django.test import TestCase from django.urls import reverse @mock.patch('app.FuturesSession.post') def test_senduserdata(self, mock): self.mock_response(mock) senduserdata() mock_post.assert_called_with() def mock_response(self, mock): mock.reset_mock() future = Future() future.set_result(Response()) mock.return_value = future How can I add get mock in the same unit test -
How can I create unique pop up windows displaying different content in dtl and html?
I am wondering how to display different content on each pop-up window using django and html. Ι have the following code: {% for sect in sects %} {% if sect.name %} <p><div class="popup" onclick="myFunction()" id="{{ sect.name }}">{{sect.name}}</p> <span class="popuptext" id="myPopup"> <table class="table table-hover" style="text-align:left; width:100%" cellpadding="1"> <tr> <th>Περιγραφή</th> <th>{{sect.description| safe | linebreaks}}</th> </tr> <tr> // ... more stuff here..// </table> </span> </div> <script> // When the user clicks on <div>, open the popup function myFunction() { var popup = document.getElementById("myPopup"); popup.classList.toggle("show"); } </script> {% endif %} {% endfor %} So the result is to have a list of my sect items printed in my page, but only one (the same) pop-up. Trying to have a unique id (named after the sect.name) or trying to pass it as an argument to myFunction() does not seem to work. Could you please give me a hint on this? Thank you very much! -
How to change THIS specific text output in django admin?
Hey im working in django 3.1 and i literally only need to change the name of the sections (example ACCOUNT on the Blue bar) i know how to change the verbose name of the models but that does not affect the section name. Any help? i need to have this working on spanish and it's a little messy to rename the models to the spanish word. Any solution that only affects the output text??? not the whole File name (Account is the name of the file, wich contains the 3 class below) -
Django api response is late. is there any good solutions?
I'm using django and react to build a website and I faced the problem that before react get a response from api, react excutes the next line. I could combine the function calling api and the swipe function, but it will be hard to read. I want to separate them if I could. Here is my code. const liked_getter = (user) => { var liked_data axios.get(`${process.env.REACT_APP_API_URL}/swipe/detail/${user}/`) .then(res => { liked_data = res.data.liked }) return liked_data } const swiped = (direction, person) => { if (direction === 'right') { var liked_data = liked_getter(person.user) if (liked_data.includes(props.id)) { console.log('MATCH') } } } liked_getter get the data from api based on user id, and I store data in liked_data, but react executes the next line "if (liked_data.includes(props.id))" as liked_data=undefined. It worked when I combined these two functions like this. const swiped = (direction, person) => { setLastDirection(direction) alredyRemoved.push(person.name) if (direction === 'right') { props.Swipe(props.swipe_id, person.user, person.user) //var liked_data = liked_getter(person.user) axios.get(`${process.env.REACT_APP_API_URL}/swipe/detail/${person.user}/`) .then(res => { if (res.data.liked.includes(props.id)) { console.log('MATCH') } }) } else { props.Swipe(props.swipe_id, person.user, null) } } However it's hard to read and I'm going to add more code here. Is there any good ways to divide them? Thank you :) -
No module named "django.core.asgi"
I"m deploying django app based on channels and when i run daphne -b 0.0.0.0 -p 8001 repository.asgi:application then i get the error No module named "django.core.asgi". What should be done? -
Django not returning queryset despite using get,filter and all
Please I am a beginner and I'm trying to make a Hospital Management System.I want to display the Patient profile however it is only returning the first name in my queryset. I need all the data saved to my database displayed.I've tried filter, get and all.They return only the first name as defined in my str method. Views def ProfileView(request): profile = Patient.objects.filter(email=request.user.email) return render(request,'profile.html',{'profile':profile}) Models class Patient(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email= models.EmailField(unique=True) phone_number = models.CharField(max_length=11) address = models.CharField(max_length=255) def __str__(self): return self.first_name Profile.html {%extends 'base.html'%} {%load static%} {%block content%} <div class="container"> {{profile}} </div> {%endblock content%} Result that displays in html <QuerySet [<Patient: Kehinde>]> -
How integrate Liqpay in django python3?
How inegrate liqpay in python3??enter image description here -
django admin disable password change for specific user
I'm currently working on a SAAS project and I would like to create an admin user for demo that anyone can access. To remove change password, I tried using set_unusable_password() but it does not work as it says password is incorrect when I try to log in. This is the code I'm using : admin = Admin.objects.create_user('admin', password='admin') admin.is_superuser = True admin.is_staff = True admin.set_unusable_password() admin.save() After looking at the docs, I found out that set_unusable_password marks the user as having no password set, and doesn’t save the User object. This explains why I could not login at the first place. So clearly set_unusable_password is not the solution. What I actually want is to login as usual, but for that specific user, the change password should be disabled, as the demo account will be used by all other testers and therefore the password should not be changed by anyone. -
All orders are not showing
I want to show all orders in a table of my panel but its not showing.Its showing in django admin but not showing in my panel. Here is my Views.py: class AdminPanel(View): def get(self, request): products = Product.get_all_products() cats = Category.get_categories() orders = Order.get_all_products() args = {'products':products, 'cats':cats, 'orders':orders} return render(self.request, 'adminpanel/main.html', args) Here is my HTML file: <table class="table table-bordered"> <thead> <tr> <th scope="col">Sno.</th> <th scope="col">Date</th> <th scope="col">Invoice ID</th> <th scope="col">Customer Name</th> <th scope="col">Phone Number</th> <th scope="col">Product Quantity</th> <th scope="col">Status</th> <th scope="col">Total</th> </tr> </thead> <tbody> {% for order in orders %} {% if orders %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{order.date}}</td> <td>GNG#{{order.id}}</td> <td>{{order.fname}}</td> <td>{{order.phone}}</td> <td>{{order.quantity}}</td> <td>{{order.status}}</td> <td>{{order.price}}</td> </tr> {% else %} <h5 class="badge badge-danger">No Orders Found</h5> {%endif%} {% endfor %} </tbody> </table> -
Github best practices - various django applications
I have an application that consists of more than one django APP. Each APP works separately, has its own VM to process requests. Today we use the following structure in GITHUB: Project ├── application1 # this application works in a separated vm ├── application2 │ ├── app # app folder │ ├── requirements.txt #requirements file │ └── manage.py └── ... I was thinking of decoupling this project in more than one repository. Each will address an application. With this approach, I can build a CI / CD pipeline for each application I would like to know from you what is the best practice to solve this problem. Whether it’s good to keep all aspects of the project in one repository or split into more than one -
Sing in and Sing up in same page Django
i'm working on a project with django and i have a problem, i need to have Sing In and Sing Up in same page; I tried many code, but no one work, when i try to log in the page redirect me without log me. How can i solve this problem ? Views.py I think the error is here, but i don't know def Registrazione(request): if request.method == "POST": if 'Register' in request.POST: form = Registrazioneform(request.POST) if form.is_valid(): username = form.cleaned_data["username"] email = form.cleaned_data["email"] password = form.cleaned_data["password1"] if User.objects.filter(username=username).exists(): return HttpResponse ("<h1>Username gia presente</h1>") else: user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) email_subject = 'Activate Your Account' message = render_to_string('activate_account.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)),#decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(email_subject, message, to=[to_email]) email.send() elif 'Login' in request.POST: #username = request.POST['username'] #password = request.POST['password'] #user = authenticate(username=username, password=password) #if user is not None: #login(request, user) #return HttpResponseRedirect("/") username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect('/') else: print("NOT WORK") return HttpResponse("Your account was inactive.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username,password)) return HttpResponse("Invalid login details given") else: … -
How to differentiate multiple GenericForeignKey relation to one model?
I have the following model structure: class Uploadable(models.Model): file = models.FileField('Datei', upload_to=upload_location, storage=PRIVATE_FILE_STORAGE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Inspection(models.Model): ... picture_before = GenericRelation(Uploadable) picture_after = GenericRelation(Uploadable) I wonder how I can tell that one file was uploaded as a picture_before and another as picture_after. The Uploadable does not contain any information about it. Googled around for some time but did'nt find a proper solution. Thanks for the support! -
How to link anchor to another tab and also within the same tab in Django template
I'm building a page with dynamic tabs base on reference to document https://www.w3schools.com/howto/howto_js_tabs.asp I'm using Django framework. I'm facing issue on linking my tab internally within the tab itself, also from tab to tab. When the page is loaded, it will first holds 2 tabs: the Form Tab and the Summary Tab. If form is filled correctly, the flow will generates dynamic tabs, Check Tabs, IE Check 1, Check 2, Check 3 Tabs appending to the same page after Summary Tab. I managed to generate all the tabs but can't anchor item within 'Summary Tab' to 'Check Tab. Besides, I also fail to anchor within the same tab. Can someone gives suggestion how to solve this problem? I would like to avoid using a bootstrap if possible. My js file: function openSummary(evt, summaryName) { // Declare all variables var i, tabcontent, tablinks; // Get all elements with class="tabcontent" and hide them tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // Get all elements with class="tablinks" and remove the class "active" tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // Show the current … -
Django for windows, using WSGIPythonPath for multiple instances of Virtual Host
Im using Windows 10 In httpd.conf (Apache) how to use WSGIPythonPath for multiple instances of Virtual Host for different project and ports since WSGIDaemonProcess is not supported on Windows. httpd.conf LoadModule wsgi_module "c:/users/webdev/documents/mark/digos-logs/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "C:\Users\WebDev\AppData\Local\Programs\Python\Python37" WSGIPythonPath "C:\Users\WebDev\Documents\Mark\digos-logs" where "C:\Users\WebDev\Documents\Mark\digos-logs" is my project root folder and "C:\Users\WebDev\Documents\Mark" is my parent folder of all my projects. Project 1 listen 9292 <VirtualHost *:9292> ServerName 127.0.0.1 # error occured (Example) WSGIPythonPath "C:\Users\WebDev\Documents\Mark\digos-logs" ######3 WSGIScriptAlias / "C:\Users\WebDev\Documents\Mark\digos-logs\app_ict\wsgi.py" <Directory "C:\Users\WebDev\Documents\Mark\digos-logs\app_ict"> <Files wsgi.py> Require all granted </Files> </Directory> DocumentRoot C:\Users\WebDev\Documents\Mark\digos-logs <Directory "C:\Users\WebDev\Documents\Mark\digos-logs\static"> Require all granted </Directory> </VirtualHost> Project 2 listen 9595 <VirtualHost *:9595> ServerName 127.0.0.1 # error occured (Example) WSGIPythonPath "C:\Users\WebDev\Documents\Mark\project2" ######3 WSGIScriptAlias / "C:\Users\WebDev\Documents\Mark\project2\app\wsgi.py" <Directory "C:\Users\WebDev\Documents\Mark\project2\app"> <Files wsgi.py> Require all granted </Files> </Directory> DocumentRoot C:\Users\WebDev\Documents\Mark\project2 <Directory "C:\Users\WebDev\Documents\Mark\project2\static"> Require all granted </Directory> </VirtualHost> -
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.