Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Only python file can read a specific file
For a High school projet, I have to use a private key to encrypt file. I changed permission to my pk, only the root user can read this file. I change the owner (to root) and put the uid right to this python file, but when I execute this python file, I can't have access to my pk, for me I have to change the right of python, but I didn't want, (problem of security). Do you have any idea to have access to a file only by a python file? The python file is included on a django project (view.py), I had too the idea to use the pid of the process but it didn't change my problem. I used chown root and chmod with 0777 on my view.py but it said that I can't have access to read this file (has the read for owner root). -
Is there a method for separating a logged in user from a super user in the views.py of a django based website?
I created a blog and users have to create an account to have access to make comment. My question is how do i make logged in users have a different access from to super user who can create a blog posts? I need a way to restrict general logged in users so they don't have similar access from the Super users.enter image description here I tried using using if user.is_superuser in one of the html pages i want to restrict but it is still not workingenter image description here -
How do I fix the scrollbar to always be at the bottom using tailwind css?
I have the following div with a list of divs. These child divs are going to be a message boxes of a chat box. <div class="overflow-auto"> </div> However, obviously I need the scoller to be at the bottom automatically whenever the user enters the page, because I want to show the latest conversation first. How am I able to do that? Thank you, and please leave any comments below. -
401 unauthorized response when doing user registration in Django rest framework using serializers and Api view
A bit of an update. Here is my serializers.py code: class SellerRegistrationSerializer(serializers.ModelSerializer): class Meta: model=Seller fields=['email','password','first_name','last_name','company_name','seller_desc','seller_image','seller_verification'] extra_kwargs={ 'password':{'write_only':True} } #def create should be done since this is a custom User model def create(self,validate_data): return Seller.objects.create_user(**validate_data) and In my views.py I have this code: from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } class SellerRegistrationView(APIView): # def post(self,request,format=None): serializer=SellerRegistrationSerializer(data=request.data) if serializer.is_valid(raise_exception=True): seller=serializer.save() token=get_tokens_for_user(seller) return JsonResponse(serilizer.data,status=status.HTTP_201_CREATED) return JsonResponse(serializer.errors,status=status.HTTP_400_BAD_REQUEST) class SellerLoginView(APIView): def post(self,request,format=None): serializer=SellerLoginSerializer(data=request.data) if serializer.is_valid(raise_exception=True): email=serializer.data.get('email') password=serializer.data.get('password') seller=authenticate_seller.authenticate(request,email=email,password=password) #where i use custom authenticator that uses email of the user and not username if seller is not None: token=get_tokens_for_user(seller) return JsonResponse({'token':str(token)},status=status.HTTP_200_OK) else: return JsonResponse({'errors':{'non_field_errors':['Email or password is not valid']}}, status=status.HTTP_404_NOT_FOUND) #when serializer sends an error, it can send non_field_errors as one of the error response but in frontend we catch that error as errors to get all the errors. so to also obtain the non_field_error, we send it inside errors as an object that we will probably jsonify return JsonResponse(serializer.errors,status=status.HTTP_400_BAD_REQUEST) now with this url:path('sregister/',SellerRegistrationView.as_view(),name='sregister'), when i make the request using thunder client i get this as a response: { "detail": "Authentication credentials were not provided." } with a 401 status . I don't know why this … -
In Django, how to use split() to split a string of dropdown items?
trips in the def trips function returns something like x-y (so team_home-team_away). trips is showing correctly in the second dropdown. I want to separate x and y, creating two variables: x will be variable a, and y will be variable b. will be I tried this, but it doesn't work: a,b = trips.split('-') I don't know if a,b = trips.split('-') is correct in setting up your code. My goal is to select the item in the combobox, then click on the button which starts the def test1 function and displays the text in the textarea (def result). Should I use the split code in the def trips function or elsewhere? Or do I have to create a new function? The render of the split in which HTML page should it be? (in trips.html which is the dropdown or in result.html which is the textarea?) Can you show me how I can fix it? views.py from django.shortcuts import render from .models import Full_Record import random def trip_selector(request): campionati = Full_Record.objects.values(pk=F('campionato__id'), name=F('campionato__name')).distinct() trips = [] return render(request, 'form.html', {'campionati': campionati, 'trips': trips}) def trips(request): if request.GET.get("campionato"): campionato = request.GET.get('campionato') trips = Full_Record.objects.filter(campionato=campionato) elif request.GET.get("trips"): selected_trip_id = int(request.GET.get('trips')) selected_trip = Full_Record.objects.get(id=selected_trip_id) request.session.update({"selected_trip_id": selected_trip_id}) … -
can we build the cordova android application with django as backend and Mysql as database
I am trying to build the cordova application by using django as backend but I do not know how to do that if anyone have been working on that please guide me to build the cordova applcation with the django as backend if anyone having solution that how I can connect the django default server to my cordova app -
Access GAID in Django
Is it possible to retrieve GAID in a Django server? Here is my scenario: I want to create a unique link in my Django project and send it to a user (it's a referral link). When the user click the link it will redirect to my server so then I can log its click and then user will redirect to an app store to download my app. Is it possible for me to get its GAID before installing the app, right after clicking the link? If yes so, then how? I searched already couldn't find anything helpful. I appreciate if anyone can offer me a documentation or something like that. -
Not getting a django's right capture group when url has a "."
I have a url http://localhost/fault/docs/testing/pipelines/dot.filetesting which should return a default html page ie index.html urls.py looks like- re_path(r'(?P<resource>.*)$', csrf_exempt(views.get_docs_from_s3), name='read_docs') view.py - ` @require_GET def get_docs_from_s3(request, resource): mime_type, _ = mimetypes.guess_type(resource) # if not Path(resource).suffix: # resource = resource.rstrip("/") + "/index.html" try: page = get_page_from_s3(resource) return HttpResponse(page, content_type=mime_type or "text/html") except Exception as e: return HttpResponse("Not found", content_type=mime_type or "text/html")` nginx conf - ` location /fault { add_header X-Cache $upstream_cache_status; rewrite ^([^.]*[^/])$ $1 permanent; proxy_set_header Host localhost:8000; proxy_pass http://localhost:8000/bug; proxy_connect_timeout 30s; proxy_read_timeout 86400s; proxy_send_timeout 30s; proxy_http_version 1.1; }` Question for a url like http://localhost/fault/docs/testing/pipelines/normal I am able to render html page since the resource in my views = docs/testing/pipelines/normal/index.html but for urls that have "." in them like mentioned above I don't get index.html appended. Note-> In the code I do not want to add /index.html in my views.py for that doesn't have, if its able to be resolved at nginx and django urls leveel -
Need advice. Forbidden (403) CSRF verification failed. Request aborted. Django error
I am making a website with django and when i login and go back then try to login again i get this error message. Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token from POST incorrect. When i login first it works okay, and after i get the error i go back and the login is successful again. I was just wondering what the problem is with my code. This is the views.py `@csrf_protect def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password ) if user is not None: auth_login(request, user) return redirect('homepage') else: messages.error(request, 'Username OR password is incorrect') context = {} return render(request, 'login.html', context)` This is my settings.py `MIDDLEWARE = [ 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ` This is my login.html `<form method="POST" action=" " > {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> <input type="text" name="username" class="form-control input_user" value="" placeholder="Username"> </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> <input type="password" name="password" class="form-control input_pass" value="" placeholder="Password"> </div> <div class="form-group"> <div class="custom-control custom-checkbox"> </div> </div> <div> {% for message in messages %} <p id="messages">{{message}}</p> {%endfor%} … -
Heroku Django remote: Is the server running locally and accepting connections on that socket? heroku django
So Ive been trying to run my django application on heroku, it works locally fine with the database, so its some issue within my base.py that I havent been yet able to identify. If anyone has encountered a similar problem and have a solution, Ive been looking around for a while no hints :( error message: remote: Verifying deploy... done. remote: Running release command... remote: remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection remote: self.connect() remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner remote: return func(*args, **kwargs) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect remote: self.connection = self.get_new_connection(conn_params) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner remote: return func(*args, **kwargs) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection remote: connection = self.Database.connect(**conn_params) remote: File "/app/.heroku/python/lib/python3.10/site-packages/psycopg2/init.py", line 122, in connect remote: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) remote: psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory remote: Is the server running locally and accepting connections on that socket? base.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the … -
datetime field in django is being displayed differently in the template and not like the saved one in database
The following is a part of my ajax request in my django template <span class='time-left'>${response.chats[key].date}</span></div>`; This is the model field it is refering to... date = models.DateTimeField(auto_now_add=True, null=True, blank=True) Now this is the problem. The datetime is saved correctly in the database to my current timezone. However, when I display it in the template like above, I get a different time for some reason. the USE_TZ=True in my settings, and I don't want to change it. Do you know how I could show the saved value in the database in the template as well? -
Getting "AttributeError: 'ProfileSerializer' object has no attribute '_meta'" when trying to update a model object
In my django project, I'm trying to update a Profile object using patch request. When the code gets to ".save()" method, I'm getting "AttributeError: 'ProfileSerializer' object has no attribute '_meta'". Please try to explain the problem to me rather than only giving me the solution. This is my Model: class Profile(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, related_name='profile') avatar = models.ImageField(upload_to="avatars/", null=True, blank=True) bio = models.TextField(max_length=500, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.user.name This is my ProfileSerializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' This is my view: @api_view(['PATCH']) @permission_classes([IsAuthenticated]) def edit_profile(request, user_id): user = request.user if not user.id == user_id: return Response({"message": "You can't edit other's profiles."}, status=status.HTTP_401_UNAUTHORIZED) profile = Profile.objects.get(user=user) serializered_prof = ProfileSerializer(profile) update_prof = ProfileSerializer(serializered_prof, request.data, partial=True) update_prof.is_valid(raise_exception=True) update_prof.save() return Response({'message': 'profile Updated.'}) I dont know why this error is raised. -
Django redirect with corrected optional url params
I am trying to implement stackoverflow's url redirection using django / django rest framework, for example. Say this url - https://stackoverflow.com/questions/3209906/django-return-redirect-with-parameters As long as the question pk (3209906) is correct, stackov will automatically correct the slug (django-return-redirect-with-parameters), even if you pass an incorrect slug. My current code views.py from django.db import models class ArticleBody(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField() def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) return super().save(*args, **kwargs) serializers.py from rest_framework import serializers class ArticleSerializer(serializers.ModelSerializer): class Meta: model = ArticleBody read_only_fields = ( "id", "title" "slug" ) fields = read_only_fields views.py from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .models import ArticleBody from .serializers import ArticleSerializer class ArticleView(APIView): def get(self, request, pk, slug=None): article_obj = ArticleBody.objects.filter(id=pk).last() article = ArticleSerializer(article_obj).data if article: return Response({"article": article}) return Response( {"message": "Article not found"}, status=status.HTTP_404_NOT_FOUND ) urls.py from django.urls import path, re_path from .views import ArticleView app_name = "article" urlpatterns = [ re_path(r"^(?P<pk>\d+)/$", ArticleView.as_view(), name="body"), re_path( r"^(?P<pk>\d+)/(?P<slug>[-\w]+)/$", ArticleView.as_view(), name="body-slug" ), ] Currently this code properly handles valid or invalid slugs. such as http://127.0.0.1:8000/article/1/ http://127.0.0.1:8000/article/1/article-name/ http://127.0.0.1:8000/article/1/artic/ (incorrect slug) Basically I am looking for a way to redirect all of these urls to http://127.0.0.1:8000/article/1/article-name/ -
django-multi-captcha-admin permission denied
I have a Django project up and running. I followed required steps for django-recaptcha and even used captcha v2 in my template. my problem is with the admin site captcha requiring. I tried to use django-multi-captcha-admin package. I followed the documentation steps (this is the documentation) but the problem is when I try to login as admin I see this error: The admin page picture You don’t have permission to view or edit anything. I searched and I didn't find anything on the internet so I asked ChatGPT and this was its answer: Make sure that the middleware of multi_captcha_admin is placed correctly in the MIDDLEWARE list, following the AuthenticationMiddleware: MIDDLEWARE = [ # ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'multi_captcha_admin.middleware.MultiCaptchaAdminMiddleware', # ... ] The new problem with this solution is when I add this part to my MIDDLEWARE I get this error trying to run server: ModuleNotFoundError: No module named 'multi_captcha_admin.middleware' django.core.exceptions.ImproperlyConfigured: WSGI application 'haadijafari.wsgi.application' could not be loaded; Error importing module. -
Trying to find the most efficient way of implementing bingo-guessing game
I'm working on creating a bingo-like quiz game to improve my Django skills. The game begins with a 3x3 grid, with each cell containing a requirement. Some items can fulfill multiple requirements, leading to their placement in multiple cells. Each cell is associated with a list of valid guesses. My goal is to determine the minimum number of guesses needed to fill the entire board. For instance: Cell 1 Cell 2 Cell 3 Cell 4 Cell 5 Cell 6 Alfa Delta Golf Juliett Quebec Sierra Bravo Echo Hotel Kilo Romeo Victor Charlie Foxtrot India Lima Sierra Whiskey Delta November Lima Mike Tango Xray November Whiskey Delta Zulu Bravo Yankee Whiskey Hotel November Oscar Delta Zulu Sierra Sierra Zulu Papa Whiskey Bravo In my initial approach, I aimed to identify the most frequently repeated guesses and then eliminate the associated column. However, I encountered difficulties when dealing with ties, triple ties, and ties for the second most repeated guesses. Although I'm implementing this in Django, I haven't included the model code here as I'm focused on understanding the underlying logic before coding it. I've already experimented with various strategies, including using AI, but the results were either extremely inefficient or failed … -
How to configure nginx to serve multi-tenant django application
I would like to deploy a django application with the django-tenants library. The project works fine locally, I can create tenants and access them via localhost:8000 Now I am trying to deploy the application on DigitalOcean using docker-compose and I have an issue with configuring the nginx server. As the log suggests I am able to start the gunicorn server on 0.0.0.0:8000 but the proxy can only reach the application like this: wget <DOMAIN>:8000 but not like this: wget <CONTAINER_NAME>:8000 (the container name in the docker-compose yml is 'web') The http response is 504 - Gateway Time-out Here is my NGINX config: server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name .<DOMAIN>; set $base /etc/nginx/sites-available/trackeree.com; # SSL ssl_certificate /etc/letsencrypt/live/trackeree.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/trackeree.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/trackeree.com/chain.pem; # security include /etc/nginx/security.conf; # logging access_log /var/log/nginx/access.log combined buffer=512k flush=1m; error_log /var/log/nginx/error.log warn; location / { uwsgi_pass web:8000; include /etc/nginx/uwsgi.conf; } # Django media location /media/ { alias $base/media/; } # Django static location /static/ { alias $base/static/; } # additional config include /etc/nginx/general.conf; } # non-www, subdomains redirect server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name www.<DOMAIN>; # SSL ssl_certificate /etc/letsencrypt/live/trackeree.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/trackeree.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/trackeree.com/chain.pem; return 301 https://trackeree.com$request_uri; } # … -
Trying to install pip dependencies from a bash script
Trying the create setup.sh script file in my current Django project's root directory. Don't have too much experience with bash scripting , so to be honest from file access to configuration the issue can be anything. So what I'm trying to run looks like this: setupBackend() { echo "--------------------------- Creating virtual environment ----------------------" pip install --upgrade pip pip install virtualenv virtualenv venv source ./venv/Scripts/active echo "----------------------- Installing dependencies ------------------------------" pip install -r requirements.txt echo "----------------------- Running Django server -------------------------" python ./kudelasz/manage.py runserver } And I have this requirements file containing the dependencies asgiref==3.7.2 colorama==0.4.6 distlib==0.3.6 Django==4.2.2 django-tailwind==3.6.0 djangorestframework==3.14.0 djangorestframework-jsonapi==6.0.0 filelock==3.12.2 inflection==0.5.1 mysqlclient==2.2.0 platformdirs==3.7.0 PyMySQL==1.1.0 PyPDF2==3.0.1 pytz==2023.3 sqlparse==0.4.4 termcolor==2.3.0 tzdata==2023.3 virtualenv==20.23.1 The probalem I'm facing is, that when the script runs the pip installation, it seems to be trying to install all these stuffs to the global python environment. At least that's what I'm assuming, because it tell me this: "Requirement already satisfied: asgiref==3.7.2 in c:\users\customer\appdata\local\programs\python\python311\lib\site-packages (from -r requirements.txt (line 1)) (3.7.2)" at each package installation attempt. I can also see in my venv directory that none of those packages get installed, only the default pip dependencies can be seen. In the end the installation fails due dependency conflicts. For now … -
Cant add image and media files from database on production mode Django Cpanel
i have a website based Django mysql and my problem is when i want to add mediafiles(images and etc) from database in django admin panel , idk why but its doesnt work and its doesn`t show me any error! just 10 second wait and after that it whows me this : This site can’t be reached im using Cpanel and my code in setting is : for url : + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) setting : MEDIA_URL = "media/" MEDIA_ROOT = "/home/samaliz1/public_html/media" STATIC_ROOT = "/home/samaliz1/public_html/static" and model: prof_pic = models.ImageField(upload_to="img/prof_pics", null=True, blank=True) i should say that my staticfiles working perfectly but idk why my media doesnt i will be so thankfull if u guys help me <3 -
Change the default route from / to /docuseal/
I don’t know if it’s the good section but my problem is the following one : In my VM, I have a django server running with gunicorn and nginx and I would like to add a docuseal entity running with ruby on rails on the website (docuseal is also running with nginx). In fact, I figure out how to make my nginx configuration. So I can access docuseal by the url mydomaine/docuseal/, all the other are manage by django. However, all the route in my docuseal app start with ‘/’, but as I say, it’s django part. So I would like to “shift” all the docuseal routes from “/…” to “/docuseal/…”. I tried to make change in config/routes.rb but I didn’t succeed. Can somebody help me please. Thanks you ! -
Django template regroup - unable to print unique data
I want to print the data in my template in the following format Date 1-> Event ID 1a --> Table showing data for that date and event Event ID 2b --> Table showing data for that date and event Date 2-> Event ID 2a --> Table showing data for that date and event Event ID 2b --> Table showing data for that date and event Views.py #some code source_metadata=MetadataTable.objects.filter(sync_id=sync_detail.id) synclogs = SyncLog.objects.filter(sync_id=sync_detail.id) logs_by_date = {} sync_logs = SyncLog.objects.filter(sync_id=sync_detail.id).order_by('-date_added') # Replace with your desired ordering for log in sync_logs: date = log.date_added.date() if date not in logs_by_date: logs_by_date[date] = [] logs_by_date[date].append(log) And templates.py div class="container"> {% for date, logs in logs_by_date.items %} <div class="card"> <div class="card-header"> <a href="#" class="date-link" data-toggle="collapse" data-target="#collapse-{{ date|date:'mdy' }}">{{ date |date:"m/d/y" }}</a> </div> <div id="collapse-{{ date|date:'mdy' }}" class="collapse"> <div class="card-body"> {% with last_event_id=None %} {% for log in logs %} {% if forloop.first or log.sync_event_id != last_event_id %} {% with last_event_id=log.sync_event_id %} <div class="card event-card"> <div class="card-header"> <a href="#" class="event-link" data-toggle="collapse" data-target="#event-collapse-{{ date|date:'mdy' }}-{{ log.sync_event_id }}">Event {{ log.sync_event_id }}</a> </div> <div id="event-collapse-{{ date|date:'mdy' }}-{{ log.sync_event_id }}" class="collapse"> <div class="card-body"> <!-- Display the SyncLog records for the selected date and event in a table --> <table class="table table-nowrap … -
No module named 'attachments.wsgi' in render
I am trying to upload my django project to render but I am finding this error No module found on 'attachment.wsgi' enter image description here I tried to publish the site. Tried to change the wsgi page but no success please help me solve this error or how should the wsgi page be like? -
How do i download and uploaded file in django database?
i have three different files on my database and they belong to users, like each user uploads three different files and they all have a "reg no" as a unique number and i want to download those files base on their "reg no". i will appreciate new code snippet my views.py def download_file(request, regno): regno = request.session.get('reg_no_admin') file = CacAdmin.objects.get(regNo=regno) response = FileResponse(open(file.filePath, 'rb')) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = f'attachment; filename="{file.fileName}"' return response urls.py path('private/download-file/<int:regno>/', views.download_file, name="download_file"), html <a href="{% url 'download_file' file.regNo %}">Download File</a> -
How to make jwt check global
I am adding authoraziation with jwt in react for frontend and django for the backend. When an access token expires I refresh it using axios interceptors. If the refresh token expires then the user logs out. I store the tokens in localStorage and to log out the user I just delete them. useAxios.js .... axiosInstance.interceptors.request.use(async req => { const user = jwt_decode(authTokens.access) const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 1; console.log(isExpired) if(!isExpired) return req const response = await axios.post(`${baseURL}/token/refresh/`, { refresh: authTokens.refresh }).catch(err=>localStorage.clear()) localStorage.setItem('authTokens', JSON.stringify(response.data)) setAuthTokens(response.data) setUser(jwt_decode(response.data.access)) req.headers.Authorization = `Bearer ${response.data.access}` return req }) I have also a file called AuthContext.js where the function to login the user is and where the tokens are made. Home.js ... let api = useAxios() let getUser = async () => { let response = await api.get('http://127.0.0.1:8000/a/') console.log(response.data) if (response.status === 200) { console.log(response.data) } } useEffect(()=>{ console.log('hey') getUser() },[]) ... So basically when the user enters the home page I am sending a request in django where you need to be authenticated to have access. So if the user's refresh token has expired then I log him out. The problem is that I don't want to write the getUser function for every single page to … -
HI i have two models called Category and item and each item has a category please how can i display all the items that are in the same category [closed]
MY MODELS.PY enter image description here MY VIEWS.PY enter image description here MY URLS.PY enter image description here .............................................................................................................................................................................................. ERROR I AM GETTING enter image description here -
User registration was working fine few days ago. Now i get 401 unauthorized response when i try to register in thunder client. am a beginner
I am making a shopify inspired django project using restframework. in my project, I have two types of users, one is the default User model and another is custom user model 'Seller'. Here is the code for the model class SellerUserManager(BaseUserManager): def create_user(self,email,password=None,**extra_fields): email=self.normalize_email(email) user=self.model(email=email,**extra_fields) user.set_password(password) extra_fields.setdefault('is_staff',True) #is_staff will let the user made here to have some admin accesses user.save() return user def create_superuser(self,email,password=None,**extra_fields): # this is a bit unnecessary as seller wont be allowed to acess the administration extra_fields.setdefault('is_superuser',True) return self.create_user(email,password,**extra_fields) # Since sellers would be different types of users they are custom users inherited from abstractbaseuser class Seller(AbstractBaseUser,PermissionsMixin): email=models.EmailField(unique=True,max_length=255,) # i don't have to create a passeord field as it is automatically inherited from abstractuser first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) is_active=models.BooleanField(default=True) is_staff=models.BooleanField(default=False) company_name=models.CharField(max_length=100) seller_desc=models.TextField() seller_image=models.FileField(upload_to='seller/sellerImage',null=True) seller_verification=models.FileField(upload_to='seller/sellerVerification',null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateField(auto_now=True) status=models.BooleanField(default=False,null=True) #verification status objects=SellerUserManager() USERNAME_FIELD='email' #this makes it so that email is used as a unique identifier and not username EMAIL_FIELD='email' REQUIRED_FIELDS=[] # some errors that was solved by chat gpt that said to do these. groups = models.ManyToManyField('auth.Group', related_name='seller_users') user_permissions = models.ManyToManyField('auth.Permission', related_name='seller_users') def __str__(self): return self.email Here is my serializers.py code: class SellerRegistrationSerializer(serializers.ModelSerializer): class Meta: model=Seller fields=['email','password','first_name','last_name','company_name','seller_desc','seller_image','seller_verification'] extra_kwargs={ 'password':{'write_only':True} } #def create should be done since this is a custom User …