Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework APIClient login is not working
I have test function to test whether user can login or not. I am using DRF's APIClient and logging in. When I do a get request to a protected API endpoint I get 401 response. I tried to print: print(client.login(username='instructor', password='asdf')) And it is returning True, which means user is found and logged in. But still when I do: response = client.get(reverse('recommend-list')) I am getting 401. Here is my test function: ` def test_user_authentication(self): client = APIClient() user_data = { 'username': 'instructor', 'email': 'myemail@example.com', 'password': 'asdf' } client.post(reverse('user-list'), user_data, format='json') self.assertTrue(User.objects.filter(username='instructor').exists()) print(client.login(username='instructor', password='asdf')) response = client.get(reverse('recommend-list')) self.assertEqual(response.status_code, 200) ` Here is how I create a new user: `class UserViewSet(viewsets.ViewSet): def create(self, request): serializer = UserSerializer(data=request.data) User = get_user_model() if serializer.is_valid(): validated_data = serializer.validated_data try: user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'] ) return Response({'id': user.id, 'username': user.username}, status=status.HTTP_201_CREATED) except IntegrityError: return Response({'error': 'Username is already taken.'}, status=status.HTTP_400_BAD_REQUEST) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ` Making get request to here: `class RecommendViewSet(viewsets.GenericViewSet): authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] def list(self, request): user_id = request.user.id movies = recommend_movies_for_user(user_id) return Response({"message": movies}, status=status.HTTP_200_OK) ` -
I want to add social links to my template in django
<ul class="list-unstyled d-flex"> <li class="ms-3"><a class="link-body-emphasis" href="#" ><i class="fa-brands fa-square-github fa-lg" ></i></a></li> <li class="ms-3"><a class="link-body-emphasis" href="#"><i class="fa-brands fa-facebook fa-lg" ></i></a></li> <li class="ms-3"><a class="link-body-emphasis" href="#"><i class="fa-brands fa-linkedin fa-lg" ></i></a></li> </ul> i want to add social links of my facebook , github and linkedin how can i do that in django without writing a view or url path just pasting my social links in href did'nt working -
how to save image in Django project
when i try to create new employee in my project the instance has been save but image not. here is my model,view and form from my django project my model- `class Emp(models.Model): emp_first_name=models.CharField(max_length=20,null=False) emp_last_name=models.CharField(max_length=20,null=False) emp_father_name=models.CharField(max_length=15,blank=False,default='') emp_mother_name=models.CharField(max_length=15,blank=False,default='') emp_photo=models.ImageField(null=True,blank=True,upload_to='static/image/emp',)` my view- `def EmpAdd(request): if request.method=='POST': form=EmpForm(request.POST,request.FILES) if form.is_valid(): form.save() messages.success(request,'New Employee has been added') else: messages.error(request,'There has been error') else: form=EmpForm() return render(request,'emp/emp_crt.html',{'form':form})` my form - `class EmpForm(ModelForm): class Meta: model=Emp fields='__all__' widgets={ 'emp_id':TextInput(attrs={'class':'form-control',}), 'emp_bod':DateInput(attrs={'type':'date','class':'form-control',}), 'emp_first_name':TextInput(attrs={'class':'form-control',}), 'emp_last_name':TextInput(attrs={'class':'form-control',}), 'emp_father_name':TextInput(attrs={'class':'form-control'}), 'emp_mother_name':TextInput(attrs={'class':'form-control'}), 'emp_photo':FileInput(attrs={'class':'form-control'}), }` when i try to creat new employee in my django project, new employee has been created but image has not been saved.what should i do? -
type error in api profile in django rest framework
typeError at /api/profile/ init() got an unexpected keyword argument 'write only' Request Method: GET Request URL: http://127.0.0.1:8000/api/profile/ Django Version: 3.2.25 Exception Type: TypeError Exception Value: init() got an unexpected keyword argument 'write only' Exception Location: /home/vagrant/env/lib/python3.6/site-packages/rest_framework/fields.py, line 738, in init Python Executable: /home/vagrant/env/bin/python3 Python Version: 3.6.9 Python Path: ['/vagrant', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/vagrant/env/lib/python3.6/site-packages' everything in the code was correct, can't able to access the api/profile page in django server. -
How to fetch all the API urls from django project in Python?
I have a django project, where some API URLs are present in urls.py in urlpatterns path and some are registered as routers(rest_framework_extensions.routers). ref: # urls.py urlpatterns = [ path("healthcheck/", health_check_view, name="healthcheck"), path("something/", include(router_something.urls)) ] here, router_something is being used to register further urls like: router_something = DefaultRouter(trailing_slash=False) router_something.register(r"path1/(?P<pk>\d+)/roles", SomeViewSet) I want to fetch all the urls in the django project with their complete path, for example: healthcheck/ something/path1/1/roles # here i am replacing the placeholder pk with 1, this is something I can do ... -
triggers error in admin default not showes. Why?
InternalError at /admin/entities/branch/add/ The type of building does not match the expected type: 'Branch' CONTEXT: PL/pgSQL function check_outlet_type_consistency() line 9 at RAISE How show in default django admin this error? googled, :( but no info -
I can't import TinyMCE
HELLO. No matter what I did, I couldn't import Tinyemc. I don't just get this error on Tinyemc; This problem exists in everything that is similar. [enter image description here](https://i.sstatic.net/5GjZoaHO.png) [enter image description here](https://i.sstatic.net/BHWlmsFz.png) [enter image description here](https://i.sstatic.net/65a3OvdB.png)your text` I couldn't find a solution to the problem in any way.`your text`` -
Text with Image Django Admin
i'd like to know how can i have a fancy editor in django admin, that can add images inside the content, like ckeditor, but when it saves, it converts all in base 64 and store it in the database istead uploading the files to a media folder. Thanks. I've tried to use ckeditor 5, but it stores the images appart the content in a separated folder. -
default datetime value at django form
i'm trying to use a default value class MSeguimientoEtnicoForm(forms.ModelForm): ... fecha_reporte = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class': 'form-control'})) ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Establece la fecha y hora actuales como valor inicial para fecha_reporte self.fields['fecha_reporte'].initial = timezone.now() template: <div class="col-sm-4"> <div class="form-group"> <label for="fechaReporte">Fecha Reporte: </label> <input class="form-control" id="fechaReporte" type="datetime-local" name="fecha_reporte" required> </div> </div> but doesn't take the timezone.now() value at the view template view and default value don't working i was searching for aroud but i didn't found nothing -
Create superuser in ktor
in django, there's manage.py createsuperuser for creating a user with elevated privileges. For ktor, I have resorted to creating a user programmatically when the app starts, (first checking if the user already exist) Is there a more elegant or standard way of doing this? I assume it would be a similar process in other frameworks, express, flask etc since they don't also have that -
I'm trying to convert a .txt file to a .pdf file, but I'm facing this problem
def txttopdf(request): if request.method == 'POST': txt = request.FILES['txt'] pdf = fpdf.FPDF() pdf.add_page() pdf.set_font("Arial", size=12) pdf.cell(200, 10, txt.read().decode('utf-8'), 0, 1) return HttpResponse(pdf.output(dest='S'), content_type='application/pdf') return render(request, 'txttopdf.html') I create the pdf file but I cannot view its content. I'm trying to convert a .txt file to a .pdf file, but I'm facing this problem. -
Django allauth: Unable to get Access token when login using google social account
I am using django allauth for google authentication. settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-9#c!e&s(-o9-6u^mt#w(w6s$ober^f(m45)=f)=m&zo1$dlcg&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'allauth', # Social login App 'allauth.account', # login App 'allauth.socialaccount', # Social login App 'allauth.socialaccount.providers.google', # Google login App 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "API", # API APP ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "allauth.account.middleware.AccountMiddleware" ] ROOT_URLCONF = 'MassMail.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.normpath(os.path.join(BASE_DIR, 'templates')), ], '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', 'django.template.context_processors.request', # requirements for django-all-auth ], }, }, ] WSGI_APPLICATION = 'MassMail.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators 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', }, ] # Google Authentication … -
Django Unit Test Fail when i test UpdateView
In my project i have UserUpdateView like this: class UserUpdateView(AuthenticationMixin, AuthorizationMixin, SuccessMessageMixin, UpdateView): '''Update User info(username, full/second name, password)''' model = User form_class = UserForm template_name = 'form.html' permission_denied_message = _("You can't change this profile, this is not you") permission_denied_url = reverse_lazy('users-detail') success_message = _('User Profile is successfully changed') success_url = reverse_lazy('users-detail') extra_content = { 'title': _('Update user'), 'button_text': _('Update'), } User model like this: class User(AbstractUser): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) def __str__(self): return self.get_full_name() And test for UserUpdateView: class UpdateUserTest(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create(username='tota123', first_name='Andrey', last_name='Totavich', password='lexA456132') def test_update_user(self): self.client.login(username='tota123', password='lexA456132') response = self.client.post( reverse('user-update', kwargs={'pk': self.user.pk}),{ 'username': 'tota321', 'first_name': 'Sergey', 'last_name': 'Simo', 'password1': 'lexA456132', 'password2': 'lexA456132' }) self.assertEqual(response.status_code, 302) # Redirect after successful update self.assertEqual(self.user.username, 'tota321') The tests result: self.assertEqual(self.user.username, 'tota321') AssertionError: 'tota123' != 'tota321' - tota123 ? -- + tota321 ? ++ How can i solve this problem & why model of user dont change? When i run my project localy - i can change user info, and it work, UserUpdateView works correctly. What i missing ? -
AttributeError while loading pickle file from views.py
I am getting AttributeError: Can't get attribute 'predictionFunction' on <module 'main' from location of manage.py . When I don't register the viewfunction in the url, the predictionFunction gets loaded but when I register it in the urls it shows error. For your reference here is what my views.py file looks like: api_view(['GET']) def predictLaptopPrice(request): parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) file_path = os.path.join(parent_dir, 'predictionFunction.pkl') print("File path:", file_path) with open(file_path, 'rb') as file: predictionFunction = pickle.load(file) file.close() print("Loaded prediction function:", predictionFunction) processor_speed = request.GET.get('processor_speed') ram_size = request.GET.get('ram_size') storage_capacity = request.GET.get('storage_capacity') result = predictionFunction([[processor_speed, ram_size, storage_capacity]]) return Response({'price': result[0]}, status=status.HTTP_200_OK) I searched everywhere what this error is about but don't know what is happening. -
How to filter a queryset by a many2many field
I have a Notification model which has a field called seen_users like so: from django.contrib.auth import get_user_model User = get_user_model() class Notification(models.Model): title = models.CharField(max_length=255) seen_users = models.ManyToManyField(User, blank=True) Whenever a user sees a notification (.e.g notification_obj), that user will be added to notification_obj.seen_users. Now how can I filter notifications that has not seen by a specific user like user1 In most efficient way? I've tried to query like below: class NotificationView(generics.ListAPIView): authentication_classess = [TokenAuthentication] permission_classes = [] def get_queryset(self): unseen_only = self.request.GET.get("unseen_only", "0") if unseen_only == "1": # THIS IS WHERE I GOT TROUBLES # Because other users may have seen this and its not empty return Notification.objects.filter(seen_users__in=[]) return Notification.objects.all() -
Django forms, blank line
In my Django form I have a blank line (_____) when I look at my choices, how to fix this? Trying to remove this line Here is the code special_occasion = models.CharField(max_length=11, choices=[('None', 'None'), ('anniversary', 'Anniversary'), ('date', 'Date'), ('business', 'Business')]) -
Why celery doesn't run the code and how can i fix it?
I'm developing an api in django, for this api I need to use celery to do delayed actions. eventually, the aim would be to remove data from the database after a certain period of inactivity. I've set up celery and Rabbitmq, but when I try to execute something with a print to try nothing happens. here's how I set up celery in settings.py: #celery settings import ssl CELERY_BROKER_URL = 'amqps://guest:guest@localhost:5671/' CELERY_BROKER_USE_SSL = { 'ca_certs': '/etc/rabbitmq/cacert.crt', 'keyfile': '/etc/rabbitmq/key.pem', 'certfile': '/etc/rabbitmq/cert.crt', 'cert_reqs': ssl.CERT_REQUIRED } CELERY_RESULT_BACKEND = "rpc://" here's the code I'm trying to run: from __future__ import absolute_import, unicode_literals from celery import shared_task from django.utils import timezone from datetime import timedelta #DELAY_FOR_DATA_DELETION = timedelta(days=30) # 30 jours par exemple @shared_task def delete_user(): print("test") return that's how I call the function: delete_user.apply_async(countdown=5) and here's how I set up the celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings') app = Celery('base', broker="amqps://guest:guest@localhost:5671/") app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() I've tried to do “celery status” to see the worker status but I get this error # /home/transcendence/venv/bin/celery status Traceback (most recent call last): File "/home/transcendence/venv/lib/python3.11/site-packages/amqp/connection.py", line 515, in channel return self.channels[channel_id] ~~~~~~~~~~~~~^^^^^^^^^^^^ KeyError: None During handling of the above exception, another … -
Django: Ignore trans strings which are already translated in app directory
I use django-allauth as a third partie package in my Django project. I copied some templates from django-allauth into my template directory to modify the layout. But I did not touch the translation strings! After running makemessages this strings appears in my .po file even though it is translated in the app directory for django-allauth. (To manage my translations I use Weblate.) How can I stop this behavior? This is blowing up my .po file and is confusing the translators, because we have to notify them not to touch this string. Can I create a list of "msgid" which will ignore some strings? -
Django Admin Soft Dashboard in aws ec2 ubuntu 24.04 using pyhton 3.6.8
For my django admin panel I used django-soft-admin-panel pip for UI, as my python runtime is 3.8 it didn't run, so I downgraded by python to 3.6 and developed the project, the ui and all other things are perfectly working in local. I need to deploy the project in any of the aws services. At first I used lambda, but lambda is only for runtime >= 3.8 then I used Elastic Beanstalk, ebs is only for runtime >= 3.7 then I deployed in EC2 with nginx and gunicorn but the project and server getting crashed. Is there any solution? -
Django Rest Framework Many To Many serializer problem
I'm creating an API in Django Rest Framework and I have a problem with a ManyToMany relation. I'm trying to create an movie and assign genre to it (ManyToMany relationship between movie and genre). Here are my models: class Genre(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(null=False,blank=False,max_length=50) def __str__(self): return self.name class Movie(models.Model): id = models.IntegerField(primary_key=True,null=False,blank=False) adult = models.BooleanField(null=False,blank=False) backdrop_path = models.CharField(null=True,blank=True,max_length=200) budget = models.BigIntegerField (default=0) homepage = models.CharField(null=True,blank=True,max_length=200) original_language = models.CharField(max_length=10) original_title = models.CharField(max_length=200) overview = models.CharField(max_length=1000) poster_path = models.CharField(null=True,blank=True,max_length=200) release_date = models.DateField(null=True,blank=True,) revenue = models.BigIntegerField (default=0) runtime = models.IntegerField(null=True,blank=True) status = models.CharField(max_length=50) tagline = models.CharField(null=True,blank=True,max_length=100) title = models.CharField(max_length=200) genres = models.ManyToManyField(Genre,blank=True) def __str__(self): return self.title here are my serializers: class GenresSerializers(serializers.ModelSerializer): class Meta: model = Genre fields = ['id','name'] def create(self,validated_data): instance, _ = Genre.objects.get_or_create(**validated_data) return instance class MovieGenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ['id'] def create(self, validated_data): instance, _ = Genre.objects.get(**validated_data) return instance class MoviesSerializer(serializers.ModelSerializer): genres = GenresSerializers(many= True) class Meta: model = Movie fields = [ 'id', 'adult', 'backdrop_path', 'budget', 'homepage', 'original_language', 'original_title', 'overview', 'poster_path', 'release_date', 'revenue', 'runtime', 'status', 'tagline', 'title', 'genres' ] # extra_kwargs = {'id': {'read_only': True}} def create(self, validated_data): genres_data = validated_data.pop('genres', []) genresInstances = [] for genre in genres_data: genresInstances.append(Genre.objects.get(pk = … -
Issue with closing modals by clicking outside on specific page
I have implemented modals on my Django website using Bootstrap, where the modals open upon clicking buttons and close when clicking outside of them. This functionality works perfectly on most pages of my website, including the base template. However, I'm encountering an issue on my system page where the modals do not close when clicking outside of them. Here's the relevant code snippet from my base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </head> <body class="background-image-shop"> <!-- Navbar --> <nav class="main-top-navbar navbar navbar-light bg-black fixed-top navbar-custom"> <div class="container"> <div class="main-top-navbar-elements navbar-text"> <a href="{% url 'shop' %}" class="font-weight-bold text-light" style="margin-right: 20px;">Tribute |</a> <a href="{% url 'temples' %}" class="font-weight-bold text-light" style="margin-right: 20px;">Temples |</a> <a href="#" class="font-weight-bold text-light" style="margin-right: 20px;">Merchandise |</a> </div> <a href="#" class="navbar-brand">Your Logo</a> <!-- Add Product Button (visible for admin users only) --> {% if user.is_authenticated and user.is_superuser %} <button class="btn btn-outline-light" onclick="showAddProductModal()">Add Product</button> {% endif %} <!-- Search Bar --> <div class="shop-slogan"> <p>The Cards Await You!</p> </div> </div> </nav> <!-- Main content --> <div id="main-content"> <!-- Your website content here --> {% block body %} … -
Django message about waiting for process
I created app, which generate pdf file with some content. After filling form by user it is submitted and after about 10 seconds file preview is opening. I want to show message that user should wait for file after hiting Submit. When I add a meesage it shows but not earlier than download start and message it is not visible (it shows too late). Actually to show the messege I need to comment line return responce my view: def pdf_create(request): if (request.method == 'POST'): form = MsdsForm(request.POST) messages.info(request, f'''Please wait for a file.''') if (form.is_valid()): cd = form.cleaned_data # A LOT OF CODE AND THINGS HERE wchich create pdf response = HttpResponse(pdf_output, content_type='application/pdf') response['Content-Disposition'] = f"filename=some_file.pdf" return response else: form = MsdsForm() return render(request, 'msds_form.html',{'form':form}) I searched google for couple of hours and didn't find simple solution. I omit some details or it isn't simple way to do that? I don't know if it is essential in this case but I don't use models. -
Error : Conversion 'rpy2py' not defined for objects of type
I am using python R library to implement the ERGM model to a data set. I am following the below approach def ergm_process(nodes, edges): try: logger.debug(f"Passed Node: {nodes}") logger.debug(f"Edges: {edges}") # Convert node and edge data for R nodes_df = pd.DataFrame(nodes) edges_df = pd.DataFrame(edges) nodes_df['Attendance'] = pd.to_numeric(nodes_df['Attendance'], errors='coerce') if 'id' not in nodes_df.columns: logger.error("Node data must include 'id' keys") return {"error": "Node data incomplete"} # R DataFrame Conversion nodes_r = pandas2ri.py2rpy(nodes_df) # Prepare node and edge data for R node_ids = nodes_df['id'].tolist() edges_tuples = [(edge['from'], edge['to']) for edge in edges] # Log and check edge tuples if not all('from' in edge and 'to' in edge for edge in edges): logger.error("One or more edges are missing 'from' or 'to' keys") return {"error": "Edge data incomplete"} flat_edges = [item for tup in edges_tuples for item in tup] # Setup R environment from rpy2.robjects.packages import importr base = importr('base') network = importr('network', on_conflict="warn") ergm = importr('ergm', on_conflict="warn") # Pass data to R ro.globalenv['nodes'] = nodes_r ro.globalenv['node_ids'] = ro.StrVector(node_ids) ro.globalenv['edges'] = ro.IntVector(flat_edges) # Flatten list of tuples # Run R code ro.r(''' print("Node IDs:") print(node_ids) print("Edges:") print(edges) net <- network::network(matrix(edges, byrow=TRUE, ncol=2), directed=TRUE, vertices=node_ids) # Ensure each attribute is set for (attr_name in colnames(nodes)) … -
How to check if a Django Model Instance contains a foreign key or not
I need to serialize data coming from Django Audit Log Entry in such a way that when in changes field There is a Field present which has a value of foreign key I need to fetch the value of that Foreign key from database and Change the Foreign key with the value. def get_changes(self, obj): changes_data = obj.changes if changes_data: model_name = obj.content_type.model_class().name try: field_mapping = getattr(ma_activity_tracker, f"{model_name}_display_atrb") except AttributeError: field_mapping = {} changes = {} for field, (old_value, new_value) in changes_data.items(): field_name = field_mapping.get(field, field) field_object = globals().get(model_name) print(field_object.User) # if isinstance(field_object, models.ForeignKey): if isinstance(field_object,models.ForeignKey): old_related_obj = field_object.related_model.objects.filter(pk=int(old_value)).first() new_related_obj = field_object.related_model.objects.filter(pk=int(new_value)).first() old_display_value = getattr(old_related_obj, field_name) if old_related_obj else None new_display_value = getattr(new_related_obj, field_name) if new_related_obj else None old_value = old_display_value new_value = new_display_value changes[field_name] = { "Old Value": old_value, "New Value": new_value } return changes return None This is what I tried but to do but the if block never gets executed -
Postman request to django with csrf works but not with request in NextJS
I'm currently working on a login system that needs a POST request and csrf authentication, so I started to work with postman and trying to send requests and took the snippet provided by the generator: const myHeaders = new Headers(); myHeaders.append("X-CSRFToken", "OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h"); myHeaders.append("Cookie", "csrftoken=OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h"); const requestOptions = { method: "POST", headers: myHeaders, redirect: "follow" }; fetch("http://127.0.0.1:8000/simulazione/api/prova_token/", requestOptions) .then((response) => response.text()) .then((result) => console.log(result)) .catch((error) => console.error(error)); The request above works in postman but if I took this code and write it in nextjs a got the forbidden error [30/Apr/2024 13:11:47] "POST /simulazione/api/prova_token/ HTTP/1.1" 403 2869 These below are the django view and settings: View @csrf_protect def prova_token(request): if request.method == 'POST': return JsonResponse("hello", safe=False) Settings CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True #CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_SECURE = False SESSION_COOKIE_SAMESITE = None ALLOWED_HOSTS = [ ] CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:3000","http://localhost:3000"] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'csrftoken', 'x-requested-with', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', 'http://localhost:3000', ] # Application definition INSTALLED_APPS = [ 'corsheaders', 'simulazione.apps.SimulazioneConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_nextjs', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I …