Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I specify OpenApiParameter properties for OBJECT type?
In drf-yasg when we specify Schema we have properties argument, where we can specify fields of OBJECT type. How do I get the same behavior for drf-spectacular's OpenApiParameter? @swagger_auto_schema( summary="Wallet balance", description="Save the wallet's balance", request=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'balance': openapi.Schema(type=openapi.TYPE_NUMBER), 'some_object': openapi.Schema(type=openapi.TYPE_OBJECT, properties={ 'a': openapi.Schema(type=openapi.TYPE_STRING), 'b': openapi.Schema(type=openapi.TYPE_STRING), }), } ), ) -
How to develop an E-commerce website using Python and Django as a server side language
I want to build an E-commerce website using Bootstrap, HTML, CSS, Java script in Frontend and For backend I want to use Python, Django and MongoDB. Can I get step wise instruction to develop files of codes of each language and how to link each one of them to make fully functional website. I want to know what directories and files will get added in code editor. -
Error display in the django admin through save_model
I have the following code in one of the classes related to the admin page: def save_model(self, request, obj, form, change): if change: if form.initial['delivered'] != form.cleaned_data['delivered']: for line in obj.lines.all(): book = line.book if not book.is_available and not obj.delivered: raise ValidationError('Error') if obj.delivered: number = line.book.number + 1 line.book.is_available = True else: number = book.number - 1 if not number: book.is_available = False line.book.number = number line.book.save() obj.save() return super().save_model(request, obj, form, change) The problem is that when the code reaches the raise ValidationError('Error') line and is executed, it doesn't show the error on the page and shows it like django debug errors, and this error is displayed only when DEBUG=True. How can I show this error like the django admin form errors? I also tried this code with django signals but it had the same result. Only when I wrote a class form myself and gave it to the admin class, it displayed the error correctly, but I cannot implement the conditions here in the form class. Is there a way to fix it in the save_model? -
Django file structure: cannot import main module without export PYPATH
I am using Django 4.0.4 Here is my project structure: root/ | README.md |-- app/ | |-- init__.py | |-- manage.py | |-- project/ | | |-- __init__.py | | |-- settings.py | | |-- urls.py | | |-- etc... | |-- webapp/ | | |-- __init__.py | | |-- apps.py | | |-- views.py | | |-- utils/ | | |-- migrations/ | | |-- etc... | |-- mediafiles/ |-- docs/ The imports inside de files are structured like this: apps.py => from app.project.settings import APP_NAME settings.py => from app.webapp.utils.paths import BASE_DIR urls.py => from app.webapp.views import home views.py => from app.webapp.models import MyModel In settings.py INSTALLED_APPS = [ "webapp", ... ] In short, nothing very unusual, except that my root folder is one level higher than in a standard Django installation. However, as soon as I run python app/manage.py runserver localhost:8000 # OR python manage.py runserver localhost:8000 # (inside the `app/` directory) I get a ModuleNotFoundError: No module named 'app' The problem is fixed if I set the PYTHONPATH variable inside the root/ directory: export PYTHONPATH="$(pwd)" If I remove the app from my imports, then the command works but my IDE (PyCharm) no longer lets me take advantage … -
ExtJS paging/pagination loads all records at page load
I am trying to set up paging for a grid in my ExtJS app. Let's say I want to show 30 records per page and I have a total of 35 records. No matter what, when I visit the view, the grid always loads all 35 records in the first page although the paging bar shows the presence of two pages (see image). The navigation buttons in the paging bar don't work in that, for example, when I hit the "Next page" button, I get the following error: Uncaught TypeError: store.nextPage is not a function at constructor.moveNext (ext-all-debug.js:185314:23) at Object.callback (ext-all-debug.js:8705:32) at constructor.fireHandler (ext-all-debug.js:144259:17) at constructor.onClick (ext-all-debug.js:144241:16) at constructor.fire (ext-all-debug.js:20731:42) at constructor.fire (ext-all-debug.js:34336:27) at constructor.publish (ext-all-debug.js:34296:28) at constructor.publishDelegatedDomEvent (ext-all-debug.js:34318:14) at constructor.doDelegatedEvent (ext-all-debug.js:34361:16) at constructor.onDelegatedEvent (ext-all-debug.js:34349:18) Hitting the "Last page" button doesn't raise an error, yet it just loads the same 35 records. When I check my webserver logs, I can see that, when I visit the view, my app doesn't just request the first page of record but all of them, which makes no sense: [20/Sep/2023:10:09:55 +0200] "GET /api/requests/?page=1 HTTP/2.0" [20/Sep/2023:10:09:56 +0200] "GET /api/requests/?page=2 HTTP/2.0" I checked the API output of /api/requests/?page=1, generated by Django REST Framework, and it returns … -
Trying the 'share chat' feature for my Chatbot but its not working
I'm working on a chatbot app, and I need to add a feature in it, "share chat" which is basically the ChatGPT feature of sharing your chat. So, I'm able copy the link generated for the chat page that is opened, and when i open the link in the new tab, the page is opening as expected and we can chat in it, but only as long as we're logged in. I mean if I tried to open that link in an incognito window, or if a non-logged in user tries to open that link, it wont open. It's probably because of the @login_required decorator we are using in the Django Backend but we can't remove it since it's required for authentication. I need to a way to implement sharing the chat and even if the user is not logged in they can open and use it. The frontend is made using HTML,CSS and JS, while the backend is Python-Django. I tried opening the link without using the @login_required decorator but it was still not working. Please let me know what approach I can take here? Like what needs to be done from the backend side or frontend? -
How can i delete an object from django database after editing it?
I edited the fields of a table that had an object. i wanted to delete the object after migration but it wouldnt let me because of the different fields. how can i delete that object? i tried to revert the changes made and go delete it but it still gives errors -
Django inline admin show child of child
I have three model in a hierarchy as follows (Django): def A(models.Model): pass def B(models.Model): a = models.ForeignKey(A) def C(models.Model): b = models.ForeignKey(B) Is it possible in django-admin that I show C model as inline of A model without using nested-inlines? -
filter object by being used in other query
I am having two models. Procedures and ProcedureCategories. Now every Procedure can have a foreignkey to a ProcedureCategory. I want to do two things: Get all Procedures of a specific type for my usergroup. And get all categories that are used in these Procedures. Here are my models: class ProcedureCategories(models.Model): name = models.CharField( max_length=200, help_text="Enter category name." ) def __str__(self): return self.name def __lt__(self, other): return self.name < other.name class Procedure(models.Model): """Model representing a task (but not a specific copy of a procedure).""" title = models.CharField(max_length=200) type = models.ManyToManyField(ProcedureTypes, help_text="Select a type for this procedure") summary = RichTextField(max_length=1000, help_text="Enter a brief description of the task", blank=True) groups = models.ManyToManyField(Group, help_text="Select which groups should be assigned for the task", blank=True) category = models.ForeignKey(ProcedureCategories, on_delete=models.PROTECT, help_text="Select which category should be assigned for the task", blank=True, null=True) date_done = models.DateTimeField(null=True, blank=True) def __str__(self): """String for representing the Model object.""" return self.title The first thing is easy: procedureModels = Procedure.objects.filter(type=2, groups__user=request.user) This gives me all Procedures of type 2 with correct user group. But how can I get all ProcedureCategorires that are used in these Procedures? ProcedureCategories.filter()? I would probably need to join it somehow. How can I do this in django? -
Selenium can't reach chrome in celery task while using supervisor
I have a Django project that uses Celery as a task queue. The task is about running a chromedriver by Selenium and fetching data from some URLs. like this: @shared_task(bind=True) def task_one(self): options = Options() options.add_argument("--start-maximized") options.add_argument('--no-sandbox') options.add_argument("--disable-dev-shm-usage") driver = webdriver.Chrome(options=options) wait = WebDriverWait(driver, 20) action = ActionChains(driver) driver.get('https://somewhere.com') # do others This task should be run periodically, for that I use celery beat. for testing, I run celery worker and celery beat in two terminals and everything seems okay. (the celery beat sends every 20 seconds and the worker runs Chrome and fetches data) But when I use Supervisor, the worker goes wrong and can't reach Chrome. (Still celery beat works well and sends every 20 seconds but the problem is in the worker) The celery logs say: 'Message: session not created: Chrome failed to start: exited normally. (chrome not reachable) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) Stacktrace: #0 0x562b0da106c3 <unknown> #1 0x562b0d6e61e7 <unknown> #2 0x562b0d719526 <unknown> #3 0x562b0d71569c <unknown> #4 0x562b0d75823a <unknown> #5 0x562b0d74ee93 <unknown> #6 0x562b0d721934 <unknown> #7 0x562b0d72271e <unknown> #8 0x562b0d9d5cc8 <unknown> #9 0x562b0d9d9c00 <unknown> #10 0x562b0d9e41ac <unknown> #11 0x562b0d9da818 <unknown> #12 0x562b0d9a728f … -
Django field not taking the given input
I have a login code in which the create two model where the data is being stored the first one is the default admin User model and the second one that is custom field Models.py from django.db import models # Create your models here. class AppUser(models.Model): username = models.CharField(max_length=150, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=128) # You should use a secure password storage method. first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) GENDER_CHOICES = [ ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ] gender = models.CharField(max_length=1, choices=GENDER_CHOICES,default='M') area = models.TextField(max_length=100,unique=False,default='Select City') phone_number = models.IntegerField(default='1') def __str__(self): return self.username and forms.py from django.contrib.auth.models import User from django import forms from .models import AppUser class SignUpForm(forms.ModelForm): GENDER_CHOICES = [ ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ] gender = forms.ChoiceField( choices=GENDER_CHOICES, widget=forms.Select(attrs={'class': 'form-control'}), required=True, label='Gender', ) class Meta: model = AppUser fields = ['username','email','password','first_name','last_name','area','phone_number'] Now the fields till gender is working just fine but after it the area and the phone number is not taking the user input the default shows up in the table; -
conflict google-analytics-data and protobuf
I get the error "ModuleNotFoundError: No module named proto" after install the google-analytics-data package in my grpcproject. This package conflicts with protobuf==3.17.0. I have tried using different versions of google-analytics-data and protobuf, but the problem persists continues. -
Django Virtual Environment Setup
Error message in terminal : PS E:\Work space\Django> & C:/Users/hp/.virtualenvs/Django-aOoBcd7m/Scripts/Activate.ps1 & : File C:\Users\hp.virtualenvs\Django-aOoBcd7m\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3 & C:/Users/hp/.virtualenvs/Django-aOoBcd7m/Scripts/Activate.ps1 CategoryInfo : SecurityError: (:) [], PSSecurityException FullyQualifiedErrorId : UnauthorizedAccess how can i fix this ? I tried to change the ExecutionPolicy to RemoteSigned in powershell after that its working, but is there any other way to fix this. -
How to store or save ssh client object in Django session?
Below functions, I am creating the ssh client and trying to save it to django session object. def create_ssh_client(host, user, password): client = SSHClient() client.load_system_host_keys() client.connect(host, username=user, password=password, timeout=5000, ) return client def save_to_session(request): ssh_client = create_ssh_client(host, user, password) request.session['ssh_client'] = ssh_client ** While trying to save to session, getting the type error -** TypeError: Object of type SSHClient is not JSON serializable Any suggestion or input appreciated. -
How To Set A Related Field To Session In Django
I want to implement the Web Push Notification in my current project, and I want the notification only sent to the currently logged-in sessions (i.e. devices). Thus I define my Subscription model like below: class Subscription(models.Model): device = models.CharField(max_length=100) session = models.OneToOneField('sessions.Session', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) info = models.JSONField() and the view function to save subscription: SubscriptionForm = model form_factory(Subscription, fields=['device', 'info']) @login_required @require_POST def subscr_view(request): form = SubscriptionForm(request.POST) if form.is_valid(): form.instance.session = request.session.model form.instance.user = request.user subscr = form.save() return JsonResponse({'subscription': subscr.id}, status=201) return JsonResponse({'errors': list(form.errors.keys())}) However, when I save the form, Django complains about the session attribute: ValueError: Cannot assign "<class 'django.contrib.sessions.models.Session'>": "Subscription.session" must be a "Session" instance. How can i set the session attribute correctly? -
Trouble Rendering Nested MultiValue Form Fields in Django - ProductPropertyField
I'm working on a Django project and facing difficulties while trying to create a multi-value form field called ProductPropertyField. My goal is to include multiple instances of ProductPropertyField within the final ProductPropertyField, but the rendering doesn't behave as expected. I have a specific structure I want to achieve: ProductPropertyField should contain multiple instances of ProductPropertyField. Each ProductPropertyField instance has three fields: key, value, and new_property. I'd like to use the provided code snippet as a reference for my implementation. Here's the code I'm using for ProductPropertyField: class ProductPropertyWidget(forms.MultiWidget): use_fieldset = True def __init__(self, attrs={}, choices=[], key=None): key_widget = forms.TextInput(attrs=attrs.pop("key_widget", {})) value_widget = forms.Select( attrs=attrs.pop("value_widget", {}), choices=choices ) new_property_widget = forms.TextInput( attrs=attrs.pop("new_property_widget", {}) ) widgets = [ key_widget, value_widget, new_property_widget, ] super().__init__(widgets, attrs) def decompress(self, value): if value: key, value, new_property = value.split(",") return [key, value, new_property] return [None, None, None] class ProductPropertiesWidget(forms.MultiWidget): use_fieldset = True def __init__(self, widgets=[], attrs={}): super().__init__(widgets=widgets, attrs=attrs) def decompress(self, value): if value: key, value, new_property = value.split(",") return [key, value, new_property] return [None for _ in self.widgets] class ProductPropertyField(forms.MultiValueField): widget = ProductPropertyWidget def __init__(self, *args, **kwargs): key_field = forms.CharField() value_field = forms.ChoiceField(choices=kwargs.pop("choices", [])) new_property_field = forms.CharField() super().__init__( fields=[key_field, value_field, new_property_field], require_all_fields=False, *args, **kwargs, ) def compress(self, … -
I want to create a staff then I want to perform CRUD operation
I want to create staff and update staff and delete staff. This is my code for create and update the staff: def create(self, validated_data): admin_data = validated_data.pop('admin') print(admin_data) try: username = admin_data.get('username') print(username) # Attempt to find an existing user with the same username existing_user = CustomUser.objects.filter(username=username) #.first() print(existing_user) if existing_user: print(existing_user,'Data comming') # If a user with the same username exists, update that user admin_instance = existing_user for attr, value in admin_data.items(): setattr(admin_instance, attr, value) admin_instance.save() else: # Create a new CustomUser instance using the 'admin' data admin_instance = CustomUser.objects.create(**admin_data) # Create a new Staff instance with the 'admin' field set to the user staff_instance = Staff.objects.create(admin=admin_instance, **validated_data) return staff_instance except Exception as e: # Handle any other exceptions that might occur during instance creation raise serializers.ValidationError({'error': f"Failed to create/update staff: {str(e)}"}) -
middleware running after views' route method
My middleware is as follows : MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', # My custom middleware where I have set request.foo = "bar" 'application.custom_middleware.CustomMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] But when doing a print of request.foo I get it printed correctly in the middleware but in the views function it throws. print("request.foo = ", request.foo) AttributeError: 'WSGIRequest' object has no attribute 'foo' request.foo in custom_middleware = bar My views's add function is as follows : @ms_identity_web.login_required def add(request): print("request.foo in add = ", request.foo) Django 4.2.5 -
How to get information of specific user who has logged in?
appname/views.py from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') # Redirect to a success page else: # Handle authentication failure (e.g., show an error message) return render(request, 'login.html', {'error_message': 'Invalid credentials'}) return render(request, 'login.html') I want to filter the users login and want to see the specific user login information. -
How to correctly incorporate wkhtmltopdf in Django Project to download PDFs?
I have a Django project that includes an HTML that I want to be downloaded as a PDF. I correctly downloaded the wkhtmltopdf executable file and also registered it in the settings.py. however, when i try to download the PDF i get this error: No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it or you can pass path to it manually in method call, check README. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf These are some code snippets: views.py: @login_required def download_resume(request): # Retrieve data from your Django models personal_info = personalinfo.objects.filter(user=request.user).last() summaries = summary.objects.filter(user=request.user).last() experiences = experience.objects.filter(user=request.user) educations = education.objects.filter(user=request.user) certs = certificates.objects.filter(user=request.user) skillset = skills.objects.filter(user=request.user) # Generate the PDF content using a template template = get_template('template0.html') context = { 'personal_info': personal_info, 'summaries': summaries, 'experiences': experiences, 'educations': educations, 'certs': certs, 'skillset': skillset } # Render the template with the context data html_content = template.render(context) # Convert HTML to PDF using wkhtmltopdf pdf = pdfkit.from_string(html_content, False) # Create a response with the PDF content response = FileResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="resume.pdf"' return response settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') WKHTMLTOPDF_BIN_PATH = r'C:\Users\lulu\PycharmProjects\builderproject\wkhtmltopdf\binwkhtmltopdf.exe' I made sure that the wkhtmltopdf was downloaded … -
[django][redis] delay in delivering websocket message used redis cloud as channel layer
currently, i am working on project that has one client side code written in python that send continuously screen shot of that system to server i.e my Django web-socket endpoint and my front end also connect to that web-socket and display that screen shot as live screen sharing. In this i have used Redis cloud free version for testing. firstly i have used in-memory channel layer and it is working really fine. but it is not preferred in production , so i want to switch it to redid but it becomes slow. i mean front-end side web-socket connection receive messages with so much delay. can anyone explain what is getting wrong here and what can be the optimal way to solve this problem????? -
Django unit test, how to run migrations on its respective multi-database?
For example, I have 2 apps, App A has models in default DB , and App B has models in other_db. eg. DATABASES = { 'default': {....}, 'other_db': {....} } When I run test, it always try to run migration again on database A and causes error about stuff already exists. Is it possible to tell Django only run App A's migration on default test db, and App B's migration on other_db test db? -
Celery synchronous task on specific worker by queue name in Django
I have two workers one with a default queue and one with a named queue. I want to run a synchronous task on the worker with the named queue. However, the tasks seems to be always executed on the web thread of Django. The code is as follows: file1.py: from test.task import predict from rest_framework.response import Response from rest_framework.views import APIView class run(APIView): def get(self, request, age): result = predict.apply(args=[age]) print(result.get()) return Response({}) task.py from celery import shared_task @shared_task(queue="gpu") def predict(age): result = age + 1 return result When I read the documentation correctly this should run on the worker started like this: celery -A main worker --loglevel=info -n worker-gpu@%h -Q gpu But it seems never to run there. Can someone explain how I can force the task to run synchronously on the the worker with the gpu queue? -
Django website showing index of/ instead web pages
I hosted my Django app on namecheap shared hosting three months ago, it has been working properly. The recently it stopped and was showing index of/ and files and folders in my public_htm folder. I have tried following the steps I used in hosted the site again but same thing keeps showing. Please what can I do to resolve this issue. -
After replacing ASCII interpretations of accentuated words in Postgresql tables these changes are not shown in my Django
I had names of cities in my DB that were shown like this 'C & oacute;rdoba' instead of Córdoba. This is, of course, because of the encoding. It is a very old table, maybe 20 years old, so probably before unicode UTF-8 was invented :)) So I changed all those escaping characters in the table with things like this: SELECT nombre_localidad, replace(nombre_localidad,'&oacute;','o') FROM localidades as you can see, I removed the tilde so I left it as o instead of 'ó' which works well when I see it on my PGAdministrator viewer for the tables, but when I returned to my Django Application and I pulled the list of cities from my select lists, they are still showing the original thing, C & oacute;rdoba instead of Cordoba. Why is still Django picking the old data. Yes, I clicked on save data changes (F6) in my PgAdministrator