Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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] -
the second form on the Django page is not being processed
I'm writing a site on Django and I ran into a problem. I have a page on the site that has a form. Then I added functionality so that when a button is pressed on this page, a modal window will appear, which also has a form. But if I want to send data from the form that is in the modal window, I am sent data from the form that is on the page, even if there is no data there and the button was not pressed. How can I change this behavior? This is my views.py file: @login_required(login_url='signin') def update_password_view(request, url_username): try: current_user = user_model.objects.get(url_username=url_username) except ObjectDoesNotExist: print("Incorrect user data") return redirect('index_page') if request.method == 'POST': form = UpdatePasswordForm(request.POST) if form.is_valid(): user_password = form.cleaned_data['password'] current_user.set_password(user_password) current_user.save() messages.success(request, "Your password has been updated successfully") else: print(form.errors) else: form = UpdatePasswordForm() img_base64, totp_secret = form_qrcode_service(current_user) return render(request, 'account/update-password.html', {'form': form, 'second_form': InputTokenForm(request.POST or None), 'qr_code': img_base64, 'totp_secret': totp_secret}) def input_code_form_view(request, url_username): try: current_user = user_model.objects.get(url_username=url_username) except ObjectDoesNotExist: print("Incorrect user data") return redirect('index_page') if request.method == 'POST': form = InputTokenForm(request.POST) if form.is_valid(): print(form.cleaned_data['code']) else: print(form.errors) return redirect('update-password', url_username=url_username) update_password_view should be responsible for processing the form on the main page, and … -
Post matching query does not exist. When post exists in DB
I'm creating a simple blog with a Django backend using MongoDB to store blog posts and their metadata. Everything worked find when I was testing with a local mongodb instance, but when I switched to an atlas hosted database I started getting the following error. The current Post model is ` class Post(models.Model): _id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField( max_length=50, help_text='Post title. equivalent to obsidian file name') publish_date = models.DateField() last_edited = models.DateField(auto_now=True) content = models.TextField(blank=False) summary = models.TextField(blank=True) tags = models.CharField(max_length=20, blank=False) choices = [ ('published', 'published'), ('draft', 'draft'), ('private', 'private') ] status = models.CharField( choices=choices, default='published', max_length=20, blank=False,) class Meta: pass def get_absolute_url(self): return reverse('post', args=[self._id]) def __str__(self): return self.title To debug I overrode the get_object method as follows: ` def get_object(self, *args, **kwargs): kwargs = self.kwargs kw_id = kwargs.get('pk') all_results = Post.objects.filter() print(all_results.first()._id == str(kw_id)) result = Post.objects.get(_id=str(kw_id)) print("result:", result) return result assuming there is only one test post in the DB, all_results = Post.objects.filter() returns the post, but some of its element (e.g. all_results.first().content are None even though it is populated in the DB. the main problem is that when trying to filter or get based on the value of the _id field … -
How to pass form data to another Django class
Не могу решить проблему связанный с ошибкой Please tell me what is my mistake? from django.urls import path from .views import * app_name = 'data_array_do' urlpatterns = [ path('planFormView/', PlanFormView.as_view(), name='planFormView'), path('planListView/', PlanListView.as_view(), name='planListView'), ] from .forms import * from .models import * from django.shortcuts import render, redirect from django.views import View from django.urls import reverse from django.db.models import Q class PlanFormView(View): form_class = Filter template_name = 'planFormView.html' def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): year = str(form.cleaned_data['year']) version = str(form.cleaned_data['version']) url = reverse('data_array_do:planListView', kwargs={"year": year, "version": version}) return redirect(url) return render(request, self.template_name, {'form': form}) class PlanListView(View): template_name = 'planListView.html' def get(self, request): year = request.GET.get('year', '') version = request.GET.get('version', '') if not year or not version: return render(request, self.template_name, {'error_message': 'Нет данных'}) my_data = FifthLevelCollection.objects.filter(Q(level_four_collection__third_level_collection__second_level_object__first_level_object__reporting_year__title=year) | Q(version=version)) return render(request, self.template_name, {'my_data': my_data}) from django import forms from .models import * # Форма для переменных фильтрации class Filter(forms.Form): year = forms.ModelChoiceField(label="Отчетный год", queryset=Year.objects.all()) version = forms.ModelChoiceField(label="Версия плана", queryset=Version.objects.all()) The user on the page fills out the form and sends it, then based on the form data, the data from the database is filtered and displayed on the page. … -
Caught in loop where timestamp value is overriding every other item's value in a list
New to Django and have been stuck on this issue for a couple days now. I am trying to display timestamp data for when an item was created in my database. I have two Django classes that look like this: class Game(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True, max_length=500) image = models.URLField(blank=True, null=True, max_length=500) genre = models.CharField(blank=True, null=True, max_length=200) platform = models.CharField(blank=True, null=True, max_length=200) developer = models.CharField(blank=True, null=True, max_length=200) publisher = models.CharField(blank=True, null=True, max_length=200) added_by = models.CharField(max_length=64) def __str__(self): return f"ID# { self.id }: { self.title }" class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() started_on = models.DateTimeField(auto_now_add=True) The Game model stores data about a game, and when I click a button I will add a game into my playinglist model, which should automatically get the time it was inserted into that model. To add a game into my playinglist I am using this function: def add_to_playinglist(request, game_id): obj = Playinglist.objects.filter(game_id=game_id, user=request.user.username) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) game = Game.objects.get(id=game_id) if obj: obj.delete() game playing_game return redirect("profile") else: obj = Playinglist() obj.user = request.user.username obj.game_id = game_id obj.save() game playing_game return redirect("profile") And to display all the items in that respective user's Playlist I am using this …