Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -) -
problem to deploy in vps ( Ubuntu 22.04 64-bit with Django/OpenLiteSpeed)
I bought a vps on hostinger to deploy a django project that I already have, but I'm a beginner and I didn't find anything that would help me, can anyone help me? I use this vps option: Ubuntu 22.04 64-bit with Django/OpenLiteSpeed I already tried to clone my git repository with git clone (my repository) but I couldn't put it as the main repository in the vps -
What is the difference between python script run in shell and python script run in djanho web server?
I am beginner in django and I would like to understand what is the difference between a python script run in shell and Python script run in django web server? I created a python script which is in charge to scrape data from a website. For that, I use a rotating proxy and a very similar website header. It works very well. However, when I set this script in a Django app, it does not work and the website detects a bot and my direct IP. Everything is enacted but I don’t understand why is it difficult to scrap from a django webserver. Do you have an idea of my problem? -
Vue files not deploying properly with django backend
Vue/Django app deployed to Heroku. Everything works great on local machine in development. On Heroku domain the app and all django templates load fine, only issue is that no vue components render. See here: [https://brainteasers.herokuapp.com/anagram-game/] In chrome dev tools I see "(failed)net::ERR_CONNECTION_REFUSED", or simply "(failed)" for the vue specific files. The Request URL: http://localhost:8080/js/chunk-vendors.58fb68d0.js My directory structure: static (backend) ├── css ├── dist (vue build files output here) │ ├── css │ └── js └── img vue-games ├── node_modules ├── public ├── src │ ├── components │ ├── app.vue │ ├── main.js │ └── router.js ├── package.json └── vue.config.js My vue.js.config: module.exports = { publicPath: 'http://localhost:8080', // The base URL where your app will be deployed outputDir: '../static/dist', // The path for where files will be output when the app is built indexPath: '../../templates/_base_vue.html', // The path for the generated index file configureWebpack: { devServer: { devMiddleware: { writeToDisk: true } } } }; The request for the vue files appear to go through my publicPath at 'http://localhost:8080' , and my best guess is this is my issue. I tried changing publicPath to the name of my domain, no luck. As a beginner I'm still struggling with fully understanding the … -
Python tox in Django
I'm using Visual Studio Code. I downloaded a GitLab project to run it and I cloned it from GitLab to Visual Studio Code. The main issue is running the proyect in localhost:8000, it is a Django proyect but there isn't any manage.py file. It has this tox.ini file: [tox] envlist = py3 [testenv:run] usedevelop = true deps = commands = 12apps runserver [testenv] usedevelop = true deps = pytest pytest-cov flake8 mypy django-stubs pytest-django commands = pytest --cov=src/twelveapps --cov-report=term --cov-report={env:COV_REPORT_TYPE:html} {posargs} flake8 src/twelveapps tests mypy src/twelveapps [coverage:run] branch = True [coverage:report] exclude_lines = pragma: no cover raise NotImplementedError [flake8] per-file-ignores = src/twelveapps/**/migrations/*.py:E501 [pytest] norecursedirs = tests/helpers DJANGO_SETTINGS_MODULE = test_settings I talked to the GitLab proyect admin and he told me to follow this steps in the terminal: tox -e run --notest mkdir .tox/run/var .tox/run/bin/12apps migrate .tox/run/bin/12apps loaddata tmp/fixtures.json tox -e run Please, give me the steps I have to follow to run this proyect in localhost (8000). Thanks. Obviously I installed tox and I have a python version which the proyect supports (3.10). The first step doesn't work (it gives me the following error: tox run: error: argument -e: expected one argument) -
Is it possible to force users to go through OTP before accessing the password reset form in Django?
path('PassChangeForm/',views.PassChangeForm, name="PassChangeForm" ), i don't want user type PassChangeForm in the URL bar of the browser, and they got PassChangeForm page, They must attempt previous page before accessing this page Suppose I have 2 Functions in my views.py the first function is to enter OTP and the second function is to get the password reset form I just want, User doesn't access that password reset form directly (like type url name or url in the URL bar of the browser). They must attempt the previous page which is Entering OTP and then they got a form of password reset. -
Unable to Login Django Admin
I'm unable to access the admin panel after deploying my Django project on an Ubuntu server using nginx and gunicorn, but wrong password is authenticated on admin panel still on entering correct details it reloads and shows admin panel login page again HTTPS SETTINGS SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True HSTS SETTINGS SECURE_HSTS_SECONDS = 3153600 SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SESSION_ENGINE = 'django.contrib.sessions.backends.db'