Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Adding an element to a ManyToManyField in Django not saved?
While I was making one of my first projects on Django, I had to create two models. One of them, Image, has a field tags which is a ManyToManyField referring to the other model, Tag. I wanted to add elements to the tags field with a post_save signal. No problem occur during this process (in particular, the elements I want to add exist), but at the end no element is added. Here is a snipplet of the models.py I've written so far : # (Importing the modules ...) class Image(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="media/") tags = models.ManyToManyField("Tag", related_name="images", blank=True) class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) def __str__(self): return self.name @receiver(post_save, sender=Image) def create_tags(sender, instance, created, **kwargs): if created: print(f"Before : {instance.tags.all()}") tag = Tag.objects.first() instance.tags.add(tag) instance.save() print(f"After : {instance.tags.all()}") When I add an element through the admin panel, the following is printed : Before : <QuerySet []> After : <QuerySet [<Tag: myfirsttag>]> But if I check the freshly added element, no tag is selected. Could you please help me figuring out what I am doing wrong ? Thanks in advance and have a nice day ! - 
        
Aborting the task is not stopping the sub process created by celery task
From Django, I'm starting the celery task which will trigger the sub process @app.task(bind=True, base=AbortableTask) def execute_script(self, data: dict): script = data.get("input") if script and script in get_scripts(): # Executing related script script_path = os.path.join(settings.CELERY_SCRIPTS_DIR, script) process = subprocess.Popen( f"python {script_path}", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) time.sleep(8) error = False if process.wait() == 0: # If script execution successful logs = process.stdout.read().decode() else: logs = process.stderr.read().decode() error = True return {"logs": logs, "input": script, "error": error, "output": ""} To abort the task, I use below code def cancel_task(request, task_id): result = TaskResult.objects.get(task_id=task_id) abortable_result = AbortableAsyncResult(result.task_id, task_name=result.task_name, app=app) if not abortable_result.is_aborted(): abortable_result.revoke(terminate=True) time.sleep(1) return redirect("home") After aborting the task, celery task is stopped by Subprocess is still running. Can you guide to solve this problem. - 
        
django post mehod while insert data
in an django project, I want to insert a title, category, image to the backend. On that thing the if statement is not working in while run the program. This is my form <form action="" enctype="multipart/form-data" method="POST" class="p-4"> {% csrf_token %} <div class="row"> <div class="col-md-12 mb-3"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control p-3" placeholder="title" name="title"> </div> </div> <div class="col-md-12 mb-3"> <div class="form-group"> <label for="category">Category</label> <select id="category" class="form-control form-select p-3" name="category"> <option value="none">Select a category</option> {% for opt in category %} <option value="{{ opt }}">{{ opt }}</option> {% endfor %} </select> </div> </div> <div class="col-md-12 mb-3"> <div class="form-group"> <input type="file" class="form-control p-3" name="image"> </div> </div> <div class="mt-3 col-md-12"> <button class="btn btn-primary" style="width: 100%;">Upload</button> </div> </div> </form> and This is my view def add(request): if request.method == 'POST': print("POST request received") title = request.POST.get('title') cat = request.POST.get('category') image = request.FILES.get('image') print(title, cat, image) else: print("GET request received") categories = addcategory.objects.all() context = { 'category': categories, } return render(request, 'add.html', context) The terminal output will be GET request received [07/Apr/2023 05:49:28] "GET /add/?csrfmiddlewaretoken=il3U1rnxUl5217Wud9i1kX6TfMNk7uOoQDfUYxYb8UlYZIczG4Uz4OgR6nib4yrF&title=veg&category=Food&image=food.jpeg HTTP/1.1" 200 4672 I want to print the "POST request received". - 
        
