Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Next.js want to convert image frame stream to a video on the frontend
I am using Django to stream image frames using return StreamingHttpResponse(run_live_demo(camera, model, conf_thresh), content_type="multipart/x-mixed-replace; boundary=frame",) When run_live_demo runs captures image from camera and yields the image. In my front-end where I am using next.js/react, I want to fetch the images but store the frames and play it is a video where it shows the current image by default but we can go back to older frames like a live video would work. I have tried lot of things, and am very confused on how to do this. To make it clear it is a live url and I cannot stop it and make it a mp4 and display that, because it suppose to be live. I tried to make it a video. import { useEffect } from "react"; function LiveStream() { useEffect(() => { const mediaSource = new MediaSource(); const videoPlayer = document.querySelector("#videoPlayer"); videoPlayer.src = URL.createObjectURL(mediaSource); mediaSource.addEventListener("sourceopen", () => { const sourceBuffer = mediaSource.addSourceBuffer( 'video/mp4; codecs="avc1.640028" ); const stream = new ReadableStream({ start(controller) { const xhr = new XMLHttpRequest(); xhr.open("GET", "http://127.0.0.1:8000/stream/0/default/0.7/0.7/0"); xhr.responseType = "text"; xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) { const contentType = xhr.getResponseHeader("Content-Type"); const boundary = contentType.match(/boundary=(.+)/)[1]; let buffer = ""; let boundaryIndex; xhr.responseType = … -
Single Form In Multiple Views
I have a form created in my forms.py file that I want to display on multiple pages of my app. The form: class Meta: model = Lead fields = ( 'first_name', 'last_name', 'address', 'city', 'state', 'zip', 'phone', 'email_address', 'date_delivery', ) widgets = { 'first_name': forms.TextInput(), 'last_name': forms.TextInput(), 'address': forms.TextInput(), 'city': forms.TextInput(), 'state': forms.TextInput(), 'zip': forms.NumberInput(), 'phone': forms.NumberInput(), 'email_address': forms.EmailInput(), 'date_delivery': forms.DateInput(), } The view: class CreateLeadView(CreateView): model = Lead form_class = LeadForm template_name = 'my_app/quote.html' Basically, I have several other views I want this form to appear on. What is the best way to accomplish this? -
How to check if a date is still less than 5 days in django query?
I am trying to check if the date an order was created is still less than 5 days, then i want to display a New Order Text. This is how i have tried doing this def vendor_orders(request): five_days = datetime.now() + timedelta(days=5) new_orders = CartOrder.objects.filter(payment_status="paid", date__lte=five_days).order_by("-id") This is returning all the orders in the database that the date is less than 5 days, which means all orders both old and new are being returned and this is not what i am expecting. If i manually create an order and set the date manually to some date in the future e.g July or August, it does not return that order. Please how can i go about this logic? all i want to do is display an order as new orders if the date which the order was created is not yet older than 5 days. Template Update i want to check if the order is a new order then i display a new badge Views.py @login_required def vendor_orders(request): five_days = datetime.now() - timedelta(days=5) # this is 5 days ago new_order = CartOrder.objects.filter(payment_status="paid", vendor=request.user.vendor, date__gte=five_days).order_by("-id") order = CartOrder.objects.filter(payment_status="paid", vendor=request.user.vendor).order_by("-id") context = { "order":order, "five_days":five_days, "new_order":new_order, } return render(request, "vendor/vendor-order.html", context) {% for … -
How do I install Haystack without CUDA?
I have integrated the Haystack vector search library into my Django application, and now I'm going through and attempting to turn the project into a Docker container. Everything is working okay, but I have noticed that when I build my Docker container, a lot of time is being spent on downloading and installing NVIDIA CUDA python packages. I am not deploying my containers on a platform with GPUs, and so I would like to install Haystack without installing the CUDA python packages. -
Profile matching query does not exist
Hi have getting error of Profile matching query does not exist and here is my codeenter image description here Hi have getting error of Profile matching query does not exist and here is my code[enter image description here]