Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How do we enable CGO from 0 to 1 in go environment
How do I change cgo from = 0 to 1 to run race in Go lang? How do I change cgo from = 0 to 1 to run race in Go lang? I have tried to run this go code but I get this error at the terminal what could be the problem, Kindly help me find it the solution. I want to run this program -
simple-jwt isn't authenticating my login attempts
I've created a custom user model that allows users to log in with their email and phone number. I tried implementing simple jwt authentication but I keep getting the error: { "detail": "No active account found with the given credentials" } Note that I've attempted logging in using only active accounts and super user accounts created both before and after attempting to login This is in my models.py file class CustomUserManager(BaseUserManager): def create_user(self, name, email, phone_number, password, **other_fields): if not phone_number: raise ValueError('You must provide a phone number') user = self.normalize_email(email) user = self.model(email=email, name=name, phone_number=phone_number, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, name, email, phone_number, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff = True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser = True') return self.create_user(name, email, phone_number, password, **other_fields) class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=200) email = models.EmailField(unique=True, null=True) phone_number = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=50) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS =['name', 'email'] def __str__(self): return self.name My backends.py file to allow users to log in with their email class EmailOrPhoneNumberBackend(ModelBackend): def authenticate(self, … -
Django:- Real-time Name Display Issue: 'Account Not Found' Despite Existing Account Number
There is a name field in the CustomUser model that I want to display when a user inputs an account number in the Transfer model. What this means is validation: Imagine you want to transfer funds to someone's account. When the sender inputs the receiver's account number, I want the name field from the CustomUser model to be displayed in the name field of the Transfer model in real-time, to accomplish this, I need to query the Account model and send the results to a JsonResponse, But I don't understand why it says Account Not Found even though the account number does exist in the database. Models.py class Account(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.IntegerField() account_balance = models.DecimalField(max_digits=12, decimal_places=6, default=0.0) account_status = models.CharField(max_length=40, choices=ACCOUNT_STATUS) is_accepted_for_Loan = models.BooleanField() class Transfer(models.Model): name = models.CharField(max_length=100) account_number = models.IntegerField() sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sender_user') receiver = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='receiver_user') amount = models.DecimalField(max_digits=12, decimal_places=6, default=0.0) timestamp = models.DateTimeField(auto_now_add=True) Template <input type="number" id="account_number" placeholder="Receiver's Account Number"> <p>Receiver Name: <span id="receiver_name"></span></p> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $('#account_number').on('input', function() { let url = "{% url 'Get_Receiver_Infor' %}; var accountNumber = $(this).val(); if (accountNumber.length > 9) { $.ajax({ url: url, type: 'POST', dataType: 'json', success: function(data) { $('#receiver_name').text(data.name); }, … -
How to cancel a HTMX request?
I've this HTMX form which uploads image to the server. I want to add a cancel button which cancels the HTMX request. HTML side of it: <form id="uploadForm" hx-post="{% url 'pins:upload_image' %}" hx-target="#imageUploadResponse" hx-swap="outerHTML" hx-on::before-request="removeResponseText(), showProgressBarCancelButton()" hx-sync="closest form:drop" enctype="multipart/form-data"> {% csrf_token %} <!- REST OF THE CODE CAN BE IGNORED BECAUSE IRRELEVANT -> <footer class="modal-card-foot"> <button type="submit" class="button is-success" id="imageUpload">Upload</button> <button id="abortUpload" onclick="abortHTMXUpload()" class="button is-hidden">Cancel </button> </footer> </form> JS side of it: <script src="https://unpkg.com/htmx.org@1.9.5"></script> <script> const burgerToggle = document.querySelector(".navbar-burger"); const navbarMenu = document.querySelector(".navbar-menu"); const uploadButton = document.querySelector(".upload"); const modal = document.querySelector(".modal"); const modalForm = document.getElementById("uploadForm"); const progressBar = document.getElementById("progress"); const abortUpload = document.getElementById("abortUpload"); // Rest of the code can be ignored due to irrelevant from this topic htmx.on('#uploadForm', 'htmx:xhr:progress', function(evt) { htmx.find('#progress').setAttribute('value', evt.detail.loaded/evt.detail.total * 100) }); function abortHTMXUpload() { htmx.trigger('#uploadForm','htmx:abort') } </script> I hope the code is self-explanatory. I've gone through the HTMX docs, tried htmx:xhr:abort and similar, nothing seems to work. -
Barcode-django-weasyprint-vuejs Generation timing out
im trying to generate a pdf that will contain one pallet barcode with the items barcodes under that pallet. the issue is happening when the pallet contain big number of items under it the call is taking around 1.7 min and then timing out. My django view :`class XivaAllBarcodeWeasyTemplateView(WeasyTemplateResponseMixin, DetailView): template_name = 'invoices/barcode_all_pallet.html' def get_object(self): try: return PurchasePallet.objects.get(pk=self.kwargs.get("pk")) except PurchasePallet.DoesNotExist: raise Http404("Not found") def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) size_unit_dict = {'1': 'KG', '2': 'LB'} context['size_unit_dict'] = size_unit_dict return context ` -
filter by intersection of lists
I have a Object-Class that has a ManyToManyRelation to groups. Now I want to get all the objects from that class where at least one group of the user is in the groups attribute of the Class. Something like: MyClass.objects.filter(groups hasIntersectionWith request.user.groups.all()) How can I do that?