How can i auto fill a field and make it readonly in django admin
I want the created_by field to be filled automatically with the email of the current admin who is logged in and it should be read only field I tried this: admin.py from django.contrib import admin from support.models import Ticket class TicketAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields['created_by'].initial = request.user return form def save_model(self, request, obj, form, change): if not obj.created_by: obj.created_by = request.user super().save_model(request, obj, form, change) admin.site.register(Ticket, TicketAdmin) I'm still able to edit the field and able to select other email addresses from a dropdown model.py class Ticket(models.Model): PRIORITY = ( ("High", "high"), ("Medium", "medium"), ("Low", "low") ) subject = models.CharField(max_length=255) body = models.TextField() priority = models.CharField(max_length=10,choices=PRIORITY) created_by = models.ForeignKey(Users, on_delete=models.CASCADE) How can I implement it? - 
        
Can I use set operation in django template(3.x)?
Here's the code I am trying to shorten: {% url 'accounts:signup' as signup %} {% url 'accounts:login' as login %} {% url 'accounts:update' as update %} {% url 'accounts:password' as change_password %} {% if request.path == signup or request.path == login or request.path == update or request.path == change_password %} document.querySelector('h6').textContent = '' {% endif %} But can I use set operation as in Python, such as: {% url 'accounts:signup' as signup %} {% url 'accounts:login' as login %} {% url 'accounts:update' as update %} {% url 'accounts:password' as change_password %} {% if request.path in {signup, login, update, change_password} %} document.querySelector('h6').textContent = '' {% endif %} The code above gives me TemplateSyntaxError. So does {% if request.path in signup, login, update, change_password %} and {% if request.path in "signup, login, update, change_password" %} doesn't work. Passing boolean value True from view functions and using it in the if tag works, but it seems inefficient: it is hard to maintain. {% if my_var %} document.querySelector('h6').textContent = '' {% endif %} How can I make it more efficient? Either in template or view level. - 
        
How To Login into Django admin from React JS Frontend Login Page
I want to type the username and password in frontend and if the credintials are right redirect to django admin while being logged in and see the models and things inside django admin. I created an API that enables users to log in and authenticate and log in to Django admin. It functions properly when I send a post request through rest_framework. However, when attempting to send a request through the frontend and redirect to django admin it fails to work and asking for the username and password. `class LoginView(generics.GenericAPIView): # authentication_classes = [BasicAuthentication] serializer_class = LoginSerializer def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) username = serializer.validated_data['username'] password = serializer.validated_data['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return Response({'message': 'Logged in successfully'}, status=status.HTTP_200_OK) else: return Response({'message': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST)` - 
        
Pagination and Filtering at the same time
views.py class CourseListView(ListView): model = Course context_object_name = "courses" template_name = "academics/course_list.html" paginate_by = 6 def get_queryset(self, **kwargs): q = self.request.GET.get('q') if self.request.GET.get('q') != None else '' return Course.objects.filter(major__major__icontains=q).order_by('course') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = "Our Courses" context['majors'] = Major.objects.all() return context academics/course_list.html ... <div class="col-12"> <!-- courses by major --> <ul class="list-inline text-center filter-controls mb-5"> <li class="list-inline-item m-3 text-uppercase active"> <a class="text-dark" href="{% url 'course-list' %}">All</a> </li> {% for major in majors %} <li class="list-inline-item m-3 text-uppercase"> <a class="text-dark" href="{% url 'course-list' %}?q={{major.major}}">{{major.major}}</a> </li> {% endfor %} </ul> </div> ... <div class="d-flex justify-content-center flex-nowrap"> {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number}}">Next</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a> {% endif %} {% endif %} </div> ... At the moment, I can filter all courses by … - 
        
How to fix "Some cookies are misusing the recommended “SameSite“ attribute" warning react django axios
I have this axios function that i use to login a user (dajngo backend) then retrieving the JWTtoken as a cookie. const loginRequest = (values) => { axios .post( "/api/login", { email: values.email, password: values.password, },{ withCredentials: true, } ) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); }; Here is the django view @api_view(['POST']) def LoginView(request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'jwt': token } return response The cookie output (Firefox) Then i get this warning I tried adding SameSite: 'None' or SameSite: 'Lax' to the function { withCredentials: true, headers: { 'Content-Type': 'application/json', }, SameSite: 'None', } But i get this error - 
        
