Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The 'poster' attribute does not have a file associated with it"
the following error occurs "The 'poster' attribute does not have a file associated with it" I don't quite understand what it may be related to and how to fix it I tried to change the url value, but nothing worked. I'm new to django. Please help html <div class="container" style="grid-template-columns: repeat(auto-fill, 300px);"> for serial in serials %} <div class="item"> <img src="{{ serial.poster.url }}" class="img-fluid" alt=""> <p> <a href="{% url 'detail_serial' serial.url %}">{{ serial.title }}</a> </p> </div> endfor %} </div> views.py class SerialDetailView(View): def get(self, request): serials = Serials.objects.all() genres = Genre.objects.all() return render(request, "serials/single_serial.html", {"serials": serials, "genres": genres}) urls.py urlpatterns = [ path('register/', views.Register.as_view(), name='register'), path('reg/', views.Reg.as_view(), name='reg'), path("serials_list/", views.SerialsView.as_view(), name='serials_list'), path("add/", views.AddView.as_view(), name='add'), path("single_serial/", views.SerialDetailView.as_view(), name='single_serial'), path("<slug:slug>/", views.SingleSerial.as_view(), name='detail_serial'), path("actor/<int:id>/", views.ActorView.as_view(), name='actor_detail'), ] -
multiple instances of django using 1 celery
I'm using Django as webserver, and redis as broker. I have 3 virtual machines running the same Django app and load balance among them and 1 redis server shared between them. Problem we are facing now is that if we run workers and scheduler on each machine then if we run task_1 on machine 1 then all machines run it 1 time.(total of 3 times.) if we turn off the worker and scheduler on 2 of the machines ( let's say 2 , 3). and then run task_1 on machine 1 everything is okay. but if we run it on machine 2 or 3 nothing happens. my plan is to change celery broker url on each machine and change database so instead of redis://host:port on all of them it would be redis://host:port/1 redis://host:port/2 redis://host:port/3 I wanted to know if this is the right way to go or is there another general solution which only requires 1 machine with celery running on it? -
Updating templates in django app without re-rendering the pages
I'm making a Django web application in python, similar to language learning quiz. It consists of three different parts. One is showing the set of sentences to a user (one element per page) and the second is asking questions about sentences that was just shown. The third one is showing results and asking for redo the wrong q/a. Each part has next/prev buttons for iteration and the content of the sentence. I also need to store info to DB when the user answers the question right to not to show it again. The set of questions is provided by a view function through filtering the models objects. I need to have these 3 stages without page rendering. I face the following problem: The list of questions is passed to the template to iterate over it once to present sentences, then I need to start the loop again with the only difference of adding a field of textarea for answer and a few buttons. What is the best way to do it? I was thinking about some ajax function that'll be triggered after the first loop is finished. This js function can refill the certain tags with textarea and buttons. But … -
i have issues in my schedule school when trying to accommodate with days and hours in my schedule school (django)
This is my modle to create a school class. class Semestre(models.Model): WEEK_DAY = ( ('Lunes', 'Lunes'), ('Martes', 'Martes'), ('Miercoles', 'Miercoles'), ('Jueves', 'Jueves'), ('Viernes', 'Viernes'), ('Sabado', 'Sabado') ) semestre = models.CharField(max_length=1) licenciatura = models.ForeignKey(Licenciatura,null=False,on_delete=models.CASCADE) ciclo = models.CharField(max_length=5,null=False) week_day = MultiSelectField(max_length=2000,choices=WEEK_DAY,max_choices=6) start_time = models.PositiveBigIntegerField(null=True) end_time = models.PositiveBigIntegerField(null=True) history = HistoricalRecords() class Meta: db_table = 'institucion_semestre' def __str__(self): template = 'Semestre {0.semestre} de {0.licenciatura} ciclo {0.ciclo}' return template.format(self) This is a techer model when choose a course class DocenteMateria(models.Model): materia = models.ForeignKey(Page,null=False,on_delete=models.CASCADE,related_name='matdoce') docente = models.ForeignKey(Docente,null=False,on_delete=models.CASCADE,related_name='docedoce') clase = models.ForeignKey(Semestre,null=False,on_delete=models.CASCADE) start_time = models.PositiveBigIntegerField(null=False) end_time = models.PositiveBigIntegerField(null=False) dia = models.CharField(max_length=10,null=False) history = HistoricalRecords() class Meta: db_table = 'pages_docenteMateria' def __str__(self): template = '{0.materia} {0.docente}' return template.format(self) And this is my view to create a schedule class def TimeTableView(request,id): try: section = Semestre.objects.get(id=id) docema = DocenteMateria.objects.select_related('materia','docente','clase').filter(clase_id=section.id) results = DocenteMateria.objects.raw('SELECT * from pages_docenteMateria GROUP BY dia') admin = Admin.objects.all() coordina = Coordina.objects.all() docente = Docente.objects.all() pages = Page.objects.all() disponi = Disponibilidad.objects.all() matedo = DocenteMateria.objects.all() print(docema.query) print(results.query) time = [0] * (section.end_time - section.start_time) time_slot = [''] * (section.end_time - section.start_time) for x in range(0, len(time)): time_slot[x] = str(section.start_time + x) + ':00 - ' + str(section.start_time + x + 1) + ':00' time[x] = section.start_time + x context_1 … -
django super user premissions
i want to add if user is super user show companies and add company anyone can help with what should add in class to do it this is class code just showing in tepmalte page all comapany and add new company not working views.py class Companies(LoginRequiredMixin, FormView, ListView): """ Company add edit delete view """ model = Company template_name = 'company/index.html' form_class = AddCompanyForm success_url = reverse_lazy('companies:index') object_list = Company.objects.all() def form_valid(self, form): user, created = User.objects.get_or_create(username=form.cleaned_data['username'], email=form.cleaned_data['email']) user.set_password(form.cleaned_data['password']) user.save() if created: address = Address(label=form.cleaned_data['label'], city=form.cleaned_data['city'], area=form.cleaned_data['area'], long=form.cleaned_data['longitude'], lat=form.cleaned_data['latitude'], country=form.cleaned_data['country']) address.save() company = Company(owner=user, name=form.cleaned_data['name'], phone_number=form.cleaned_data['phone_number'], logo=form.cleaned_data['logo'], address=address, water_source=form.cleaned_data['water_source']) company.save() return super().form_valid(form) form.py ` class AddCompanyForm(forms.ModelForm): """ Add company model form """ name = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput()) logo = forms.ImageField(required=False) phone_number = forms.CharField(widget=forms.NumberInput()) label = forms.CharField(max_length=20) country = forms.ModelChoiceField(queryset=Country.objects.all()) city = forms.ModelChoiceField(queryset=City.objects.all()) area = forms.ModelChoiceField(queryset=Area.objects.all()) latitude = forms.CharField(max_length=50, required=False) longitude = forms.CharField(max_length=50, required=False) water_source = forms.ModelChoiceField(queryset=WaterSource.objects.all()) class Meta: model = User fields = ['name', 'username', 'email', 'password'] def __init__(self, *args, **kwargs): super(AddCompanyForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.layout = Layout(Row(Column('name', css_class='form-group col-md-6 mb-0'), Column('username', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('email', css_class='form-group col-md-6 mb-0'), Column('password', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('phone_number', css_class='form-group col-md-6 mb-0'), Column('logo', css_class='form-group col-md-6 mb-0'), css_class='form-row'), … -
Using Django Rest Framework, how can I capture values from an URL to a viewset using routers, not with URLconf?
I have two models: the first is named Card and has a foreign key (named owner) to the second model (User). I'm trying to write a view that lists all the Cards owned by a User, the client selects the User by changing the URL (not query parameters). For example, if I make a GET request to /cards/by-user-id/42/, I should get all the Cards owned by the User whose id is 42. From what I understood, it is possible to achieve this by using an URL pattern like this : path('cards/by-user-id/<int:user_id>', my_view.as_view()) and then in the viewset I can use self.kwargs['user_id'] to get the id and then filter the data. However, I can't find how to do it using routers (more appropriated for djangorestframework). I tried with <int:user_id> in the prefix but it does not pick it up, it just considers it as a normal string, so not only the URL is incorrect (I have to type literally /cards/by-user-id/<int:user_id>/) but also kwargs doesn't contain 'user_id'. Here is what I tried: models.py: from django.contrib.auth.models import User from django.db import models class Card(models.Model): owner = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) serializers.py: from rest_framework import serializers from . import models class CardSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField() … -
I want to enable or disable fields for some users from admin panel
This is template <div class="container mt-3"> <h5 class="card-title">Kindly enter the details. All details are required</h5> <form class="row g-3" method="post" action="{% url 'home' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="col-md-4"> <label for="name" class="form-label">Full Name</label> <input type="text" class="form-control" id="name" name="name" required> </div> <div class="col-md-4"> <label for="parentage" class="form-label">Father's Name</label> <input type="text" class="form-control" id="parentage" name="father" required > </div> <div class="col-md-4"> <label for="mothername" class="form-label">Mother's Name</label> <input type="text" class="form-control" id="mothername" name="mother" required> </div> <div class="col-md-4"> <label for="phonenumber" class="form-label">Phone number</label> <input type="tel" class="form-control" id="phonenumber" name="pnumber" required> </div> <div class="col-md-4"> <label for="ephonenumber" class="form-label">Emergency contact number</label> <input type="tel" class="form-control" id="ephonenumber" name="enumber" required> </div> <div class="col-md-4"> <label for="dob" class="form-label">Date of Birth</label> <input type="date" class="form-control" id="dob" name="dob" required> </div> <div class="col-12"> <label for="inputAddress" class="form-label">Address</label> <input type="text" class="form-control" id="inputAddress" placeholder="" name="address" required> </div> <div class="col-md-6"> <label for="photo" class="form-label">Upload a photo</label> <input type="file" class="form-control" id="photo" name="photo" accept="image/*,.pdf" required> </div> <div class="col-md-4"> <label for="schoolname" class="form-label">School Name</label> <input type="text" class="form-control" id="schoolname" name="sname" required > </div> <div class="col-md-4"> <label for="inputState" class="form-label">Role</label> <select id="select" class="form-select" name="role" required> <option selected>Choose...</option> <option value="student">Student</option> <option value="teacher">Teacher</option> </select> </div> <div id="show"> </div> <div class="col-12"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> This is models.py class Student(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True) fullname= models.CharField(max_length=50) father = models.CharField(max_length=30) mother = models.CharField(max_length=30) phno=models.IntegerField() ephno = models.IntegerField() … -
ModuleNotFoundError when importing into database in django python
I have a file that is trying to populate the database. However it shows modulenotfounderror error message directory The error is pointing to the below code. error area settings.py have included the app config settings.py I am not sure what else is the problem. Help please. -
Django Login/Logout Logger
I have a django project where I need to know how much time each user spends on the site. The first thing that came to my mind was that since I have a CustomUser I can create my own login/logout view and populate a table with login and logout and the user's identifier. However, I wanted to know if there is a callback function for django.contrib.auth.urls. So I can use the default login form? -
GeocoderUnavailable at /
from django.shortcuts import render, get_object_or_404 from .models import Measurement from .forms import MeasurementModelForm from geopy.geocoders import Nominatim from geopy.distance import geodesic from .utils import get_geo, get_center_coordinates, get_zoom import folium Create your views here. def calculate_distance_view(request): # initial values distance = None destination = None obj = get_object_or_404(Measurement, id=1) form = MeasurementModelForm(request.POST or None) geolocator = Nominatim(user_agent='measurements') ip = '72.14.207.99' country, city, lat, lon = get_geo(ip) location = geolocator.geocode(city) # location coordinates l_lat = lat l_lon = lon pointA = (l_lat, l_lon) # initial folium map m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon), zoom_start=8) # location marker folium.Marker(\[l_lat, l_lon\], tooltip='click here for more', popup=city\['city'\], icon=folium.Icon(color='purple')).add_to(m) if form.is_valid(): instance = form.save(commit=False) destination\_ = form.cleaned_data.get('destination') destination = geolocator.geocode(destination\_) # destination coordinates d_lat = destination.latitude d_lon = destination.longitude pointB = (d_lat, d_lon) # distance calculation distance = round(geodesic(pointA, pointB).km, 2) # folium map modification m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon, d_lat, d_lon), zoom_start=get_zoom(distance)) # location marker folium.Marker(\[l_lat, l_lon\], tooltip='click here for more', popup=city\['city'\], icon=folium.Icon(color='purple')).add_to(m) # destination marker folium.Marker(\[d_lat, d_lon\], tooltip='click here for more', popup=destination, icon=folium.Icon(color='red', icon='cloud')).add_to(m) # draw the line between location and destination line = folium.PolyLine(locations=\[pointA, pointB\], weight=5, color='blue') m.add_child(line) instance.location = location instance.distance = distance instance.save() m = m.\_repr_html\_() context = { 'distance' … -
All static files returning 404 error when deploying Django Project using Digital Ocean
404 error imageI have tested my app in development and successfully got it fully functional in development running on my local server. I have now been trying to push it into development and none of the static files are being served. The connection has been successful as the domain shows the app with just plain HTML. However, all static files are returning the same 404 error. i have tried to modify my static_root in my settings.py. I have my paths set up like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
Why django codes not updating automatically using supervisorctl and Gunicorn?
Using Supervisor, I deployed Django. Django codes are not updated, instead I must restart Nginx or Supervisor. If you could help me with this issue, that would be great. Supervisor configuration [program:program_name] directory=/home/user/django/dir/django_dir/ command=/home/user/django/dir/venv/bin/gunicorn --workers 3 --bind unix:/home/user/django/dir/name.sock ingen> #command=/home/user/django/dir/venv/bin/gunicorn_config.sh numprocs=3 process_name=name%(process_num)d autostart=true autorestart=true stopasgroup=true user=user Group=www-data stderr_logfile=/home/user/django/dir/logs/supervisor_err.log stdout_logfile=/home/user/django/dir/logs/supervisor.log redirect_stderr=true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 I am trying to restart the supervisor process with the below command in order to update the Django backend codes, but it doesn't always work. sudo supervisorctl restart program_name:* //'program_name' refers to the name of the program in the supervisor configuration file METHOD 2 A second trail with a ssh_filename.sh file and the second command in the above supervisor configuration is used to run the ssh_filename.sh script. #!/bin/bash NAME="django_dir" #Django application name DIR_PARENT=/home/user/django/dir DIR=${DIR_PARENT}/django_dir #Directory where project is located USER=user #User to run this script as GROUP=www-data #Group to run this script as WORKERS=3 #Number of workers that Gunicorn should spawn SOCKFILE=unix:${DIR_PARENT}/dir.sock #This socket file will communicate with Nginx DJANGO_SETTINGS_MODULE=django_dir.settings #Which Django setting file should use DJANGO_WSGI_MODULE=django_dir.wsgi #Which WSGI file should use LOG_LEVEL=debug cd $DIR source ${DIR_PARENT}/venv/bin/activate #Activate the virtual environment export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR_PARENT:$PYTHONPATH #Command to run the progam under supervisor exec ${DIR_PARENT}/venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ … -
APNS Server Error - Bad Device Token (Only on production not develop of Heroku)
We are getting the following error when trying to send a notification to a user on the production version of our iOS app: enter image description here However, it is working properly on the development version. Our tech stack is using SwiftUI on the frontend, Django on the backend and for notififcations we are usign the django-push-notifications library and APNS. Please let us know if you have any ideas! We tried viewing logs, resetting package dependencies, and changing the settings.py file by turning sandbox to false among other things. -
M-Pesa payment gateway integration Django
I need m-Pesa payment gateway integration in node or Django. Want to get reference from the code and modify it according to my need. Do anyone integrated before? -
How to startapp from inside docker-compose
I have a problem in the steps of testdriven.io The definitive guide to Django Celery, when i want to start a new tdd app if i execute these commands ` $ docker-compose exec web bash (container)$ ./manage.py startapp tdd ` it creates an app that is read only and pycharm cant change read only status. Some solutions say that it is because i created the app from root user but i cannot understand how to solve it. Here are the Dockerfile and the Docker-compose. version: '3.3' services: web: build: context: . dockerfile: ./compose/local/django/Dockerfile image: testdriven_web # '/start' is the shell script used to run the service command: /start # this volume is used to map the files and folders on the host to the container # so if we change code on the host, code in the docker container will also be changed volumes: - .:/app ports: - 8010:8000 # env_file is used to manage the env variables of our project env_file: - ./.env/.dev-sample depends_on: - redis - db db: image: postgres:14-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_DB=hello_django - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django redis: image: redis:7-alpine celery_worker: build: context: . dockerfile: ./compose/local/django/Dockerfile image: testdriven_celery_worker command: /start-celeryworker volumes: - .:/app env_file: - … -
How to create api endpoint to create super user in django
Hey i have one question about creating superuser with djangorestframework. I want to create superuser with POST request using DRF 3.14 How should i do that if i'm using Android as a client for example? -
Django - Import Models from an installed Package
I have all of my Django models in another package which I install using pip in a Django app. models_package | - models.py | - setup.py and in models.py i have from django.contrib.auth.models import AbstractUser class User(AbstractUser): .... in my Django app i have my_django_app | ... | models.py website | ... | settings.py manage.py in my_django_app.model i have from models_package.models import * and in website.settings.py i have AUTH_USER_MODEL = "my_django_app.User" but when i run python manage.py runserver i get: RuntimeError: Model class my_django_app.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The Thing is User which comes from models_packages.models and models_packages is not a Django app which I add to INSTALLED_APP in settings.py. it is only a package containing all shared Models that I need in multiple different Django apps. Is there any way to use models in models_package.models without adding it to INSTALLED_APP inside website.settings.py -
How to make Django Formset Management Forms Generate Unique IDs for Fields
I am making an 'Project' program where users can write articles with a variable number of images and associate a list of various important dates with their article. According to the Django documentation, using formsets along with javascript can create dynamic forms for this purpose. However, when trying to implement this for both my image_formset and mydate_formset I opened the console to find that both the {{ image_formset.management_form }} and {{ date_formset.management_form }} had the same IDs for every field. Because of this I cannot use javascript to update the form-TOTAL_FORMS fields to properly reflect how many forms are currently being used. Is there any way to fix so that each form-TOTAL_FORMS can be selected uniquely? I may attempt to work around the problem by adding the parent of {{ date_formset.management_form }} to the script's criteria for selection, but I think having two html elements with the same ID is generally a bad idea. -
How to know that a single user is connected through websocket from multiple devices? In django
I'm working on social media app in django. I have one user who is logged in from multiple devices and connected to websocket. How do i know that from which devices user is connected through websocket and through which is not. So i can send push notifications to user's device from which user is not connected.? For now im handling it through making a table called user devices. This table is connected to user table with foreign key. So whenever user login from a particular device Im storing its information like device id, device token, is_online. And whenever user gets connected through websocket im Changing its state to is online true. And whenever user disconnects from websocket im Changing it to false according to multiple devices. I just want to know is there any more efficient way then this. -
Django - Where do you store non-django .py files in your app?
I have three python files (two that scrape data and 1 with my functions) I'm using in my app. Each file is about 150 lines, I don't want to include this code in views.py to keep my views as clean and readable as possible. Is there a best practice to keep things tidy? A separate folder inside the app with all external non-django .py files (similar to 'Templates' for .html or 'Static' for .css)? Any suggestions are appreciated. A Google search didn't yield any results. -
JWT auth dosen't create token for Custom user model in Django?
I have the following problem : i created a custom UserModel and Djoser for jwt auth. when i create a superuser by terminal it created with hashed password but when i create it with an APIVIEW it created without being hashed so when i need to create a token for created user it gives me "detail": "No active account found with the given credentials" but when i create a token for the superuser it created successfully. my custom user model: class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_("Please enter your email address")) email = self.normalize_email(email) new_user = self.model(email = email, **extra_fields) new_user.set_password(password) new_user.save() return new_user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Super user should have is_staff True')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Super user should have is_superuser True')) if extra_fields.get('is_active') is not True: raise ValueError(_('Super user should have is_active True')) return self.create_user(email, password, **extra_fields) class User(AbstractUser): username = models.CharField(max_length=200, unique=True) email = models.EmailField(max_length=200, unique=True) phone_number = PhoneNumberField(null=False, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'phone_number'] objects = CustomUserManager() def __str__(self): return self.username User View: class UserView(APIView): def get(self, request): user = User.objects.all() serializer = … -
how to give specific permission to users and moderator django
I am working on a django project where it has two type of users. One is moderator (admin) and another one is normal user (researcher). I want the admin can not create blogpost. blogposts can only normal users. normalusers can create, update, delete, view blogpost created by himself and also view other people's posts. The admin can view normal user's post but can not edit their post. The admin the delete or approve post made by normal users. blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved = models.BooleanField('Approved', default=False) like = models.ManyToManyField(get_user_model(), related_name='likes', blank=True) def __str__(self): return self.title users.models.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization', blank=True, null=True) profile_pic = models.ImageField(default='default_person.jpg', upload_to='profile_pics') blog/researcher-profile.html {% extends 'users/base.html' %} {% block content %} <div class="content-section"> <div class="media"> … -
How do class-based views work in Django Rest Framework?
I want to have an understanding to reason about Django + DRF. I'm following along the tutorial on the Django Rest Framework site Consider the SnippetList class in views.py: class SnippetList(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) I'm used to JavasCript and to a more imperative way of doing things and it feels that there is a lot of magic here since I'm not explicitly instantiating any classes nor calling any methods. So, my question is, what happens when I request this view? How can I reason about the steps and the process? I visit the endpoint in http://127.0.0.1:8000/snippets/ to get a list of all the snippets and what is the cascade of events thereafter? How is the /snippets/ query parameter passed to the view class? I realise it's it might not be a specific enough question but I'm trying to disentangle the magic happening behind the scenes. -
Django rest framework 401 error with React Axios
Im working on a project with Django rest framework backend and React as frontend. Axios is used for http request and JWT for authentication. I issue im facing is that, after login and getting token django is throwing 401 error for every request. But this issue is resolved if header config is toggled for Axios. Please find the below codes for your reference and help to resolve. Thanks in advance. DRF **settings.py** REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=2), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': True, } CORS_ALLOWED_ORIGINS = [ "http://localhost:3000" ] **axios setup** const axiosClient = axios.create({ baseURL: import.meta.env.VITE_API_URL, headers: { "Content-Type": "application/json", }, }); export default axiosClient; const jToken = useSelector((state) => state.authSlice.accessToken); axiosClient.interceptors.request.use(function (config) { config.headers.Authorization = `Bearer ${jToken}`; return config; }); **Axios request** const fetchData = async () => { try { const response = await axiosClient.get(AppContext.managementStudentUri); // console.log(response.data); setData(response.data); setIsLoading(false); } catch (error) { apiErrorHandler(error); } }; -
Django dumpdata-loaddata serialize custom class
[Django 2.2] I'm trying to create a set of fixtures from my database using the dumpdata command provided by Django. I want to be able to load these fixtures using the loaddata command. One of the Models I'm trying to dump has a custom field: particularly, I'm facing my problem with a field (of type MyHStoreField) that inherits from django.HStoreField. Django is incapable of serializing MyHStoreField. From the Django docs, I think that what this class needs to be serialized is a custom JSONEncoder (https://docs.djangoproject.com/en/2.2/topics/serialization/#json-1). However, I don't know how to tell both dumpdata and loaddata to use this Encoder. Is there any kind of registry that django uses in order to know which Encoders are available, or do I need to override the loaddata and dumpdata commands somehow?