Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting DisallowedRedirect error with password changin view - Django
views.py @login_required def mudar_senha(request): if request.method == 'POST': print(request) form = PasswordChangeForm(user=request.user, data=request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Importante para não deslogar o usuário após a mudança de senha return HttpResponseRedirect(reverse('users:perfil')) else: form = PasswordChangeForm(user=request.user) return render(request, 'users/editar_usuario.html', {'form': form}) urls.py """Define padrões de URL para users""" from django.contrib.auth.views import LoginView, LogoutView, PasswordChangeView from django.urls import path # Importa o modúlo viws para a pasta do app "." from . import views app_name = "users" urlpatterns = [ path('login/' , LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', LogoutView.as_view(next_page='learningLogApp:index'), name='logout'), path('perfil/', views.perfil, name='perfil'), path('registrar/', views.registrar, name='registrar'), path('editar/', views.editar_usuario, name='editar_usuario'), path('mudar_senha/', PasswordChangeView.as_view(success_url='learningLogApp:index'), name='mudar_senha'), ] **Exception Type: **DisallowedRedirect try this: return HttpResponseRedirect(reverse('users:perfil')) and this: sucess_url = reverse_lazy(request, 'users/perfil.html') and this: return reverse_lazy(request, 'users/perfil.html') and this: return reverse_lazy(request, 'users:perfil') and this: return reverse_lazy('users:perfil') and this: return redirect('users:perfil') and this: return HttpResponseRedirect(reverse('learningLogApp:index')) and this: return redirect('users:perfil') Same error in all cases. Ps. The password ARE changing. The problem is with the redirect! (Exception Value: Unsafe redirect to URL with protocol) -
How can I make a paragraph in Django Admin form to be italic? I am using Vue3 Composition API for frontend?
I am building a blog app with a body TextField in Django Admin with Vue3 composition API as frontend. I have tried several ways to make the body (article) to be italic but It only displays the raw input (e.g. italic). I want to make a paragraph italic in Django Admin with body textfield. How do I do that? Admin.py: from django.contrib import admin from blog.models import Profile, Post, Tag from django import forms from .widget import ItalicizedTextInput class PostModelAdminForm(forms.ModelForm): body = forms.CharField(widget=ItalicizedTextInput) class Meta: model = Post fields = '__all__' @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): model = Profile @admin.register(Tag) class TagAdmin(admin.ModelAdmin): model = Tag @admin.register(Post) class PostAdmin(admin.ModelAdmin): model = Post form = PostModelAdminForm list_display = ( "id", "title", "subtitle", "slug", "publish_date", "published", "body" ) list_filter = ( "published", "publish_date", ) list_editable = ( "title", "subtitle", "slug", "publish_date", "published", "body", ) search_fields = ( "title", "subtitle", "slug", "body", ) prepopulated_fields = { "slug": ( "title", "subtitle", ) } date_hierarchy = "publish_date" save_on_top = True @admin.register(Tag) class TagAdmin(admin.ModelAdmin): model = Tag @admin.register(Post) class PostAdmin(admin.ModelAdmin): model = Post form = PostModelAdminForm list_display = ( "id", "title", "subtitle", "slug", "publish_date", "published", "body" ) list_filter = ( "published", "publish_date", ) list_editable = ( "title", "subtitle", "slug", … -
How do I start properly Django project?
I wrote C:\Users\jj>django-admin startproject mysite And the results are Fatal error in launcher: Unable to create process using '"c:\program files\python38\python.exe" "C:\Program Files\Python38\Scripts\django-admin.exe" startproject mysite' I tried to start my first django project, but It wont open. I can't find any solutions to this problem on the internet and I have not idea what to do next -
DB PostgreSQL data invisible in my website
we developing a website and I have a problem with data stored in DB PostgreSQL locally including images uploaded in some pages from DB just visible to me when I share the code with my team they can't see the images even though they have already been uploaded to their directory file in the project how can I fix that and there are steps we should take when we making a website and using DB ( we use the same usename;and pass of DB server and when i update the database and they pull the code it just update the schema without the data i stored -we use vs code ide,python lang and Django framework,PostgreSQL DB Github for sharing) -
Github mistakes. I lost latestfile
Github mistake I didnot know what i did. but i just deleted all my files . a day before i commit directly to main. i now create a branch , commit , goto main and then merge branch to main and push. i accidentally deleted all my latest work. then i am with old data. it only shows one commit in git log of lastnight which was my first commit of project. *jobsearch is project name add job and notification was commit message dbc0f6f (HEAD -> main, origin/main) HEAD@{0}: checkout: moving from branch1 to main cd95d6d (branch1) HEAD@{1}: commit: add job and notification dbc0f6f (HEAD -> main, origin/main) HEAD@{2}: checkout: moving from main to branch1 dbc0f6f (HEAD -> main, origin/main) HEAD@{3}: checkout: moving from main to main dbc0f6f (HEAD -> main, origin/main) HEAD@{4}: commit (initial): jobsearch PS C:\Users\gunar\OneDrive\Desktop\Coders\JobSearch> git reset --hard HEAD~ undo cd95d6d (branch1) HEAD@{1}: commit: add job and notification dbc0f6f (HEAD -> main, origin/main) HEAD@{2}: checkout: moving from main to branch1 dbc0f6f (HEAD -> main, origin/main) HEAD@{3}: checkout: moving from main to main dbc0f6f (HEAD -> main, origin/main) HEAD@{4}: commit (initial): jobsearch A day before i commit directly to main. i now create a branch , commit , … -
Django 403 "detail": "Authentication credentials were not provided." Knox Tokens
I was following this tutorial (https://github.com/bradtraversy/lead_manager_react_django/tree/db45e4f6fc05a3481e7b8a0223e0aab0355a84b6) to make a Django-React-Redux application. I am having trouble with my UserAPI, specifically when making a GET request. Note that I am using knox tokens. As the logout function works fine (this function is a default from knox), I can see that the token is properly generated from the login, as I use this token for logout. I suspect that there is something in my settings.py that is wrong. The error is: 403: "detail": "Authentication credentials were not provided." class UserAPI(generics.RetrieveAPIView): # this route needs protection # need a valid token to view permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user # Get the registered organizations of the user @action(methods=['get'],detail=True) def registered_orgs(self,request,*args,**kwargs): instance = self.get_object() orgs = instance.followed_organizations.all() serializer = OrganizationSerializer(orgs,many=True) return Response(serializer.data) Here is my settings file: """ Generated by 'django-admin startproject' using Django 4.1.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os import mimetypes mimetypes.add_type("text/javascript", ".js", True) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # … -
how can i fix the ImportError cannot import name 'get_accounts'
hi im trying out python and django for the first time and im trying to set up a simple route to display some data. The issue im running into is that when i try to run the webserver i keep getting this importError regarding one of the functions in my views.py file located in the accounts folder. any help would be greatly appreciated!!! django version: 5.0.3 python version: 3.11.8 Error - ImportError: cannot import name 'get_accounts' from 'accounts.views' /accounts/views.py from django.http import JsonResponse from .models import Account def get_accounts(): accounts = Account.objects.all() data = [{"id": account.id, "type": account.type, "balance": account.balance,"transactions": account.transactions} for account in accounts] return JsonResponse(data, safe=False) /accounts/urls.py from django.urls import path from . import views app_name = "accounts" urlpatterns = [ path('accounts_list/', views.get_accounts, name='account-list'), ] urls.py from django.urls import path from accounts.views import get_accounts urlpatterns = [ path('api/accounts/', get_accounts), ] -
Why nginx don't see staticfiles and Media files Django +nextjs +Docker
I have Nginx config and using Docker to server Django, Nextjs and Nginx server { listen 80 default_server; return 403; } server { listen 80; location /staticfiles/ { alias /app/staticfiles/; } location /mediafiles/ { alias /app/mediafiles/; } location / { proxy_pass http://nextjs:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location ~* ^/(api|admin) { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://server:9000; } } The problem is when I added a location to nextjs, nginx doesn't want to see static files, but if I use config without next js django + admin it serves ok. server { listen 80; location / { try_files $uri @proxy_django; } location @proxy_django { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://server:9000; } location /staticfiles/ { alias /app/staticfiles/; } location /mediafiles/ { alias /app/mediafiles/; } } Thanks for helping -
How to resolve possibly conflicting urls in webpage rendering
When I try to load a page, I get another page instead... I try to load a page called wikiPage as shown in my urls description that follows, but I get another url patterns linking to a view called newPageb instead, though the two urls have same parameters and the one that is first in order gets called, But how do I make them distinct where I can call them irrespective of order. Here is my urls.py... app_name= "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("randomPage", views.randomPage, name="randomPage"), path("<str:pagetitle>", views.newPageb, name="newPageb"), path("<str:pagetitle>", views.wikiPage, name="wikiPage"), path("<str:z>", views.wikiPage, name="wikiPage"), path("newPage", views.newPage, name="newPage"), path("<str:pageSearch>", views.search, name="search"), path("", views.search, name="search") Here are the conflicting views.. def newPageb(request, pagetitle) ... ... def wikiPage(request, pagetitle): ... ... and here is the template where the pagetitle parameter was declared {% extends "encyclopedia/layout.html" %} " {% block title %} Encyclopedia {% endblock %} {% block body %} <h1> {{title}} </h1> <ul> {% for pagetitle in entries %} <li> <a href="{% url 'encyclopedia:wikiPage' pagetitle=pagetitle%}"> {{ pagetitle }} </a> </li> {{entrie|safe}} {% endfor %} </ul> {% endblock %} -
I'm trying to create vendor user API that has one-to-one relationship with the user it throws integrity error, pls help me
Integrity error in Django rest framework project. I am trying to register a vendor user, that has a one-to-one relationship with the user, but it throws an integrity error. The error code IntegrityError at /API/accounts/signup/vendor/ NOT NULL constraint failed: accounts_vendor.user_id Request Method: POST Request URL: ``http://127.0.0.1:8000/api/accounts/signup/vendor/ Django Version: 4.2.6 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: accounts_vendor.user_id Exception Location: C:\Users\Moses Ogiri\Desktop\medic-ecommerce\env\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute Raised during: accounts. views.VendorSignupView Python Executable: C:\Users\Moses Ogiri\Desktop\medic-ecommerce\env\Scripts\python.exe Python Version: 3.12.0 model.py class User(AbstractBaseUser, PermissionsMixin): ADMIN = 1 VENDOR = 2 HEALTHCARE = 3 LOGISTIC = 4 CUSTOMER = 5 ROLE_CHOICES = ( (ADMIN, 'Admin'), (VENDOR, 'Vendor'), (HEALTHCARE, 'Healthcare'), (LOGISTIC, 'Logistic'), (CUSTOMER, 'Customer'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4,editable=False, unique=True) first_name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], null=False) last_name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], null=False) email = models.EmailField(_('email address'), max_length=100, unique=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at= models.DateTimeField(auto_now=True) auth_provider = models.CharField(max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) objects = UserManager() REQUIRED_FIELDS = ["first_name", "last_name"] USERNAME_FIELD = 'email' ordering = ('-created_at ',) def __str__(self): return self.email @property def get_full_name(self): return f"{self.first_name.title()} {self.last_name.title()}" serializer.py class VendorSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) class Meta: model = Vendor fields = [ 'id', 'company_name', 'company_logo', 'company_files', 'company_email', … -
Has anyone seen this error before? ODBC Error code 0x68
My manager updated our test database data and ever since I've been getting this error ever since while trying to access our test system. We are currently making a python Django web application. Does anyone know why this would be happening? ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x68 (104) (SQLExecDirectW)') -
CommandError: errors happened while running msguniq
C:\Users\Boss\OneDrive\İş masası\ask>django-admin makemessages --locale 'en' --ignore=myenv/* CommandError: errors happened while running msguniq msguniq: error while opening "C:\Users\Boss\OneDrive\Is masasi\ask\locale\django.pot" for reading: No such file or directory in main folder: locale en LC_MESSAGES settings.py LANGUAGES = ( ('az', _('Azerbaijan')), ('en', _('English')), ) LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGE_CODE = 'az' MODELTRANSLATION_DEFAULT_LANGUAGE = 'az' TIME_ZONE = 'Asia/Baku' SITE_ID = 1 USE_I18N = True USE_TZ = True and i use gettext 0.21 and iconv 1.16 - Binaries for Windows in ubuntu server i can makemessages but in windows i only get error django.pot" for reading: No such file or directory,msguniq: error while opening in django project i try to py manage.py makemessages -l en -
I have the next error Reverse for 'solicitud_detail' with keyword arguments
I am trying to see the details of my created requests but the url to enter the details is not recognized. I don't know what it could be. I will attach the views of my code. If you can help me, please. html {% extends 'base.html' %} {% load static %} {% block content %} {% include 'nav.html' with active='new1' %} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous" /> <!-- DataTable.js --> <link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/dataTables.bootstrap5.min.css" /> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" /> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/index.css' %}" /> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css"> <br> <br> <div class="hstack gap-3"> <div class="p-2"><h3>Solicitudes </h3></div> <div class="p-2 ms-auto"></div> <div class="p-2"><a class="btn btn-primary btn-md" href="{% url 'crear_solicitud' %}">Crear OC</a> </div> </div> <br> <div class="container"> <table id="datatable-programmers" class="table table-hover"> <thead class="table table-primary"> <tr> <th>#</th> <th>Código</th> <th>Asunto</th> <th>Descripción</th> <th>Estado</th> <th>Plazo de Pago</th> <th></th> </tr> </thead> <tbody id="tableBody_programmers"> <!-- Los resultados se mostrarán aquí --> </tbody> <br> <br> </div> <!-- Bootstrap --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <!-- jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <!-- DataTable.js --> <script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.13.1/js/dataTables.bootstrap5.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> <script > let dataTable; let dataTableIsInitialized = false; const dataTableOptions = { columnDefs: [ { className: "centered", targets: [0, 1, 2, 3, 4, 5, … -
Django Database query optimization on filter() same QuerySet and assigning to different variables
I have a base queryset and the goal is to build a dashboard statistic using the base queryset but filtered by different values for each variable. My simplified code for better understanding: class Transaction(models.Model): """ Invoice model. Represents a basic income/outcome transaction. """ user = models.ForeignKey(CustomUser, related_name="transactions", on_delete=models.CASCADE) title = models.CharField(max_length=32, verbose_name="Title") category = models.ForeignKey(Category, related_name="transactions", on_delete=models.CASCADE, null=True, blank=True) operation = models.CharField(max_length=8, choices=OPERATION_TYPE, verbose_name="operation") value = models.DecimalField(max_digits=14, decimal_places=2, verbose_name="value") date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Category(MPTTModel): """ Category model. Represents a category where money have been spent/earned.""" name = models.CharField(max_length=54, unique=True) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='children') Having the models above I've created ClassBasedView(ListView) : class DashboardView(ListView): """ View implements dashboard functionality. """ model = Transaction template_name = "invoices/dashboard.html" ordering = "-date_created" def get_queryset(self) -> QuerySet[Any]: queryset = super().get_queryset() queryset = queryset.filter(user=self.request.user).select_related("category__parent") return queryset def get_context_data(self, **kwargs: Any) -> dict[str, Any]: data = super().get_context_data(**kwargs) # retrieving all transactons transactions_all = self.get_queryset() # retrieving incomes/expenses summary for current month incomes_this_month = transactions_all.filter(transaction_filter.transaction_date_filter(month="current"), operation="incomes") incomes_this_month_sum = incomes_this_month.aggregate(Sum("value")).get("value__sum") expenses_this_month = transactions_all.filter(transaction_filter.transaction_date_filter(month="current"), operation="expenses") expenses_this_month_sum = expenses_this_month.aggregate(Sum("value")).get("value__sum") # retrieving incomes/expenses summary for previous month transactions_prev_month = transactions_all.filter(transaction_filter.transaction_date_filter(month="previous")) incomes_previous_month = transactions_prev_month.filter(operation="incomes") incomes_previous_month_sum = incomes_previous_month.aggregate(Sum("value")).get("value__sum") expenses_previous_month = transactions_prev_month.filter(operation="expenses") expenses_previous_month_sum = expenses_previous_month.aggregate(Sum("value")).get("value__sum") You can see transaction_date_filter in … -
Django Sessions Login
in the following code section of my Django project, I have a function login_view. This function is supposed to log in a user. My question would be how I can use Django's sessions to start a separate session at each login: def login_view(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "users/login.html", { "message": "Invalid credentials" }) return render(request, "users/login.html") This is what i tried: def login_view(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: request.session['username'] = username request.session['password'] = password request.session['user'] = user login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "users/login.html", { "message": "Invalid credentials" }) return render(request, "users/login.html") -
Django - Is there a possibility to somehow combine multiple foreign keys into 1 field value from another model?
I want to create a model called DailyPerformance with following fields: class DailyPerformance(models.Model): date = models.DateField() driver = models.ForeignKey(Employee, on_delete=models.CASCADE) TYPE_OF_GOODS_CHOICES = ( ("Excavated soil", "Excavated soil"), ("Sand", "Sand"), ("Crushed stone", "Crushed stone"),... ) type_of_goods = models.CharField(blank=True, null=True, max_length=30, choices=TYPE_OF_GOODS_CHOICES) place_of_loading = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE) place_of_unloading = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE) number_of_rounds = models.IntegerField(blank=True, null=True) My biggest problem is with fields place_of_loading and place_of_unloading. Place of loading could be Construction site, Gravel pit, Sand pit, etc., while place of unloading could be Construction site or Landfill. Since I already have ConstructionSite model, I wanted to create models GravelPit, SandPit, Landfill and combine all of them in DailyPerformance model. This is the idea: Our drivers will need to fill the form at the end of working day, and I want for place_of_loading drop-down menu to have values from ConstructionSite, GravelPit and SandPit. The same goes for place_of_unloading. place_of_loading = models.ForeignKey(ConstructionSite, GravelPit, SandPit) place_of_unloading = models.ForeignKey(ConstructionSite, Landfill) I know this doesn't work, but wanted to know if there is any other solution. -
(Django 5.03] problem with django.contrib.auth.views.LogoutView
Today i am reviving an old django project. After creating all the needed things and importing the database, i could login and it worked (Or so i thought!) Everything works like it was when i abandoned the project a year or so ago, except the logout link in my header. I looked for people with similar problems and i found this: As per the Django 5.0 release notes, support for logging out via GET requests in the django.contrib.auth.views.LogoutView is removed. You must issue a POST in order to log out and be redirected. But that doesn't help me at all. I will show some of the code i use below: header.html <li class="nav-item "> <a class="nav-link " href="logout "> {{user.username.capitalize}} uitloggen</a> </li> views.py from django.contrib.auth.models import User, auth def logout(request): auth.logout(request) return redirect('/') urls.py from django.contrib.auth import views from members import views as member_views path('logout/', views.LogoutView.as_view(template_name='registration/logout.html'), name='logout'), logout.html {% extends 'index.html' %} {% block css %}<meta http-equiv="refresh" content="5;{% url 'index' %}">{% endblock %} {% block title %}Logout{% endblock title %} {% block content %} <div class="container bground2"> <div class="form"> <h2>You are logged out</h2> <h6>You will be redirected to the Home Page</h6> <div class="border-top pt-3 pb-5"> <small class="text-muted text-center"> Login again<a … -
Accessing the development server over HTTPS, but it only supports HTTP error in django rest framework
I implemented it and it seems to have given me a error(I currently do not have that exact error in my logs. It might even be same to the error I am currently encountering). I tried to reverse it. It didn't worked. I went to ChatGPT. It gave me some troubleshooting methods and some solutions. Nothing worked. Here is my settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'later' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'api', # api is my app name 'rest_framework', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.contenttypes', ] MIDDLEWARE = [ # 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'pythonRestApi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pythonRestApi.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # This is the code which was reversed. It was all set to True … -
I need assistance on how to get X-API-KEY in mtn API documentation for data sharing
I Am trying to make an automation software that can automatically share data and airtimes from my mtn line to my end users I tried using the mtn developer API and I got stuck at the X-API-KEy, I do not know how to go about that and if there's an alternative route to automate things I'm in Nigeria I will love to know. Thank you @api_view(['POST']) @permission_classes([AllowAny]) def datame(request): url = "https://api.mtn.com/v1/oauth/access_token?grant_type=client_credentials" payload = "client_id=sOO7K85Q9F5XKA5bxZ8zCQzESY3dluv2&client_secret=q0FLPsgZV2m6nhS7" headers = { 'Content-Type': "application/x-www-form-urlencoded" } token_response = requests.request("POST", url, data=payload, headers=headers) # get access token using get() method token = token_response.json().get('access_token') print(token_response.text) print('token: ', token) url = "https://api.mtn.com/v1/datashare/providers/2348131116906" payload = { "consumerMsisdn": "2348062596273", "threshold": "string", "unit": "string", "nodeId": "string", "input": "string", "paymentOption": "string", "targetSystem": "CIS", "operationType": "MAKE_UNLIMITED_ALL" } headers = { "Content-Type": "application/json", "transactionId": "1256", "X-API-Key": token } response = requests.request("POST", url, json=payload, headers=headers) print(response.text) return JsonResponse({"res":response.json()}) -
Django ForeignKey model not working with serializer
I am trying to build a django app that takes a record file as an uploaded file and then generates data for that record file and saves it to a local directory in the "server" local pc at the moment so for now i have this: models.py: class Sensor(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50) OwnerCompany = models.CharField(max_length=50) def __str__(self): return self.name class Bag(models.Model): name = models.CharField(max_length=255) sensor = models.ForeignKey("Sensor",on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) bag_file = models.FileField(upload_to="bag_files/") def __str__(self) -> str: return self.name views.py : class BagView(APIView): #to be changed to viewset parser_classes = [MultiPartParser] def get(self, request): bags = Bag.objects.all() serializer = BagSerializer(bags, many=True) return Response(serializer.data) def post(self, request): print(request.FILES,request.data) serializer = BagSerializer(data=request.data) if serializer.is_valid(): bag_upload = request.FILES['bag_upload'] if bag_upload: bag_name = os.path.basename(bag_upload.name) serializer.create(serializer.validated_data,bag_name) return Response({'message': 'Bag File Created and Data Extracted', 'data': serializer.data}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py : class SensorSerializer(serializers.ModelSerializer): class Meta: model = Sensor fields = "__all__" class BagSerializer(serializers.ModelSerializer): bag_upload = serializers.FileField(write_only=True) class Meta: model = Bag fields = ['id', 'sensor', 'date_created', 'bag_upload'] def create(self, validated_data,bag_name): print("HIIII") bag_upload = validated_data.pop('bag_upload', None) sensor_data = validated_data.pop('sensor', None) # Get 'sensor' data from validated data print(sensor_data) bag_name = bag_name # Check if 'sensor' data is provided if sensor_data is None: … -
Django-React not staying logged in
I have a React JS - Django site and I implemented the login functionality. But I have seen that the user does not stay logged in even though it authenticates and moves to the home page after log in. I tried displaying the username once it navigates to the home page and it returns empty. Views.py class Login(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') # Authenticate user user = authenticate(request, username=username, password=password) if user is not None: # If authentication succeeds, log in the user login(request, user) return JsonResponse({"message": "Login successful"}) else: # If authentication fails, return error response return JsonResponse({"error": "Invalid username or password"}, status=status.HTTP_400_BAD_REQUEST) Login.js const handleSubmit = async (e) => { e.preventDefault(); try { const response = await fetch("http://localhost:8000/login/", { method: 'POST', withCredentials: true, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); const data = await response.json(); if (response.ok && data.message === "Login successful") { // Redirect to the home page upon successful login navigate('/'); } else { // Set error state with the error message setError(data.error); } } catch (error) { // Handle network or server errors setError("An error occurred during login. Please try again later."); } I have the … -
Is there any way to optimize get_or_create() to make the program faster?
The functionality I want to achieve is to create a new class and import users. Since I don't want the same user to be imported multiple times and a user can join different classes, I have used get_or_create(). However, I have noticed that the program becomes slow when importing a large number of users at once (using CSV to import users). def post(self, request): class_data = request.data class_data["start_time"] = dateutil.parser.parse(class_data["start_time"]) class_data["end_time"] = dateutil.parser.parse(class_data["end_time"]) class_data["created_by"] = request.user if class_data["end_time"] <= class_data["start_time"]: return self.error("Start time must occur earlier than end time") user_data = class_data.pop("users") # Retrieve user data and remove it from the class data try: with transaction.atomic(): if Class.objects.filter(title=class_data["title"]).exists(): return self.error("Class with the same title already exists") class_obj = Class.objects.create(**class_data) # Create the class object # Add the creator to the class members if not class_obj.users.filter(id=request.user.id).exists(): class_obj.users.add(request.user) for data in user_data: if len(data) != 4 or len(data[1]) > 32: return self.error(f"Error occurred while processing data '{data}'") username = data[1] user, created = User.objects.get_or_create(username=username, defaults={ "password": make_password(data[1]), "college": data[3], "student_number": data[1] }) if created: profile = UserProfile(user=user, real_name=data[2]) profile.save() # class_obj.users.add(user) if not class_obj.users.filter(id=user.id).exists(): class_obj.users.add(user) return self.success(ClassAdminSerializer(class_obj).data) except IntegrityError as e: return self.error(str(e).split("\n")[1]) I have identified three areas that slow down the … -
Django drf-yasg API versions switch from drop down
Is there a way to show available API versions in drop down using drf_yasg without overwriting the template? I checked their docs but seems like i have to use versionized URL to see different version of API, or i can show all API version URLs on same page. But I want to have a drop down to show only selected version paths. -
Have to run python manage.py collectstatic everytime I make change in my static files to show the changes in Django
I am creating a Django application and right now it's in development phase. I am using Google Cloud Storage, so I have to change settings accordingly, but after that I have to always run python manage.py collectstatic to show the changes in css or js file, no matter how small they are. settings.py STATIC_URL = 'static/' DEBUG = True DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'videovogue' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' service_account_key_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") GS_CREDENTIALS = service_account.Credentials.from_service_account_file(service_account_key_path) What is going wrong? MAX_FILE_SIZE = 209715200 # 200 MB -
How can I authenticate a user based on correct/incorrect credentials, but ignore their "is_active" state if I want to handle it separately?
Currently with django's default auth.authenticate method, it will return None if the credentials are correct, but user.is_active is false. This means that users who have correctly entered their credentials will receive the same error message as users who have incorrectly entered their credentials. I am looking to provide users with an error message for an edge case when they've entered the correct credentials, but haven't activated their account via email verification and thus user.is_active=False. My question is how do I implement this safely and efficiently? views.py: ... from django.contrib.auth import authenticate class LoginView(View): def get(self, request): return render(request, 'accounts/login.html') def post(self, request): username = request.POST['username'] password = request.POST['password'] if username and password: user = auth.authenticate(username=username, password=password) if user: if user.is_active: auth.login(request, user) return redirect('accounts:home') else: uidb64 = Base64.get_uidb64(user) message = format_html("Please check your email for a verification link, or <a href='{}'>click here to request a new one.</a>", reverse('accounts:verify', kwargs={'uidb64':uidb64})) messages.error(request, message) else: messages.error(request, 'Invalid account credentials. Please try again.') return render(request, 'accounts/login.html') return render(request, 'accounts/login.html')