Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-RQ API_TOKEN configuration to access to stats endpoint
I'm trying to retrieve some statistics from the django-rq queues and I'm having some difficulties to access to the provided URL from the Django-Rq documentation These statistics are also available in JSON format via /django-rq/stats.json, which is accessible to staff members. If you need to access this view via other HTTP clients (for monitoring purposes), you can define RQ_API_TOKEN and access it via /django-rq/stats.json/<API_TOKEN>. Well, I have defined a simple RQ_API_TOKEN just for testing purposes in my settings.py RQ_API_TOKEN = "AAABBBCCC" And I'm trying to access it via Postman but I keep receiving the following response: {"error": true, "description": "Please configure API_TOKEN in settings.py before accessing this view."} I've tried to send the token in the headers o even a query param, but it still doesn't work as is intended to work. Example URLS that I've tried with query params: django-rq/stats.json/?token=AAABBBCCC django-rq/stats.json/?api_token=AAABBBCCC django-rq/stats.json/?API-TOKEN=AAABBBCCC django-rq/stats.json/?API_TOKEN=AAABBBCCC The same I've tried, but leaving no query param and inserting the token as a header with the same keys. Nothing works. -
SynchronousOnlyOperation from celery task using gevent execution pool on django orm
I found this question that describes exactly what happens to my software, but I haven't found any answers to this problem. SynchronousOnlyOperation from celery task using gevent execution pool is there any update on how to use gevent and celery in combination with django orm? I've opened quite a few issues from all sides but I'm not getting replies. https://forum.djangoproject.com/t/synchronousonlyoperation-from-celery-task-using-gevent-execution-pool/21105 https://forum.djangoproject.com/t/synchronousonlyoperation-django-gunicorn-gevent/21182 https://github.com/celery/celery/issues/8262 https://github.com/gevent/gevent/issues/1955 https://github.com/benoitc/gunicorn/issues/3000 monkey.patch_all() and https://github.com/psycopg/psycogreen -
Site 127.0.0.1 does not allow connection
please help me understand. I have a separate html page on which I display certain information in the form of a table. In my main page, I am displaying this page through an iframe, but instead of displaying the page, it shows me a gray page that says "Site 127.0.0.1 does not allow connection". What could be the problem? main.html: <a href="{% url 'units' rack.pk %}" target="temp"><button>test</button></a> <iframe name="temp" src="units.html"></iframe> That is result: -
The default value with or without "()" in a Django model field and "ValueError: Cannot serialize function" error
<The 1st case>: I can use timezone.now() with or without () as a default value in DateTimeField() as shown below: from django.utils import timezone # Here datetime = models.DateTimeField(default=timezone.now()) Or: from django.utils import timezone # Here datetime = models.DateTimeField(default=timezone.now) So, what is the difference between now() and now? <The 2nd case>: I can use timezone.now().date() with () as a default value in DateField() as shown below: from django.utils import timezone # Here date = models.DateField(default=timezone.now().date()) But I cannot use timezone.now().date() without () as a default value in DateField() as shown below: from django.utils import timezone # Here date = models.DateField(default=timezone.now().date) Then, I got the error below: ValueError: Cannot serialize function <built-in method date of datetime.datetime object at 0x0000019D077B70F0>: No module So, what is the difference between now().date() and now().date? -
How to solve "Preparing metadata (setup.py): finished with status 'error'" when deploy django + mysqlclient in railway.app
I'm trying to deploy my Django website on the railway.app host. It works out smoothly without the "MySQL" database. It works smoothly with "MySQL" at localhost too, but when I upload it to railway it fails. I wonder if there are some unfinished dependencies. How does i fix this? My database code looks like this:`DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': os.environ.get('MYSQLHOST'), 'PORT': os.environ.get('MYSQLPORT'), 'NAME': os.environ.get('MYSQLDATABASE'), 'USER': os.environ.get('MYSQLUSER'), 'PASSWORD': os.environ.get('MYSQLPASSWORD'), } }` I'm programming on a windows desktop. -
File upload using Django Forms
I have a file field in MissFormModel model: file = models.FileField(upload_to ='uploads/') My forms.py looks like: class SendNewRequest(ModelForm): class Meta: model = MissFormModel fields = ("sender", "file") labels = { 'sender':'', 'file':'', } widgets = {} My index view: def index(request): context ={} forms = MissFormModel.objects.all() if forms.exists(): return render(request, 'app/index.html', {'forms':forms,'context':context}) else: return render(request, 'app/index.html', {'forms':None,'context':context}) I am trying to implement file upload forms: def send_new_request(request): form = SendNewRequest() if request.method == 'POST': form = SendNewRequest(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('index') return render(request, 'forms/new_request.html', {'form':form}) My template: {% for i in forms %} <tr> <th scope="row">{{i.id}}</th> <th>{{i.sender}}</th> <th> {% if i.file %} <a href="{{ i.file.url }}" class="btn btn-primary btn-sm" target="_blank"> Download </a> {% endif %} </th> </tr> {% endfor %} My new_request.html: <form action="" method="POST" encytpe="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> But when I've created new forms with attachment at my index page i see nothing. The same situation in admin page. Could you explain what i am doing wrong? -
Django ORM get object based on many-to-many field
I have model with m2m field users: class SomeModel(models.Model): objects = SomeModelManager() users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) My goal is to get instance of this model where set of instance users matches given queryset (it means that every user from queryset should be in m2m relation and no other users). If I do obj = SomeModel.objects.get(users=qs) I get ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. And I totaly understand the reason of such error, so the next thing I did was creating a custom Queryset class for this model to override .get() behavior: class SomeModelQueryset(QuerySet): def get(self, *args, **kwargs): qs = super() # Prevent recursion if (users := kwargs.pop('users', None)) is not None: qs = qs.annotate(count=Count('users__id')).filter(users__in=users, count=users.count()**2) return qs.get(*args, **kwargs) class SomeModelManager(models.Manager.from_queryset(SomeModelQueryset)): ... So what I try to do is to filter only objects with matching users and make sure that amount of users is the same as in queryset. But I don't like current version of code. users__in adds instance to queryset each time it finds match, so it results in n occurrences for each object (n - number of m2m users for specific object). Count in .annotate() counts unique users … -
Why am I getting a Forbidden (403) CSRF cookie not set error when trying to login after deploying my Django project?
Django project works locally, but when I deployed it and tried to login I got Forbidden (403) CSRF cookie not set. My settings.py have this code 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', ] # template stuff TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': PROJECT_TEMPLATES, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages' ], }, }, ] # Internationalization USE_I18N = False SECURE_CROSS_ORIGIN_OPENER_POLICY = None #SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_NAME = 'new_session_id' CSRF_COOKIE_NAME = 'new_csrf_token' SESSION_COOKIE_SECURE=False #CSRF_COOKIE_SECURE = True CSRF_USE_SESSIONS = True CSRF_TRUSTED_ORIGINS =["http://34.118.121.194:8000","https://34.118.121.194:8000",'http://34.118.121.194:8000/','https://34.118.121.194:8000/'] #SESSION_COOKIE_AGE = 7200 CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'None' #SESSION_COOKIE_DOMAIN = 'localhost:8000' ALLOWED_HOSTS = ['*'] I have the csrf tag in my form. I tried mutliple things, but nothing helped. I also inspected it and noticed that the set-cookie is present in the login get request, but not in the post. The cookie in the get request looks like this: Set-Cookie: new_session_id=7hdqxannws6eakk1ayc8at3dldustjrj; expires=Mon, 12 Jun 2023 09:28:14 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None I have deployed it with google cloud, not sure whether it can affect it or not. The connection to the site is not secure also. Please give suggetions what the problem might be. -
Handling 'Object of type SimpleUploadedFile is not JSON serializable' error in Django DRF tests
If you're working with nested parameters in Django and experiencing difficulties while testing, you can pass the data for the nested structure using dictionaries or JSON objects. Here's an example of how you can do it: serializer.py class ProductImageCreateSerializer(serializers.ModelSerializer): class Meta: model = AlProductImage fields = [ 'image_name', 'image_src' ] class ProductOptionCreateSerializer(serializers.ModelSerializer): option_length = serializers.IntegerField(default=0) is_active = serializers.CharField(default='y') is_direct_delivery = serializers.CharField(default='n') is_custom = serializers.CharField(default='n') class ProductCreateSerializer(serializers.ModelSerializer): name = serializers.CharField() brand_id = serializers.CharField(write_only=True) purchase_count = serializers.IntegerField(default=0) custom_yn = serializers.CharField(default='n') is_active = serializers.CharField(default='y') options = serializers.ListSerializer( child=ProductOptionCreateSerializer(), write_only=True, required=False, ) images = serializers.ListSerializer( child=ProductImageCreateSerializer(), write_only=True, required=False, ) tests.py class ProductTest(MainScenarioTest): def create_product(self, data): res = self.client.post( path='/product/product/', data=data, content_type='application/json', ) return res def test_product_create(self): brand = 1 input_data = dict( name='test product', brand_id=brand, options=[ { 'options': "test_option", 'option_length': 100, 'price': 500, 'delivery_fee': 300, 'direct_delivery_fee': 300, 'quantity': 300, }, { 'options': "test_option", 'option_length': 100, 'price': 500, 'delivery_fee': 300, 'direct_delivery_fee': 300, 'quantity': 300, } ], images=[ { 'image_name': 'test_image_1.jpg', 'image_src': SimpleUploadedFile( 'test_image_1.jpg', open(os.path.join('test_imgs', 'hanssem.jpg'), 'rb').read() ) } ] ) res = self.create_product(input_data) print(res) I have an error [Object of type SimpleUploadedFile is not JSON serializable] I tried encoding it in base64, but it failed because the image_src field is of type FileField. I also … -
How to add firebase google login method to a django app
I am developing a Django web application and I would like to integrate Firebase Google Login for user authentication. I have gone through the Firebase documentation, but I couldn't find a direct approach for implementing Google Login in Django. I would like to know how I can add Firebase Google Login to my Django app. Specifically, I would like to achieve the following: Allow users to sign in to my Django app using their Google accounts. Retrieve user information such as email, name, and profile picture from Google after successful authentication. Save the authenticated user to Firebase Authentication for further authentication and authorization. I have already set up Firebase for my project and obtained the necessary service account JSON file. I have also installed the required packages like firebase-admin, -
How to make django-filter depend on another django-filter
I'm using package django-filter and i have some fields which i want to be depend on another field like i have field name and field car and if i choose name Michael in name filter, filter car will show me only cars that Michael has This looks like a big problem and i dont know how to solve that filters.py import django_filters from django_filters import DateTimeFromToRangeFilter from django.db.models import Q from common.filters import CustomDateRangeWidget from common.models import CounterParty, ObjectList from .models import OpenPointList class OpenPointFilter(django_filters.FilterSet): """ Django-filter class to filter OpenPointList model by date, CounterParty name and Object name """ CHOICES = ( ('Closed', 'Closed'), ('Open', 'Open') ) status = django_filters.ChoiceFilter(choices=CHOICES) category_choice = django_filters.ModelChoiceFilter(label='Категория', queryset=OpenPointList.objects.values_list('category', flat=True).distinct()) category = django_filters.CharFilter(method='custom_category_filter') class Meta: model = OpenPointList fields = ( 'open_point_object', 'status', 'category', ) -
Django - CrispyForms - DecimalField - Validation Error Message
I have the following model and would like to ensure that a) either the user is able to enter only numbers and a decimal point or b) a custom validation error is displayed to the user to enter a decimal value only. I am using the init method and would like to include such validation in this method. Is it possible?. The CurrencyCode is a ForeignKey field so it has to appear as a dropdown on the rendered form. Below is the code and screenshots: MODELS.PY: class Forex(models.Model): currency_code = models.ForeignKey(Currency, on_delete=models.CASCADE) forex_rate = models.DecimalField(max_digits=8, decimal_places=4) last_updated_on = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Forex Rates" def __str__(self): return self.currency_code.currency_code FORMS.PY: class ForexForm(forms.ModelForm): class Meta: model = Forex fields = ['currency_code', 'forex_rate'] def __init__(self, *args, **kwargs): super(ForexForm, self).__init__(*args, **kwargs) self.fields['currency_code'].error_messages = {'required': 'Currency Code Cannot Be Blank', 'unique': 'Forex Rate Already Exists!' } self.fields['forex_rate'].error_messages = {'required': 'Forex Rate Cannot Be Blank'} VIEWS.PY: def forex_add(request): form = ForexForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, msg_add) return redirect('forex_list_page') context = { 'form': form } return render(request, 'main/forex_add.html', context) FOREX_ADD/HTML: <form action="" method="POST" novalidate> {% csrf_token %} <div class="row"> <div class="col-4"> {{ form.currency_code|as_crispy_field }} </div> <div class="col-8"> {{ form.forex_rate|as_crispy_field }} </div> </div> <div class="col-12"> … -
Why is django TestCase not connecting to test database?
1 I am writing a Django test inheriting from django.test.TestCase. Everywhere, in the docs, it says a test db will be automatically created. Here I am using the very standard approach but the test_get_opportunity class method is using my production db. Even tough a test db is created the objects.create doesnot populate it with data and the datas are fetched from my production db Please see my code bellow. from django.test import TestCase import request from core.models import Opportunity class OpportunityViewTest(TestCase): def test_get_opportunity(self): # Create a test opportunity opportunity = Opportunity.objects.create(name='TestOpportunity', created_by='postgres') print(opportunity.id) # Set up the request url = "http://127.0.0.1:8000/pure-protect/opportunity/" data = {'opportunity_id': opportunity.id} response = requests.get(url, data) print(response.json()) # Assert the response self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()['status'], 'success') I have used --keepdb to verify id the data is updated in the table but its not updated When i hard code the opportunity_id in request. I see the datas are fetched from production db What do I do wrong and what has to be done so a test db is used for the test? -
Iterate over a list in a template from a dictionary generated in View file
I am creating a table in Django with columns of static and dynamic data. The dynamic data is easy to call from the database and loop through. The static data has been stored in the View as a dictionary. The problem I'm facing is when I need to iterate over a list in the template that comes via the dictionary. Here is the template code: <thead> <tr> <th>Amino acid</th> <th>Common</th> <th>Example species</th> <th>All consumers</th> <th>Text</th> <th>Image</th> </tr> </thead> <tbody> {% for amino_acid, use, text, image in amino_acids %} <tr> <td>{{ amino_acid }}</td> <td>{{ amino_acid_counts|dict_lookup:amino_acid|default_if_none:''|dict_lookup:'count' }}</td> <td> {{ amino_acid_counts|dict_lookup:amino_acid|default_if_none:''|dict_lookup:'example_list' }} </td> <td> {{ amino_acid_counts|dict_lookup:amino_acid|default_if_none:''|dict_lookup:'total_count' }} </td> <td> {{ text }} </td> <td><img src="{{ image }}" style="width: 200px; height: 150px;"> </td> </tr> {% endfor %} </tbody> This works fine, except for {{ amino_acid_counts|dict_lookup:amino_acid|default_if_none:''|dict_lookup:'example_list' }} which just displays the list like this: ['bacteria1', 'bacteria2' etc.]. Ideally, I'd like to iterate over this list and link urls to each list item, e.g.: {% for bug in example_list.items %} <i><a href="/bacteria/{{ bug.slug }}" target="_blank">{{bug}};</a></i> {% endfor %} Is there a way to do this either in the template or in the view? -
'QuerySet' object has no attribute 'book_set'
I have these models: from django.db import models # Create your models here. class Author(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False,verbose_name="Full Name") def __str__(self): #template = '{0.name}' return self.full_name class Meta: verbose_name_plural='01-Author' class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True,blank=True) title = models.CharField(max_length=255, null=False, blank=False, verbose_name="Book Titles") production = models.DateField(max_length=255, null=False, blank=False, verbose_name="Productions Date") def __str__(self): return self.ttile class Meta: verbose_name_plural='02-Book' When I try to call method book = author.book_set.all() in views: def detail_book(request, id): author = Author.objects.all() book = author.book_set.all() context = { "title": f"Detail Book", "author": author, "book": book, } return render(request, 'detail_book.html', context) And it cause error 'QuerySet' object has no attribute 'viajems' -
django to vercel deployment error "serverless function has crashed"
I created a django application with a postgres database, im trying to deploy to vercel, by all indication on the browser the server is working correctly , vercel is also working correctly however I'm receiving the message "serverless function has crashed". help ive checked the logs, crosschecked the details and database values and ensured it runs locally. -
How to decide the resolution of image extracted from pdf by pymupdf
I am using pymupdf and django, I extract images from pdf. my source code is like this. doc = fitz.open(file_path) for page in doc: pix = page.get_pixmap() # render page to an image pix.save(media_root+ "/parsed/" + str(page.number) + '.png') It makes 1192 x 842 size,96 resolution png. I wonder what makes this size and resolution? The picture in the pdf is more clear, but extracted image is blurred How can I set the final png resolution? I can do this with this perameters? -
Why does database receive no data on a successful Django POST?
I am getting a successful 302 redirect POST when submitting my form, but data is not populating in the database. I am trying to create a simple comments post. Take the comment, submit it, redirect to the one page back ('lists'), display new comments - fairly straightforward - but I cannot figure out why I am not getting any data in the database I am using a postgres backend models.py class TicketComment(models.Model): ticket = models.ForeignKey(TicketList, on_delete=models.CASCADE) technician = models.ForeignKey(TechnicianUser, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s -%s' % (self.ticket.name, self.ticket) forms.py class TicketCommentAddForm(forms.ModelForm): class Meta: model = TicketComment fields = '__all__' views.py def apps_tickets_comments_view(request,pk): tickets = TicketList.objects.get(pk=pk) comments = TicketComment.objects.all() context = {"tickets":tickets,"comments":comments} if request.method == "POST": form = TicketCommentAddForm(request.POST or None,request.FILES or None,instance=tickets) if form.is_valid(): form.save() print(form.cleaned_data['technician']) messages.success(request,"Comment inserted Successfully!") return redirect("apps:tickets.list") else: print(form.errors) messages.error(request,"Something went wrong!") return redirect("apps:tickets.list") return render(request,'apps/support-tickets/apps-tickets-details.html',context) ticket-details.html <form action="{% url 'apps:tickets.comments' tickets.identifier %}" method="POST" enctype="multipart/form-data" class="mt-3"> {% csrf_token %} {{ form.as_p }} <div class="row g-3"> <div class="col-lg-12"> <label for="bodyTextarea1" class="form-label">Leave a Comment</label> <textarea class="form-control bg-light border-light" id="bodyTextarea1" rows="3" placeholder="Enter comment" name="body"></textarea> <input name="technician" type="hidden" name="technician" value="{{user.pk}}"> <input name="ticket" type="hidden" value="{{tickets.pk}}"> </div> <div class="col-lg-12 text-end"> <button type="submit" class="btn btn-success" id="add-btn">Post Comment</button> … -
django-axes doesn't lock users after multiple failed login attempts
I'm using django axes and I'm running my tests, for now, in the admin login area, but for some reason, it's not blocking the user after consecutive failures. When I test it on my localhost, it works normally, but when I deploy it and do the tests with the site on the server, it doesn't block users. django is logging everything to the database as normal. I'll show my settings.py code below: INSTALLED_APPS = [ ... 'axes', ] MIDDLEWARE = [ ... 'axes.middleware.AxesMiddleware', ] AUTHENTICATION_BACKENDS = [ # AxesStandaloneBackend should be the first backend in the AUTHENTICATION_BACKENDS list. 'axes.backends.AxesStandaloneBackend', # Django ModelBackend is the default authentication backend. 'django.contrib.auth.backends.ModelBackend', ] AXES_FAILURE_LIMIT = 3 import datetime as dt delta = dt.timedelta(minutes=5) AXES_COOLOFF_TIME = delta AXES_RESET_ON_SUCCESS = True AXES_ENABLE_ACCESS_FAILURE_LOG = True AXES_LOCK_OUT_AT_FAILURE = True USE_TZ = False I ran the commands python manage.py check and python manage.py migrate OBS: I put the command USE_TZ = False, because I'm using mysql and from what I've read, it needs to be like this -
fullstackcapapi.models.version.Version.DoesNotExist: Version matching query does not exist
I'm making a public prayer journal full stack(for context, the version in the error is closer to Bible translation). Whenever I edit a verse and submit it, I get "fullstackcapapi.models.version.Version.DoesNotExist: Version matching query does not exist." on the backend and this on the frontend: "PUT http://localhost:8000/verses/2 500 (Internal Server Error)". The lines these errors point to: fetch(${dbUrl}/verses/${verseId}, verse.version_id = Version.objects.get(id=request.data["version_id"]) Backend: def update(self, request, pk): "Handle PUT requests for a single post""" verse = Verse.objects.get(pk=pk) verse.uid = User.objects.get(id=request.data["uid"]) verse.verse = request.data["verse"] verse.version_id = Version.objects.get(id=request.data["version_id"]) verse.content = request.data["content"] verse.save() serializer = VerseSerializer(verse) return Response(serializer.data) Frontend: const updateVerse = (user, verse, verseId) => new Promise((resolve, reject) => { const verseObj = { version_id: Number(verse.version_id.id), verse: verse.verse, content: verse.content, uid: user.id, }; fetch(`${dbUrl}/verses/${verseId}`, { method: 'PUT', body: JSON.stringify(verseObj), headers: { 'Content-Type': 'application/json' }, }) .then((response) => resolve(response)) .catch((error) => reject(error)); }); And also this in case it's needed: const handleSubmit = (e) => { e.preventDefault(); if (verseObj.id) { updateVerse(user, currentVerse, verseObj.id) .then(() => router.push('/')); } else { const payload = { ...currentVerse }; createVerse(payload, user).then(setCurrentVerse(initialState)); } }; I don't really know what to do here, any help is appreciated. -
listen for django signals in JS
Is there any way to implement a JS addEventListener that receives a signal from Django? I have to upload multiple files, each one is processed individually sequentially, the idea is to notify as a list each time a document is finished processing. My idea: document.addEventListener('documento_extraido', function(event) { const nombreDocumento = event.detail.nombre_documento; console.log(`El documento ${nombreDocumento} ha sido procesado.`); // Aquí puedes agregar el código para mostrar la notificación de finalización de un documento en el frontend. }); -
Django & React - Session Authentication
I am using session authentication in my Django - React application. But no session cookie is stored in the cookie storage. (A csrf token cookie is stored!) On the frontend Part, I make a post request for the login: axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.withCredentials = true; const client = axios.create({ baseURL: "http://127.0.0.1:8000", }); function submitLogin(e) { e.preventDefault(); setIsLoading(true); client .post("/login", { email: email, password: password, }) .then(function (res) { setCurrentUser(true); window.location.reload(); // Refresh the page after login }) .catch(function (error) { setIsLoading(false); }); } I get a status code 200, user is logged in everything seems to work fine. but no session Cookie is stored and I get a SameSite attribute error in dev tools: Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute even though I set everything in settings.py: SESSION_ENGINE = 'django.contrib.sessions.backends.db' SESSION_COOKIE_SECURE = False # Set it to False during development with HTTP SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = 'None' # If using cross-site requests SESSION_COOKIE_SECURE = True # If using HTTPS note that when setting SESSION_COOKIE_SAMESITE = 'lax' or 'strict' and removing SESSION_COOKIE_SECURE = True # If using HTTPS the log in no longer works I also tried without … -
Django CookieCutter fails on setup with DistutilsFileError
I'm trying to use a Material Design theme for the CookieCutter library. Here's the git to the theme. However after providing all the setup details I get a crash Here's the cookiecutter command I ran cookiecutter https://github.com/app-generator/cookiecutter-django.git Here are the settings I provided during setup Traceback (most recent call last): File "C:\Users\Praneeth\AppData\Local\Temp\tmp6gmwl1xi.py", line 48, in <module> post_hook() File "C:\Users\Praneeth\AppData\Local\Temp\tmp6gmwl1xi.py", line 22, in post_hook copy_tree(fromDirectory, toDirectory) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\distutils\dir_util.py", line 123, in copy_tree raise DistutilsFileError( distutils.errors.DistutilsFileError: cannot copy tree './tmp/apps/static': not a directory ERROR: Stopping generation because post_gen_project hook script didn't exit successfully Hook script failed (exit status: 1) What's going on here? I'm not even sure where this /tmp/apps/static path is on my system. Any recommendations? I'm very lost as I'm new to Django and this CookieCutter library -
Adding custom header to DRF test APIClient
I need to add a custom header to the APIClient for a test. I have tried to follow this section of the official docs from rest_framework.test import APIClient client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) Following the official docs results in an error because the name has hyphens This raises a syntax error because the name is not valid. from rest_framework.test import APIClient client = APIClient() client.credentials(HEADER-WITH-HYPHEN='Token ' + token.key) I also tried using from rest_framework.test import RequestsClient but this needs the url to include http which isn't possible because the server doesn't run while testing. It also isn't possible to change the header name to something more pythonic :| -
django-phone-field and rest framework: not a valid number
I'd like to use django-phone-field together with rest-framework. I've configured a simple model: from phonenumber_field.modelfields import PhoneNumberField class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) phone = PhoneNumberField(null=True, blank=True) As well es as a modelSerializer: from phonenumber_field.serializerfields import PhoneNumberField class UserProfileSerializer(CountryFieldMixin, serializers.ModelSerializer): phone = PhoneNumberField(required=False) user = serializers.StringRelatedField(read_only=True) class Meta: model = UserProfile fields ="__all__" I'd like to be able to use international numbers. The problem is, that depending on the country-prefix used, I'm getting a repsonse to enter a valid number. The examples from the django-phone-field documentation work, using a prefix +1 . The prefix for France and Germany work as well. However, other countries I've tried don't work, e.g. CZ: +420 . But maybe I'm using the module wrong altogether. Does someone know, how to use django-phone-field + rest-framework with international numbers? Thanks a lot. -)