CREATE TABLE AS SELECT in Django
I would like to run a CTAS query in django with a postgres database. In other words, I'd like to create a table from queried results. I'd like to create a new table using columns from multiple models so when I use it in a view, I don't have to run multiple queries, I can just use the new table. It would be temporary and created every time the view is called, so as the data updates, the table generated is up to date as well. I know Django does not have any built in functionality for that but does anyone know how to do something similar? Currently I am using one table and having to do a filter function on every row to combine multiple tables of data. I am using django version 4.1.5 and postgres backend. - 
        
Encrypt python Scripts for django and flask
I am working on developing two applications for a client using Flask and Django frameworks. However, I am seeking guidance on encrypting my Python script to ensure the client cannot access my code. Furthermore, I am planning to deploy the applications using Docker Compose with Nginx and Postgres.I would appreciate any feedback on whether this deployment approach is optimal or if there is a better alternative. - 
        
Django urls.py: RecursionError: maximum recursion depth exceeded while calling a Python object
I want to make a urls that leads to my urls.py in my app, but it gives me a RecursionError every time. This is my code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('ptr.urls')) ] And if you need the full traceback, here it is: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/checks/urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/checks/urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/checks/urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) [Previous line repeated 987 more times] File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/checks/urls.py", line 62, in _load_all_namespaces namespaces = [ File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/checks/urls.py", line 65, in <listcomp> if getattr(url, "namespace", None) is not None RecursionError: maximum recursion depth exceeded while calling a Python object - 
        
Django: 'QuerySet' object has no attribute 'product_obj' when running for loop
I am trying to loop through a queryset, get the product object and remove the qty of items ordered from the product's stock amount. This is how my model Looks class CartOrderItem(models.Model): order = models.ForeignKey(CartOrder, on_delete=models.CASCADE) product_obj = models.ForeignKey(Product, on_delete=models.CASCADE) qty = models.IntegerField(default=0) ... date = models.DateTimeField(auto_now_add=True, null=True, blank=True) And this is how it looks in the admin section This is how i ran the forloop @login_required def PaymentSuccessView(request): ... order_items = CartOrderItem.objects.filter(order=order, order__payment_status="paid") for o in order_items.product_obj: print(o.title) # print all the products title print(o.stock_qty) # print the stock qty from the Product model # I want to substract the CartOrderItem's qty from the Product's stock qty It then shows this error that says 'QuerySet' object has no attribute 'product_obj' This error is saying that the queryset for the CartOrderItems models does not have an attribute "product_obj", but i clearly have a 'product_obj' field in my CartOrderItems This is how i wanted to substract the items qty from the product stock qty, i am not sure this would work and i haven't tried it because the error above would not allow me for o in order_items.product_obj: o.product_obj.stock_qty -= o.qty o.save() - 
        
how can i fix this issue in django script project
I'm working on python/Django project and I'm having this error,, please advice tried several solutions none of them are correct Problem statement: int() argument must be a string, a bytes like object or number, not 'NonType'``` [text](https://stackoverflow.com)[problem statement](https://github.com/mohammedabdelhafiz/Django-rar/blob/master/_3_showtime_script.py) the script of the code on my github account couldn't upload it https://github.com/mohammedabdelhafiz/Django-rar/blob/master/_3_showtime_script.py - 
        
Please I am not figure out that problem on installation packages
I successfully activated the venv and the pip not working on installing packages Please Help! I run pip install django and nothing happens - 
        
why i cant create user and no do i gets any error in django?
when i am trying to create a user , it does not shows any message/error nor its creating a user , please help me .(https://i.stack.imgur.com/bKhMf.jpg)(https://i.stack.imgur.com/Kx7bt.jpg)(https://i.stack.imgur.com/I3svX.jpg) i should have been able to create new user but ..... - 
        
I want to write a validator for(options.dir) instead of using(os.path.abspath)
def run(self): for filename in glob.glob(os.path.abspath(options.inputdir) + '/PQRS_*.dat'): if self.options.verbose: print filename.split('/')[-1] for row in self.readfile(filename): self.loadline(row)`enter code here So i want to use validator instead of os.path.abspath, I am new to python kindly let me know how to validation (options.inputdir) with a function def run(self): for filename in glob.glob(os.path.abspath(options.inputdir) + '/PQRS_*.dat'): if self.options.verbose: print filename.split('/')[-1] for row in self.readfile(filename): self.loadline(row) - 
        
