Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static Files not working on PythonAnywhere - but working on local server
I'm deploying My web app on Pythonanywhere. After deployment, static files are not shown on it. While StaticFiles are working fine on Local Server. Lets just say staticfiles contain an image which is shown on Local Server on Home Page but doesn't show on pythonanywhere after deploying. What could be the issue? I tried adding static folder in each of my app, also as a global folder. Also, configured it on settings.py correctly as well. STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / 'static', ] Here's the link to my website: http://syedhamza10.pythonanywhere.com/ It is supposed to show a logo along with The Vision Realtor -
My django-server doesn't find my CSRF token
CORS related: CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:8000', 'http://127.0.0.1:8001', 'http://localhost:3000'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False CSRF_HEADER_NAME = "X-CSRFToken" CORS_EXPOSE_HEADERS = [ 'Content-Type', 'X-CSRFToken' ] My react-code: const fetchToken = async () => { try { const getTokenApiUrl = UrlApi + `/payment/`; const response = await fetch(getTokenApiUrl); const jsonData = await response.json(); setCsrfToken(jsonData.token) } catch (error) { console.error('Feil ved henting av data:', error.message); } }; Cookies.set('X-CSRFToken', csrfToken, { expires: 7}); const response = await fetch(sendPayementUrl, { method: 'POST', // Angi metoden til POST headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken' : Cookies.get('X-CSRFToken'), }, My views.py code: @csrf_protect def initializePayment(request): if request.method == 'GET': data = { 'token' : None } data['token'] = get_token(request) print(data) return JsonResponse(data, status=200) elif request.method == 'POST': received_token = request.headers.get('X-CSRFToken') # Hent token fra headeren print(received_token) try: data = json.loads(request.body) except Exception as e: print("Fikk ikke hentet data fra request") else: print("Data:", data) print("Sukess") return JsonResponse({'message': 'Dine data ble behandlet riktig.'}) else: return JsonResponse({'error': 'Noe gikk galt'}) The POST-request is accepted by the CORS, but django tells me that "Forbidden (CSRF cookie not set.)". I can see by my eyes, that the token is send to the frontend when it reloads, placed in the cookies-storage by my code in … -
How to upload a Django project to Hostinger
Someone know how can I post a Django project on Hostinger, I have tried a lot of things and I can't do it, do I need a VPS and a Host, or only one, and how can I post it?, and also I made my project with html pages I expect that u can help me, all help is welcome. -
Django form using DateTimeRangeField will not validate
When trying to check if the form is valid using .is_valid(), I get AttributeError: 'list' object has no attribute 'strip' for my DateTimeRangeField. I am using RangeWidget(forms.SplitDateTimeWidget(date_attrs={"type": "date"}, time_attrs={"type": "time"},),), with postgres db. I switched the backend from sqlite3 to postgres so I could use the DateTimeRangeField and the debugger shows the correct information in the POST request. Do I need to switch my datetimerange column/field into two columns, datetime_start and datetime_stop? Or is there another way to validate that I have missed? Should I just separate out the range into a separate form and use a key to connect it to my current form? I would like to add the ability to add many time ranges in the same form in the future. -
drf-spectacular generate got multiple values for keyword argument 'context' error
Django 3.2/ DRF 3.14.0 When forming a page with api documentation, an error is observed in the console got multiple values for keyword argument 'context' Code sample class CustomBatchView(mixin.ListModelMixin, mixin.CreateModelMixin, VendorViewSetMixin): def_serializer(self, *args, **kwargs): context = {'request': self.request} if self.action == 'create': return BatchCreateSerializer(*args, context=context, **kwargs) elif self.action in ['update', 'partial_update']: return BatchUpdateSerializer(*args, context=context, **kwargs) else: return BatchSerializer(*args, context=context, **kwargs) The problem is that when Viewsets in DRF calls get_serializer, it passes context inside kwargs. So when I try to pass the context separately, there is a conflict. The reason why I need separate context attribute is because using this logic further in self.context.get('request') So if implement this if 'context' in kwargs: del kwargs['context'] inside get_serializer All work perfect. Such a problem does not arise with business logic. Only at the moment of forming API documentation. What can this be related to and how can it be fixed? -
After cmd python manage.py runserver, project is running but some options of admin panel is showing does not exist after clicking on it
`Environment: Request Method: GET Request URL: http://127.0.0.1:8000/account/profile/ Django Version: 3.1.14 Python Version: 3.11.5 Installed Applications: ['jazzmin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'administration', 'teacher', 'student', 'academic', 'employee', 'result', 'address', 'account', 'attendance'] Installed 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'] Traceback (most recent call last): File "C:\Users\hp\Envs\school_management_system\Lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\hp\Envs\school_management_system\Lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\VS Code Files\school_management_system-master\account\views.py", line 7, in profile profile = UserProfile.objects.get(id=request.user.id) File "C:\Users\hp\Envs\school_management_system\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\hp\Envs\school_management_system\Lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /account/profile/ Exception Value: UserProfile matching query does not exist. I expect to run the project. -
Django administration
I create superuser Django administration gives me an error when trying to login (Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.) It can be said that I checked almost every option, but still I could not login to Django administration. How can I solve this problem? 1.Delete database 2.I delete migrations AND etc. -
django is expecting DNS record content in ALLOWED_HOSTS
i have a django app deployed on northflank and i register the domain on namecheap and am using cloudflare for dns management, i added the domain to django's setting.ALLOWED_HOSTS ALLOWED_HOSTS = ['www.domain.com'] and also configured the domain on northflank and also configured the dns record on cloudflare usin g the dns configuration settings northflank provided Record type CNAME CNAME/ALIAS/APEX Record name www .domain.com Expected Record Content www.domain.com.t16j-p585.dns.northflank.app Current Record Content No record found everything is working fine but django keeps throwing this error: DisallowedHost Invalid HTTP_HOST header: 'www.domain.com.t16j-p585.dns.northflank.app'. You may need to add 'www.domain.com.t16j-p585.dns.northflank.app' to ALLOWED_HOSTS. its really confusing to see that django is expecting the dns record content to be added to the ALLOWED_HOSTS i have tried to flush the dns cache but i still get the error -
How to handle foriegn key in djanog user model, When I do not want admin user to have a foreign key?
My custom user model has forigen key info I want each user to have an acount in my app with some infomration(linked to the info model) But the admin user has no such account it only manages the user information I do not want admin user to have a foriegn key So if I set the defalut=null I get "NOT NULL constraint failed: app_myuser.info_id" Or if i set defualt=0 I get FOREIGN KEY constraint failed Please tell me the right way to handle this situation from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class info(models.Model): name = models.CharField(max_length=30) age = models.IntegerField(default=0) class MyUserManager(BaseUserManager): def create_user(self,username ,key,password=None): user = self.model(username=username) user.set_password(password) user.save(using=self._db) user.info = key return user def create_superuser(self, username, password=None): user = self.model(username=username) user.set_password(password) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) info = models.ForeignKey(info, on_delete=models.CASCADE ,default=None) objects = MyUserManager() USERNAME_FIELD = "username" def __str__(self): return self.username @property def is_staff(self): return self.is_admin -
If statement in Django Model related to an other model
I'm building a Django Python App and I am facing a problem. For some reason, I would like to implement a different price (Produit.PU_HT_WH) according to the customer (client) type (retailer or wholesaler (booleans). I would like to implement it to my models.py so that I don't have to changes Models.py (Produit) : class Produit(models.Model): id_Prod = models.CharField(max_length=200, null=True) EAN = models.IntegerField() PU_HT_WH = models.FloatField(null=True) denomination = models.CharField(max_length=200, null=True) def __str__(self): return self.id_Prod def PU_HT(self): if self.client.retailer: PU_HT= (self.PU_HT_WH/ 0.85) else : PU_HT = self.PU_HT_WH return PU_HT Models.py (Client) : class Client(models.Model): id_Client = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) nom_client = models.CharField(max_length=200, null=True) prenom_client = models.CharField(max_length=200, null=True) raison_sociale = models.CharField(max_length=200, null=True) retailer = models.BooleanField(default=False, null=True) def __str__(self): return self.nom_client My goal here is that I just have to replace every " {{prod.PU_HT_WH|floatformat:2}}€ " to " {{prod.PU_HT|floatformat:2}}€ " to display prices according to the customer. The website works only on @login_required so I would like that the customer only sees his price. I hope that I've been enough understandable ! Thanks for every tips that you could give me :) I've tried many ways but I always have an error on that line : if self.client.retailer : I don't konw if it … -
Autocomplete city field with yandex suggestView
I have an input field for the city. I need a drop-down list of cities to appear when I start entering a city. ONLY CITIES. <input type="text" name="city" id="city"> I have a js function, but it shows not only cities, but also regions and the like, but I only need cities function onLoad (ymaps) { var suggestView = new ymaps.SuggestView('city'); } It would also be nice to add an error when pressing a button if the user has not selected anything from the list Hepl please -
Django CheckConstraint failing
I'm creating a custom user-model where every user needs a company assigned, unless they are a superuser or staff. To accomplish this, I'm adding 3 CheckConstrains as seen below: class CustomUser(AbstractUser): ''' Custom User class, username and email are required. Company is required except for staff and super users ''' company = models.ForeignKey(Company, on_delete=models.PROTECT, null=True, blank=True) class Meta(AbstractUser.Meta): constraints = [ CheckConstraint( check=Q(is_superuser=False, is_staff=False, company__isnull=False), name="user_must_have_company", ), CheckConstraint( check=Q(is_staff=True, company__isnull=True), name="staff_cannot_have_company", ), CheckConstraint( check=Q(is_superuser=True, company__isnull=True), name="superuser_cannot_have_company", ), ] Desired behaviour is: Super-users and Staff users cannot have a company all 'normal' users need to have a company set. However, all initial conditions fail on the same CheckConstraint user_must_have_company. user = CustomUser.objects.create(username='staffuser', is_staff=True, company=None) IntegrityError: CHECK constraint failed: user_must_have_company company = Company.objects.create(name='Test') user = CustomUser.objects.create(username='normal_user', is_staff=True, company=company) IntegrityError: CHECK constraint failed: user_must_have_company user = CustomUser.objects.create(username='superuser', is_superuser=True, company=None) IntegrityError: CHECK constraint failed: user_must_have_company What am I missing? -
How to extract data from a URL fragment Django
Hi I'm trying to learn development by creating a web app that displays users top Spotify stats and so I'm trying to use supabase to login to Spotify however the redirect gives a URL in the form of: http://127.0.0.1:8000/callback/#access_token= I'm currently working using Django and because the data is in a URL fragment I cant access it using request.get. How would I go about extracting the data from the URL. -
How to delete a application of django on Docker?
I created a application for Django (name is accounts), but I want to delete it for a reason. I've used Docker. So in virtual environment, I just remove the account folder, and it works, but in docker mode, I get this error. even i down container but it isn't working -
Google OAUTH2 using django-socialauth
I have a django project in which i'm using django-social-auth to implement google and facebook. From the side it seems to work quite well as i've been able to register and login using it. However, as soon as i turn google API into production, i get an error of mismatch_url. In the credentials => Authorized redirect URIs i have this url: https://www.swimseekr.com/social-auth/complete/google-oauth2/ but when i try to login, google give me this error: which shows an http url: You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. If you're the app developer, register the redirect URI in the Google Cloud Console. Request details: redirect_uri=http://www.swimseekr.com/social-auth/complete/google-oauth2/ so if i go back to testing mode, and remove the 's' from http, and try to login, it works again. Anyone, can help me on this? Thank you. -
How to send ajax post request for a video file in Django?
I want to send an ajax post request to a django view for a video file. I am creating a simple page where the user could record his camera and audio. After the user stops recording, the recorded video file would then automatically be sent to a backend view where I would save it to the database. Here is my current template with javascript. <body> <video muted id="video" autoplay></video> <button id="btn">Start Recording</button> <button id="stopbtn">Stop Recording</button> <script src="script.js"></script> </body> <script> window.onload = function () { const parts = []; let mediaRecorder; navigator.mediaDevices.getUserMedia({ audio: true, video: true}).then(stream => { document.getElementById("video").srcObject = stream; document.getElementById("btn").onclick = function () { mediaRecorder = new MediaRecorder(stream); mediaRecorder.start(1000); mediaRecorder.ondataavailable = function(e) { parts.push(e.data); } } }); document.getElementById("stopbtn").onclick = function () { mediaRecorder.stop(); const blob = new Blob(parts, { type: "video/webm" }); // Create a FormData object to send the Blob const formData = new FormData(); formData.append("video_blob", blob); // Make the ajax call $.ajax({ url: '/save-video/', type: 'POST', success: function (res) { console.log("video uploaded successfully") }, data: formData, cache: false, contentType: false, processData: false }); } }; </script> And I want to send it to the following view. def save_video(request): if request.method == "POST" and request.FILES.get("video_blob"): uploaded_blob = request.FILES["video_blob"] … -
query to count reverse foreign fields and reverse manytomany field
In my application there are users and users can block each other. I want to save each action taken by a user. In an action, a user could perform multiple ban operations on other users. That is why the Action table has a user_list. Now I want to find the total number that other users target the specific user. For example User_5 was targeted by other users 8 times. models.py class BanMode(models.Model): ban_mode = models.CharField(max_length=10, blank=False, null=False) class CustomUser(models.Model): custom_name = models.CharField(max_length=96, blank=False, null=False) custom_id = models.IntegerField(blank=False, null=False) class Action(models.Model): taken_by = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=False, null=False) ban_mode = models.ForeignKey(BanMode, on_delete=models.PROTECT, blank=False, null=False) user_list = models.ManyToManyField(CustomUser, blank=False, null=False) Following code successfully finds the total number of actions on the user performed by other users (users not unique). CustomUser.objects.annotate(banned_by_count=Count('user_list', distinct=False)) However, I want to apply a filter. I want to find the total number of actions (for example actions whose ban_mode is 1) on the user performed by other users (users not unique). This query does not work. CustomUser.objects.annotate(banned_by_count=Count('user_list', distinct=False, filter=Q(action__ban_mode__ban_mode="BAN"))) -
i am trying to upload file with arabic name in django upload file
i am trying to make upload file button upload file in Arabic named with form = UploadFileForm(data=request.POST, files=request.FILES) but when i select Arabic named file it does not add it without giving any error my views.py def upload_file(request): if request.method == 'POST': form = UploadFileForm(data=request.POST, files=request.FILES) if form.is_valid(): portfolio=form.save(commit=False) portfolio.user = request.user portfolio.file= form.filename.decode('utf8') portfolio.save() return redirect('upload_file') else: form = UploadFileForm() files = UploadedBooksFile.objects.all() return render(request, 'upload_file.html', {'form': form, 'files': files}) def download_file(request, file_id): uploaded_file = UploadedBooksFile.objects.get(pk=file_id) response = HttpResponse(uploaded_file.file, content_type='application/force-download') response['Content-Disposition'] = f'attachment; filename="{uploaded_file.file.name}"' return response -
Django Read more, Read less text
I have this implementation of Read more - Read less in Django: HTML: <p><strong>Overview:</strong> <span class="overview">{{ game.overview|default:"N/A"|slice:"300"}}</span> {% if game.overview|length > 300 %} <span class="dots">...</span> <span class="more" style="display: none;">{{ game.overview|default:"N/A"|slice:"300:" }}</span> <button class="read-button" onclick="readMore(this)">[Read more...]</button> {% endif %} </p> JavaScript: function readMore(button) { var parent = button.parentNode; var dots = parent.querySelector(".dots"); var moreText = parent.querySelector(".more"); if (dots.style.display === "none") { dots.style.display = "inline"; button.innerHTML = "[Read more...]"; moreText.style.display = "none"; } else { dots.style.display = "none"; button.innerHTML = "[Read less...]"; moreText.style.display = "inline"; } } My problem is that when the text get's sliced inside a word like in this example: Created in Unity, and designed to be played in-browser, players make a series of moral and dialogue choices within each chapter, before being presented a larger question at the end of eac ... [Read more...] When I am clicking the [Read more...], the output is like this and the word 'each' get's separated where the slice occurred.: Created in Unity, and designed to be played in-browser, players make a series of moral and dialogue choices within each chapter, before being presented a larger question at the end of eac h chapter, asking what should happen next in the story. … -
Creating a small website using Django and python
I need someone to create a website in Python using Django. I need at least 3 pages and one database driven component. I need a polls app where users can login, authenticate and vote. (This has to be done in Python using Django (models.py, views.py, urls.py etc)) I tried to create it myself however i ran into error after error after error and i need this to be done properly. -
When a Django custom field accepts a class-type parameter, it causes infinite AlterField migrations
I'm trying to define a custom field in Django, and I wanted to initialize it with a helper object. The field class receives the helper object an init parameter, and stores internally. Unfortunately, this results in an odd consequence: As soon as any model makes use of this field, Django considers it to always be in an altered state, and therefore to always have changes requiring new migrations. Is there any way to solve this, or is it just a blanket rule that a custom field can only be initialized with primitives? Walkthrough and Detail I'm defining a simple custom Django field, as follows: class FooField(CharField): def __init__(self, foo : Foo, *args, **kwargs) -> None: self.foo : Foo = foo super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs["foo"]=self.foo return name, path, args, kwargs Where Foo is a simple object, e.g.: class Foo: def __init__(self, n): self.n=n def __repr__(self): return f"Foo({self.n})" Now I add this new field type to a model (having written supporting class FooSerializer and method default_foo(), to support migrations -- supporting code below): from django.db import models from .utils.foo_field import Foo, FooField, default_foo fooA= Foo(1) fooB = Foo(2) class MyModel(models.Model): n1 = models.IntegerField() # preexisting … -
Type hinting with cyclic dependency
I am building a Django/DRF application and have the following models: class Company(models.Model): some_field = models.TextField() some_method(user): pass class User(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE) The method some_method of the company model uses a user as input. The code itself works fine. However, how can I type hint this parameter to get IDE support / code completion in PyCharm? Declaring it like some_method(user: User): yields an "Unresolved reference" error makes sense since the user class is declared further down in the file. Is there a workaround or do I have to live without code completion? -
i want two pass two context in index.html file
my views.py from django.shortcuts import render, HttpResponse,redirect from .models import * # Create your views here. def index(request): products=Product.objects.all() params={'product':products} categories=Category.objects.all() category={'category':categories} return render(request,'index.html',params,category) i am creating an ecommerce website on django and i want to pass two context in index.html one is product and one is category but after doing this the index.html is not working -
Django MySQL Backup in sql file format
I have project in Django and Database in MySQL and I want Backup of DB every week so that If anything goes wrong with server or database so I can use that DB, but unfortunalty I didn't find any solution that can help me. I'm trying to get backup of database every week, I have MySQL database and I have also tried using 'django-dbbackup' but it's not giveing output as expected in '.sql' format. -
Better way to query a ManyToManyField in Django
Assume the model below: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) Is there a better way to get the same result as foo? foo = Article.objects.filter(publications=1).filter(publications=2).filter(publications=3).filter(publications=4).filter(publications=5) I tried bar = Article.objects.filter(Q(publications=1) & Q(publications=2) & Q(publications=3) & Q(publications=4) & Q(publications=5)) and baz = Article.objects.filter(publications__id__in=[1, 2, 3, 4, 5]) But they are not the same as foo