Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Trying to install pipenv install mysqlclient (There are incompatible versions in the resolved dependencies)
I am trying to follow a django course my mosh and I am trying to install the pipenv install mysqlclient however I am unable to install and keep having this error.. (storefront) (base) tanweijie@localhost1-6 storefront % pipenv install mysqlclient Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing mysqlclient... Resolving mysqlclient... Adding mysqlclient to Pipfile's [packages] ... ✔ Installation Succeeded Pipfile.lock (be1d61) out of date, updating to (f41128)... Locking [packages] dependencies... Building requirements... Resolving dependencies... Resolving dependencies... ✘ Locking Failed! ⠹ Locking... ERROR:pip.subprocessor:[present-rich] Getting requirements to build wheel exited with 1 [ResolutionFailure]: File "/Users/tanweijie/opt/anaconda3/lib/python3.9/site-packages/pipenv/resolver.py", line 704, in _main [ResolutionFailure]: resolve_packages( [ResolutionFailure]: File "/Users/tanweijie/opt/anaconda3/lib/python3.9/site-packages/pipenv/resolver.py", line 662, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: File "/Users/tanweijie/opt/anaconda3/lib/python3.9/site-packages/pipenv/resolver.py", line 642, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: File "/Users/tanweijie/opt/anaconda3/lib/python3.9/site-packages/pipenv/utils/resolver.py", line 1167, in resolve_deps [ResolutionFailure]: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( [ResolutionFailure]: File "/Users/tanweijie/opt/anaconda3/lib/python3.9/site-packages/pipenv/utils/resolver.py", line 948, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "/Users/tanweijie/opt/anaconda3/lib/python3.9/site-packages/pipenv/utils/resolver.py", line 690, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your … -
Celery task not getting aborted using AbortableTask
I have a long running celery task. I want to terminate/stop/revoke that task if user hits /cancel route. I used multiple ways of doing this, but none of them worked. I am using RabbitMQ as a message broker. I have defined a view called "cancel_task" which receives "task_id" from the request parameters. But, my task is not aborted despite it getting request properly. Can somebody tell me how to terminate/cancel/stop this task? Even after cancelling task, this task does not stop executing. I referred to this document - Abort celery task example task.py views.py Imports in views.py Imports in task.py Output - -
Django is not running. Django not found error occurs
python3 Python 3.9.6 (default, May 7 2023, 23:32:44) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. import django django.file /Users/dc/Library/Python/3.9/lib/python/site-packages/django/init.py' django also works I installed Django from pip3 in Mac m1 but it is not running your text -
Hit DB only once while filtering a queryset in Django-rest-framework
I am filtering a model under some conditions say, qs = Model.objects.filter(category=value). I am send this queryset as a response using ListModelMixin. class ModelViewset(ListModelmixin): def get_queryset(self): return Model.objects.filter(category=value) The select statement was running n times for n items which seems reduntant, Somehow I want to hit db only once and use them as Response. I tried list, but it has too much overhead and has slowed down the performance. Is there any way to acheive this by not using list, bool or remaining things as they will also execute each items which results in n queries for n items in Model. -
Why can I not deploy django project with elastic beanstalk?
I have created a zip file with all my programs and it runs well locally. For some reason elastic beanstalk gives several errors when I deploy my zip file. Such as: "Warning: Configuration files cannot be extracted from the application version my_tennis_club2. Check that the application version is a valid zip or war file." "Error: The instance profile aws-elasticbeanstalk-ec2-role associated with the environment does not exist." "Error: Failed to launch environment" I followed the tutorial https://www.w3schools.com/django/django_deploy_eb.php where I always got the same result as the tutorial up until I was gonna upload the zip file containing my entire project to elastic beanstalk -
Nested serializer get_or_create unique constraint validation error
I Have a UserModelSerializer: class UserModelSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'date_joined', 'is_active', 'is_verified', 'is_superuser', 'is_staff', 'is_hidden', 'created_date'] read_only_fields = ['id', 'date_joined', 'is_active', 'is_verified', 'is_superuser', 'is_staff', 'is_hidden', 'created_date'] and a UserBanModelSerializer: class UserBanModelSerializer(ModelSerializer): user = UserModelSerializer() class Meta: model = UserBan fields = ['id', 'user', 'until', 'reason', 'description', 'created_date'] read_only_fields = ['id', 'created_date'] def create(self, validated_data): user_data = validated_data.pop('user') user, created = User.objects.get_or_create(**user_data) user_ban = UserBan.objects.create(user=user, **validated_data) return user_ban I want my representation to have complete User data and also i want the frontend developer to be able to send the represented data back to server without any problem(if I only add UserModelSerialzer to to_representation method of UserBanModelSerializer frontend developer needs to send user id instead of the whole user data But when I use is_valid method on serializer I get this exceptions: "username": [ "A user with that username already exists." ], "email": [ "A user with that email already exists." ] I dont want to create a User when I want to create a UserBan I only want it to be created if the User is not found -
How to connect Python and Next.js?
I have been working on django/next.js project. but I'm stuck in connection part between python and next.js. as I'm full stack developer, I have experienced to connect between laravel and react. but this case is first to me. please help me so that I can accomplish as soon as possible. I was just building basic python project. I wanna know detail steps because this is urgently task. -
What are the main differences between django and rest framework?
i have used rest framework, but i didn't know the difference between django and rest framework either. main difference between django and rest framework. i need the exact differences between django and rest framework. #django, #restframework. -
Editing or moving site-packages in django
In django ive installed the django-two-factor-auth package through my virtual environment, and it is installed in /env/Lib/site-packages/. What is best practice of editing such a package? If for example i want to edit the urls (or the views)? Do i move or copy the packages from the env/ into my django project as an app? My existing project setup is: /env/ /project/ -/app1/ -/app2/ As im quite new to django, im looking for best practices before i start making my own judgements. As my /env/ is not tracked by git, i cant imagine i should be editing the package directly within. I tried copying the entire django-two-factor-auth package into my project, but im not sure how to register it correct in settings.py (im also wary of having a copy of the same library in both /env/ and /project/). -
How to accept Ngrok connections on Docker Django
I'm trying to create tunnel connection and accept Stripe payment success requests. docker-compose.yml: ... django: ... ports: - '8000:8000' ngrok: container_name: ecommerce_ngrok_ctnr image: ngrok/ngrok:latest restart: unless-stopped command: start --all --config /etc/ngrok.yml ports: - 4040:4040 depends_on: - django volumes: - ./ngrok/ngrok.yml:/etc/ngrok.yml ngrok.yml: version: 2 authtoken: *** tunnels: django: proto: http addr: localhost:8000 inspect: true The error code is: ERR_NGROK_8012 dial tcp 127.0.0.1:8000: connect: connection refused -
Dockerized Django application cannot connect to native PostgreSQL. Ubuntu 22.04.3 DigitalOcean
On my DigitalOcean droplet, my running Django docker-compose container can easily connect to PostgreSQL if it's also a container, which is not the preferred way for me. I have tried many approaches to connect to my database from django conainer. First, I edited postgresql.conf: listen_addresses = '*'. Also I added my droplet's ip address to pg_hba.conf and even allowed all connections: host all all 0.0.0.0/0 md5 host all all 172.28.0.2/16 md5 Also I allowed all connections to 5432 port in firewall. It's for testing though. OpenSSH ALLOW Anywhere 80/tcp ALLOW Anywhere 443/tcp ALLOW Anywhere 5432 ALLOW Anywhere 5432/tcp ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 443/tcp (v6) ALLOW Anywhere (v6) 5432 (v6) ALLOW Anywhere (v6) 5432/tcp (v6) ALLOW Anywhere (v6) In my django settings, I am setting my droplet's ip address as database host, and the port is 5432. What did I miss? What could be the reason? I've read that /16 in 172.28.0.2/16 is likely to be the reason, because you can set it to be 32 or 16 or even 8 and it's said to vary depending on the droplet's ip. I tried some of them but it didn't really help. I always … -
Render Serialized data in django rest framework
I'm new to django and web development and wanna know how to render html with serialized data which i use for my api's here's my files: Views.py class IngredientsViewSet(ModelViewSet): http_method_names = ['get','post','patch','delete','options','head'] permission_classes = [isAdminOrReadOnly] queryset = Ingredients.objects.all() def get_serializer_class(self): if self.request.method in ['POST','PATCH','delete']: return IngredientCreateSerializer return IngredientSerializer Models.py class Ingredients (models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) unit_price = models.DecimalField( max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField(validators=[MinValueValidator(0)]) last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT, related_name='products') def __str__(self) -> str: return self.title Serializer.py class IngredientSerializer (serializers.ModelSerializer): class Meta: model = Ingredients fields = ['id','title','unit_price','description','collection'] class IngredientCreateSerializer (serializers.ModelSerializer): class Meta : model = Ingredients fields = ['id','title','slug','unit_price','description','collection','inventory'] class CollectionSerializer(serializers.ModelSerializer): # featured_ingredient = IngredientSerializer() class Meta : model = Collection fields = ['id','title','featured_ingredient'] I want to render a html file and pass my Ingredient model data to it. -
How to return to fetching if the route needs @login_required, after logging the user in
I am building a project using Django as a backend and JavaScript for the client-side, one of the implementation for this project is a like button, sending the data if the user clicked the like button. fetch(`/like/${like.dataset.post_id}`, { method: 'PUT' }) .then(response => { if (response.redirected) { window.location.href = response.url; return; } else { return response.json()} }) .then(message => { // error do nothing if (message.error) { // show the error to the user ... console.log(message.error); } else { if (message.liked) { like.className = "liked like"; } else { like.className = "not-liked like"; } // get the html tag where the number of like is inserted. const text = like.parentElement.querySelector('.like-number'); // then insert the number inside that text.innerHTML = message.like; // convert the number Ex. 10000 => 10K changeNumber(text); } }) .catch(error => console.log(error)) This is the route where it fetch the data @csrf_exempt @login_required(login_url='/login') def like(request, post_id): if request.method != 'PUT': return JsonResponse({"error": "Method not found!"}, status=405) # Get the post post = Post.objects.get(pk=post_id) # remove the user from the like list if post.like.contains(request.user): post.like.remove(request.user) post.save() like = post.like.all().count() # return message, no of like and boolean expression return JsonResponse({"success": f"{request.user} Liked post by { post.user }", "like": like, …