Make Virtual Enviroment in Python [closed]
I can't make virtualenv. Help me, please "mkvirtualenv: command not found" I hope everyone can solve it - 
        
Django Rest Framework - Custom error messages - Serializer vs. Model
:) Hello! I'm currently facing a problem that I am not being able to solve by searching the documentation or other questions, if someone can help I would be very grateful. The problem is relatively of simple: I am adding custom messages for validation errors that come up when posting a new object, but I'd like to do it in one place only: inside model OR inside serializer. For the sake of this example and my use case, I am talking only about unique and max_length validations. Defining error_messages=errors_dict inside the model fields currently only changes the unique validation error message, displaying the default for max_length. The opposite happens when I set it inside the serializer, using extra_kwargs inside Meta. It only changes the max_length validation error message. Does anyone know what I am missing here? Is it possible to set the error_messages in only one place? Thank you! Here are some code snippets, it it helps: errors in the below examples is the same dictionary, containing both keys (unique and max_length). Inside Model, working only for the unique validation: class User(AbstractUser, SplintModel): (...) cpf = models.CharField('CPF', blank=False, max_length=11, unique=True, error_messages=errors) Inside Serializer, working only for the max_length validation: class … - 
        
user not creating in django
I am working on an inventory management based project and i have downloaded a template "sneat". I have set all its urls according to django and also creates a signup and login views. When user(any person who manages store) sign up it will go to login page. But user is not created i have tried code but when i check on database user is not created. My 'signup.html' file is... <form id="formAuthentication" class="mb-3" action="Login" method="POST"> {% csrf_token %} <!--{{ form.as_p }}--> <div class="mb-3"> <label for="username" class="form-label">Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Enter your username" autofocus required /> </div> <div class="mb-3"> <label for="email" class="form-label">Email</label> <input type="text" class="form-control" id="email" name="email" placeholder="Enter your email" required /> </div> <div class="mb-3 form-password-toggle"> <label class="form-label" for="password">Password</label> <div class="input-group input-group-merge"> <input type="password" id="password" class="form-control" name="password" placeholder="&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;" aria-describedby="password" required /> <span class="input-group-text cursor-pointer"><i class="bx bx-hide"></i></span> </div> </div> And my signup views are... def Signup(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') # Check all required fields are filled if not username or not email or not password: messages.error(request, 'Please fill all required fields.') return redirect('Signup') # Check email is not already in use if User.objects.filter(email=email).exists(): messages.error(request, 'Email already exists.') return redirect('Signup') # … - 
        
Migrating database to VPS server from django project
I am wanting to be able to migrate my database from my django project to my VPS so I can access it from all my machines. I am wondering what I should be using as the hostname as I keep getting an error if I use the servers IP address: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2002, "Can't connect to server on 'xxxx.instance.snappyhost.co.uk' (10061)") I have successfully been able to connect to it via MySQL workbench but django doesnt seem to accept these settings. Settings I have tried: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mhprints-v3-dev', 'HOST': 'xxxx.instance.snappyhost.co.uk', 'PORT': '3306', 'USER': 'xxxx', 'PASSWORD': 'xxxxxx', } } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mhprints-v3-dev', 'HOST': 'xxxx.instance.snappyhost.co.uk', 'PORT': '22', 'USER': 'xxxx', 'PASSWORD': 'xxxxxx', } } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mhprints-v3-dev', 'HOST': 'Mysql@127.0.0.1:3306@xxxx.instance.snappyhost.co.uk', 'PORT': '3306', 'USER': 'dave', 'PASSWORD': 'xxxxxxxxx', } } - 
        
How to save a GDAL dataset to Django file field?
I am attempting to write a file to a Django model which has a FileField. This file has been processed from GDAL. Suppose I have this model. I watch for the file field and process the image then save the resulting image to file_cloud_geotiff. #models.py class Layer(models.Model): name = models.CharField(max_length=50, blank=True) file = models.FileField( upload_to='layers', null=True, max_length=500) file_cloud_geotiff = models.FileField( upload_to='cloudgeotiff', null=True, blank=True, max_length=500) def __str__(self): return self.name In my tasks, I have a function to convert the saved file. #tasks.py from osgeo import gdal def convert_to_cloud_geotiff(obj_id): instance = Layer.objects.get(pk=obj_id) geotif = instance.file.path src_ds = gdal.Open(geotif) translate_options = gdal.TranslateOptions(format='COG', creationOptions=['COMPRESS=LZW']) name = os.path.basename(instance.file.name) des_ds = '/vsimem/{}'.format(name) ds = gdal.Translate(des_ds, src_ds, options=translate_options) # Write variable ds to Layer's file_cloud_geotiff What I know is that the result or dataset is stored to the variable ds in this case. I want to write that dataset to the model other file field. The result is also saved from a memory file des_ds = '/vsimem/{}'.format(name). However, this mem file is not accessible and cannot be opened so that it can be written to the file field. How can I utilize the dataset object ds to write in a Django file field? - 
        
What would cause erratic primary key incrementing?
I have a django project with a microsoft sql DB that is containerized. I recently noticed that whenever I restart the project the next time I create an object it's primary key field is skipping anywhere from 900-1000 values. I am not really sure what information may be relevant to this issue. But here is a simple example. I have a simple model that is using the default autofield django automatically creates. # models.py class Contractor(models.Model): first_name = models.CharField( db_column="first_name", max_length=255, blank=False, null=False, verbose_name="First Name" ) I also have a view that creates a new Contractor. # views.py def add_contractor(request): form = ContractorForm() if request.method == "POST": form = ContractorForm(request.POST) if "submit" in request.POST["submit"]: if form.is_valid(): form.save() messages.success(request, "Added new Contractor") return redirect("contractors") else: print(form.errors) pass context = { "url": "contractor_details", "method": "post", "form": form, "title": "Add New Contractor", "submit_label": "Add", } return render(request, "employees/contractor_details.html", context) I bring up the project... docker-compose -f local.yml up navigate to the view, create a new contractor and hit submit. The new Contractor will be created with its id=1. Then if I restart the project and create an additional Contractor, it will be created with an id=1002. I am confident this issue has nothing … - 
        
classify_image function not being called as a function while running django
def classify_image(image_path) -> str: # Preprocess the image img = preprocess_image(image_path) # Make a prediction output = model(img) prediction = torch.argmax(output, 1) predicted_class = class_names[prediction.item()] return predicted_class Error shows TypeError at / 'collections.OrderedDict' object is not callable It shows error in line output = model(img) Exception Location: C:\Users\krishna sahu\PycharmProjects\Plant-Disease-Classification-Pytorch\PlantDisease\ImageApp\views.py, line 38, in classify_image What should be correct solution for this error. - 
        
unsupported media type "binary/octet-stream" in request
I'm trying to upload image to s3 bucket from HTML using django rest_framework. getting unsupported media type "binary/octet-stream" in request error while uploading the image Error: enter image description here - 
        
How to configure Pytest on Pycharm or IntelliJ Idea?
I am trying to run my test methods that is written using pytest. But I want to use the shortcut arrow and debug icon to execute or debug my method. But it's not working for as it is unable to detect the method path. I am getting the following response : enter image description here And this is my configuration enter image description here As you can see my working directory, i'm already in tests/user but pytest is still looking for tests/ directory. Note Default test runner is already set to pytest in IntelliJ settings. Thanks We tried all of the things from the docs of Jetbrains, Stack overflow, google.