Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin Postoffice queued mails are not editable
I am working on two separate django apps. We are sending mail in django. Due to some mistakes in the mail sometimes it is required to edit the queued mail. But for some the one of the apps allow to edit the queued mail whereas the other apps won't allow to edit the contents. I am new to django and don't know how to solve this thing. -
Filter child class date field in DRF
I'm new in DRF , i need to child class filed filter in parent view models.py class Customer(Base): name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100, blank=True, null=True) comments = models.CharField(max_length=255, blank=True, null=True) class Cart(Base): user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="cart") cart_number = models.CharField(max_length=500, default=increment_cart_number, null=True, blank=True) total_summa = models.FloatField(default=0) is_saved = models.BooleanField(default=False) class Base(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True filters.py class CustomerListFilter(rest_framework.FilterSet): name = rest_framework.CharFilter(lookup_expr='icontains') class Meta: model = Customer fields = [ 'name', 'phone_number', ] I need to filter the list of customer's carts according to the dates of the carts -
Unable to display a Bootstrap 5 stepper in a Django
I am having a problem getting the vanilla flavored stepper Bootstrap function to display properly in Django and wondered if there is something I am missing. Other Bootstrap elements such as alerts work fine. None of the formatting for the stepper is being picked up and I am just getting the text displayed vertically e.g.as follows without the bullet points 01 Basic Information 02 Personal Data 03 Terms and Conditions 04 Finish Step 1 Step 2 Step 3 Step 4 I have a Base html where I have the Bootstrap cdns. e.g. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> I wish to display the stepper in index.html which extends base.html. Within a div with class="container-fluid", I have another div where I have inserted the standard horizontal stepper code i.e. <div class="row mt-4"> <p> <div height="800px" class="stepper" id="stepper2"> <div class="steps-container"> <div class="steps"> <div class="step" icon="fa fa-pencil-alt" id="1"> <div class="step-title"> <span class="step-number">01</span> <div class="step-text">Basic Information</div> </div> </div> <div class="step" icon="fa fa-info-circle" id="2"> <div class="step-title"> <span class="step-number">02</span> <div class="step-text">Personal Data</div> </div> </div> <div class="step" icon="fa fa-book-reader" id="3"> <div class="step-title"> <span class="step-number">03</span> <div class="step-text">Terms and Conditions</div> </div> </div> <div class="step" icon="fa fa-check" id="4"> <div class="step-title"> <span class="step-number">04</span> <div class="step-text">Finish</div> </div> </div> </div> … -
Django tests : doesn't work for testing case for is_staff user
That seems to be a silly question explained by some stupid error, but I could not figure it out for the moment. General situation : I have a little Djano app used as small database for some items. Items could be viewed, edit or deleted. View is available for all users, but edit/delete only for Staff users. It was implemented and during manual test it works fine (if I'm not staff user I get 403 for edit/delete pages, then if I become staff user : I could edit/delete). But the automatic test Fail and I could not figure why. Here is the test code : def createTestUserAndLogin(self): self.user = User.objects.create_user(username='testuser', password='qwerty') login = self.client.login(username='testuser', password='qwerty') def createTestStaffUserAndLogin(self): self.user = User.objects.create_user(username='staffuser', password='qwerty_staff', is_staff=True) login = self.client.login(username='testuser', password='qwerty_staff') self.assertTrue(self.user.is_staff, "User is not staff") def test_delete_item_as_non_staff_user(self): test_serial = "AA1111" new_item = Item(serial_number=test_serial) new_item.save() self.createTestUserAndLogin() url = reverse("delete_item", kwargs={'pk':new_item.id}) resp = self.client.get(url) self.assertEqual(resp.status_code, 403) self.client.logout() def test_delete_item_as_staff_user(self): test_serial = "AA1111" new_item = Item(serial_number=test_serial) new_item.save() # Could delete with Staff user self.createTestStaffUserAndLogin() self.assertTrue(self.user.is_staff, "User is not staff") url = reverse("delete_item", kwargs={'pk':new_item.id}) resp = self.client.get(url) self.assertNotEqual(resp.status_code, 403) confirm_data = {'delete': 'yes'} resp = self.client.post(url, confirm_data) self.assertEqual(Item.objects.all().count(), 0) If I launch manage.py test on these tests I … -
Trigger long process in Django view
I have a view (start_job_view) in Django that should trigger a very long process. I'd like the view to return immediately and add a message to the user ("your job has started" using the message framework) and I'd like that when the long process terminates it sends a new message to the user ("your job has finished"). How can I do this? Note: I am not keen to add Celery to my project for this only task... -
How to monitor if the django sslserver is down
We are starting our server using django using the below command and it works fine. Python3 ./manage.py runsslserver www.abc.com:8443 —certificate abc.vet —key abc.pem But sometimes it automatically crashes . I would like to understand about how to monitor this , do we have any prebuilt monitoring in django itself The approach I have is a shell script where I can constantly check if process is up using Ps -ef Is there anything inbuilt in django to monitor if this sslsevrr is up ? Regards Tejas -
Django crispy forms inline checkboxes
I am using Django-cripsy-forms to build a form. I have a model with several attributes (MultiSelectField) all with the same choices (CHOICES). from django.db import models class Visit(models.Model): CHOICES = ( ("A","A"), ("B","B"), ("C","C"), ("D","D"), ) q1 = MultiSelectField(null=True, choices=CHOICES, blank=True) q2 = MultiSelectField(null=True, choices=CHOICES, blank=True) q3 = MultiSelectField(null=True, choices=CHOICES, blank=True) q4 = MultiSelectField(null=True, choices=CHOICES, blank=True) q5 = MultiSelectField(null=True, choices=CHOICES, blank=True) q6 = MultiSelectField(null=True, choices=CHOICES, blank=True) I want to make a form with checkboxes for each choice for all attributes. But to avoid clutter want to have the checkboxes in-line. Sort of like a questionnaire (example below) I tried using django-crispy-forms InlineCheckboxes as shown below. But the checkboxes would never be displayed inline. But would be displayed as shown in the picture below. I also tried editing the styling of the labels and inputs of individual checkboxes but that also didn't work. What am I doing wrong? And is there a better way of doing this? from django import forms from django.forms import ModelForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout from crispy_forms.bootstrap import InlineCheckboxes class VisitForm(ModelForm): class Meta: model = Visit fields = '__all__' widgets = { 'q1': forms.CheckboxSelectMultiple(), 'q2': forms.CheckboxSelectMultiple(), 'q3': forms.CheckboxSelectMultiple(), 'q4': forms.CheckboxSelectMultiple(), 'q5': forms.CheckboxSelectMultiple(), 'q6': … -
Django Migrations Do I need type hints and how?
Python now has type hinting (or typehint? is it one word or two?). Some docs can be seen at peps.python.org. The issue is that typehinting is made for devs to understand the program usage and avoid errors but what happens if it's code made for automation? i.e. Django migrations where the code isn't run by another dev/user but by another software? Django creates its own migrations via manage.py makemigrations and this is the code that comes out: class Migration(migrations.Migration): dependencies = [ ('app', '0029_auto_20220601_1515'), ] operations = [ migrations.AlterField( model_name='jobexecution', name='job_type', field=models.CharField(choices=[('foo', 'Foo'),('bar', 'Bar)], default='foo', max_length=30), ), ] On the other hand when I want to do data migrations I create something like this: def forwards(apps, schema_editor): Foo = apps.get_model('app', 'Foo') FixedResponse.objects.create(name='Bar') def backwards(apps, schema_editor): Foo = apps.get_model('app', 'Foo') Foo.objects.filter(name='Bar').delete() class Migration(migrations.Migration): dependencies = [ ('app', '0035_fixedresponse'), ] operations = [ migrations.RunPython(forwards, backwards) ] Should I type hint both files? How do I typehint the latter (the data migration)? -
Invalid block tag on line 150: 'tag', expected 'endblock'. Did you forget to register or load this tag?
I use tags in my project by using @register.simple_tag. This is how i use it in my project: <div class="py-2 pl-4 shadow-blueshadow border border-forblueshadow rounded md:shadow-none md:border-0"> {% some_tag current_organization.pk None selected_language as some_tag %} <a class=" font-light text-darkgreen block text-center" href="{{some_tag}}"> <i class="fas fa-undo text-darkgreen "></i> <span class="hidden md:inline-block">{% trans "Reset" %}</span> </a> </div> I know that the problem is not in my tag, cause I used the same tag before. Just in case this would be the tag (without the return since it's kinda much): @register.simple_tag(name="some_tag") def okr_example_link(org_id, tag_name=None, language=None): if tag_name and language: return ... elif tag_name: return ... elif language: return ... else: return ... Yet I get the following error: Invalid block tag on line 150: 'simple_tag', expected 'endblock'. Did you forget to register or load this tag? -
Use JS script on Django html?
When using my js script in html, I get an error: the file was not found, although the file is in the directory. Help me to understand. Thanks! I have next structure of project: ---- app -------- urls.py -------- settings.py -------- wsgi.py ---- health_app -------- urls.py -------- templates ------------- scripts ------------------ myscript.js ------------- index.html I can use myscript.js in my app health_app. index.html <script type="text/javascript" src="templates/scripts/myscript.js"></script> console error: Not Found: /health_app/templates/scripts/myscript.js [18/Oct/2022 07:34:52] "GET /health_app/templates/scripts/myscript.js HTTP/1.1" 404 2303 -
How to get function return value and use it in html template, flask
I have html file index.html and a python file using flask, i want to call a function from python file and use the return value in an attribute in html i.e. <div style="display: {{ some_builtin_function('drowsiness_alert') }};" > <h1>Hide this</h1> </div> python file: @app.route('/drowsiness_alert') def drowsiness_alert(): return "none" I am using url_for to return url from flask so i was wondering if there is a builtin method for getting function return value, i have searched the internet for a while but the information is too overwhelming, i am new to flask. example code of url_for is <img src="{{ url_for('video_feed') }}" height="80%"> -
Problem in activating virtual environment in Django with "env\Scripts\activate.bat" command [duplicate]
I am trying to activate already created virtualenvironment named 'proj2' in PyCharm terminal(in Windows 11). But it is not working. Could anybody please tell me, how could I fix this problem? + proj2\scrips\activate.bat : The module 'proj2' could not be loaded. For more information, run 'Import-Module proj2'. At line:1 char:1 + proj2\scrips\activate.bat + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (proj2\scrips\activate.bat:String) [], CommandNotFoundException + FullyQualifiedErrorId : CouldNotAutoLoadModule -
DoesNotExist at / profile matching query does not exist
sorry I'm quite new to Django and Python, doing a school project, I was doing a default login with python, it creates the users and makes a login, so far so good. When I log in with the admin I can enter "html.html" without problems and the view runs and makes the queries in the database, the problem is when I log in with a different profile than the admin, I get this message DoesNotExist at /nuevo/ Profile matching query does not exist. views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.http import HttpResponse from django.contrib.auth.decorators import login_required from .models import profile # Create your views here. @login_required(login_url= 'signin') def index(request): user_object = User.objects.get(username=request.user.username) user_profile = profile.objects.get(user=user_object) return render(request, 'index.html', {'user_profile' : user_profile}) @login_required(login_url= 'signin') def upload(request): return def signup(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, 'Email Taken') return redirect('signup') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('signup') else: user = User.objects.create_user(username = username, email = email , password = password) user.save() # log user in redirect to settings user_login = auth.authenticate(username=username, password=password) auth.login(request, user_login) # … -
Django-tenant : executing tenant_command on the test DB?
I am using django_tenants and I have an API to create a new tenant. In this API we initialize data in some models from fixtures. execute_from_command_line(["manage.py", "tenant_command", "loaddata", "core/fixtures/"+file, "-s", self.schema_name]) I am now writing Tests on this API using APITestCase. The test creates the database schema but fails on the fixture command (which works fine outside of Test cases). The error is "django.core.management.base.CommandError: Invalid tenant schema, 'la_poste'" I believe the issue is that the command is executed in the real DB and not the Test DB. tenant_command does not seem to have a "database" option. Can I still test this ? Thanks -
cs50w wiki couldn't create a new encyclopedia entry whenever I click on submit button to does nothing
I was working on cs50w project1 wiki using django and when I try to create a new encyclopedia entry the submit button doesn't work. views.py def createnewform(request): if request.method == "POST": form = CreateForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) return HttpResponseRedirect(reverse("index")) else: return render(request, "encyclopedia/add.html", {'form': CreateForm()}) return render(request, "encyclopedia/add.html", {'form': CreateForm()}) url.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>/", views.detail, name="detail"), path("wiki/search", views.searched_result, name="searched-result"), path("wiki/add", views.createnewform, name="new-form") ] add.html {% extends "encyclopedia/layout.html" %} {% load crispy_forms_tags %} {% block title %} New {% endblock%} {% block body %} <form action="{% url 'new-form' %}" method="Post"> {%csrf_token%} {% crispy form %} <input type="submit"> </form> {% endblock %} util.py def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) -
Sometime .sock file missing
My django application working fine on the server. But after the new production release sometimes the server gets down. While checking the logs it's showing app.sock failed (2: No such file or directory) while connecting to upstream But the file is there after restarting the gunicorn it's working fine. -
Please I need help on how to use Gdal with my Django application
I have installed Gdal on my virtual environment already but the issue is I don’t know the right path to put in my settings.py all the videos I’m seeing online are only for the windows operating system -
Django select_for_update: Is it possible to allow the creation of related objects during the transacaction?
Postgres DB For example if you have models: class Foo(models.Model): name = models.CharField() class Bar(models.Model): foo = models.ForeignKey(Foo) Is there a way to create a new Bar instance during a transaction that has a ForeignKey field set to the Foo instance that is currently locked? I have tried using 'self' in the 'of' argument too but doesn't seem to work. Eg: with transaction.atomic(): foo = Foo.objects.select_for_update().get(id=1) # other stuff Bar.objects.create(foo=foo) # other stuff Creating the Bar instance won't affect the reasons I am wanting transaction atomic, but it seems like trying to create Bar causes a big delay in my tasks. Is there anyway I can allow this behaviour, or only lock certain fields of Foo during the transaction? -
How would You write a Django REST Framework view that only allows for changing a single field in a model thru a REST call?
I am a beginner in Django, I have a problem with updating only one field in a model Marchant. I just want to update my status field, but when I was trying to update the status field via partial update all the fields are showing, but I only want the status field. PATCH : { "status": "inactive" } Updated API: { "id": 82, "full_name": "Update all", "contact_no": "0122256666", "contact_no_two": "01793912259", "identity": "Passport", "identity_no": "55555555", "email": "rafiul@gmail.com", "bank_name": "asd", "bank_account_name": "adsas", "bank_account_num": "asda", "business_name": "sadda", "address": "asda", "pickup_address": "dsad", "password": "123456", "confirm_password": "123456", "status": "inactive", "payment_method": { "id": 6, "method_name": "Bank", "status": "active", "tanent": 15 }, "city": { "id": 2, "cities_name": "Dhaka", "status": "active", "tanent": 12 }, "area": { "id": 16, "areas_name": "Mirpur 10", "status": "active", "cities_name": 2, "tanent": 12 } } here, I only want the status update -
Query the first object of all user related objects in Django
I have a django model like below: class Books: name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) timeStamp = models.DateTimeField(auto_now_add=True) first = models.BooleanField(default=False) I already have like a million entries in the Books table and added first field recently. Now I want to update the first field of the first created object of every user to True. all = Books.objects.all() li = [] for i in all: if i.user.username not in li: i.first = True i.save() li.append(i.user.username) I tried the following function but it takes so long to execute, with much data in it. So is there a faster way? Tried the bulk_update method, for that also the loop should be completed. -
parsing into queryset for product media
I have two different models for my product. One is for product information and the other is product media. class Products(models.Model): id=models.AutoField(primary_key=True) url_slug=models.CharField(max_length=255) subcategories_id=models.ForeignKey(SubCategories,on_delete=models.CASCADE) product_name=models.CharField(max_length=255, null=True) brand=models.CharField(max_length=255) max_price=models.DecimalField(max_digits=7, decimal_places=2) discount_price=models.DecimalField(max_digits=7, decimal_places=2) product_description=models.TextField() product_long_description=models.TextField() created_at=models.DateTimeField(auto_now_add=True) in_stock_total=models.IntegerField(default=1) is_active=models.IntegerField(default=1) class ProductMedia(models.Model): id=models.AutoField(primary_key=True) product_id=models.ForeignKey(Products,on_delete=models.CASCADE) media_type_choice=((1,"Image"),(2,"Video")) media_type=models.CharField(max_length=255) media_content=models.FileField(upload_to="media") created_at=models.DateTimeField(auto_now_add=True) is_active=models.IntegerField(default=1) Now I have two user module one of which needs no authentication and the other is for authenticated user. For unauthenticated user I have my items dictionary as following. items=[] item = { 'product' :{ 'id': product.id, 'media_content': media.media_content, 'product_name': product.product_name, 'discount_price': product.discount_price, }, 'quantity': cart[i]["quantity"], 'get_total': total, } items.append(item) for the authenticated user my items is a query set: if request.user.is_authenticated: customer_user = CustomerUser.objects.get(user = request.user) order, created = Order.objects.get_or_create(customer_user, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items Now when I want to call the media of the product in html for unauthenticated user I call {{item.product.media_content}} to have a visible product image in cart. But this doesn't work for authenticated user. I don't want to change html command. How can I add the media content in the above items queryset? -
Django Apps with shared model migrate to multi schemas Postgres
In a Django project, I have a few apps and one model-class will be created in one app's models.py and imported to another apps' models.py. then I run migrate for each app per one schema in Postgres, there is no error reported. But the issue is the shared model will be migrated to all the schemas because (I assume this is the reason) I imported this model in each app's models.py. Anyone knows How to avoid or solve this problem. Because I would like keep the model only stay in his original schema. Or can I delete this model directly from each schema it appears?...without any side effects. Please help, Thanks! -
Annotate django query set on related object queryset's related object count
I have the following three models: class User(AbstractUser): username = None name = models.CharField(max_length=255) email = models.EmailField(unique=True) account_type = models.CharField( choices=AccountType.choices, default=AccountType.GENERAL, max_length=8, ) first_name = None last_name = None USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name"] objects = UserManager() @property def total_likes(self): queryset = ( self.works.filter(visibility=Visibility.PUBLIC) .select_related() .annotate(likes=models.Count("social")) ) return ( queryset.aggregate(models.Sum("likes")).get("likes__sum") or 0 ) def __str__(self) -> str: return self.name class WorkImage(models.Model): user = models.ForeignKey( to=User, on_delete=models.CASCADE, related_name="works" ) title = models.CharField(max_length=255) image = models.ImageField(upload_to=work_image_directory_path) @property def likes(self): return self.social.count() def __str__(self) -> str: return f"{self.user.name}'s {self.work_image_type} {self.title}" class WorkImageSocial(models.Model): work = models.ForeignKey( to=WorkImage, on_delete=models.CASCADE, related_name="social" ) liked_by = models.ForeignKey( to=User, on_delete=models.CASCADE, related_name="liked_works" ) def __str__(self) -> str: return f"{self.liked_by.name}=>{self.work.title}" I am writing a custom ordering filter to get the "most liked" users, what I want to do is annotate users with a field called "likes" which will have the sum of all likes on their work images, how do I achieve this? -
Django 'str' object has no attribute 'read'
I am making the database call to bring a BLOB type image to the django view, but I get the error "'str' object has no attribute 'read'". views.py def listar_productos(): django_cursor = connection.cursor() cursor = django_cursor.connection.cursor() out_cur = django_cursor.connection.cursor() cursor.callproc('FASTFERIA.SP_LISTAR_PRODUCTOS', [out_cur]) lista = [] for fila in out_cur: data = { 'data': fila, 'imagen':str(base64.b64encode(fila[7].read()),'utf-8') } lista.append(data) return lista At first I got the error "'NoneType' object has no attribute 'read'", I fixed this by changing the row number where the image attribute is located. 'imagen':str(base64.b64encode(fila*[7]*.read()),'utf-8') If you could help me understand what the error is trying to say, I would appreciate it very much. -
Django choice field validation in admin
I have a model that has a choice field with choices loaded in the runtime. from some_utils import get_currency_options class Product(models.Model): name = models.CharField(max_length=20) currency = models.CharField(max_length=3, null=True, blank=True, default="USD", choices=[]) def clean(self): # getting the currency options at execution time, options may vary at different times currency_code_options = get_currency_options() if self.currency and self.currency not in currency_code_options: raise ValidationError({"currency": f"Invalid currency code {self.fb_check_currency}."}) super(Product, self).clean() Please ignore the bad design here, it was defined like this since we need to integrate with a legacy system. In the Django admin, I have a form like this from some_utils import get_currency_options class ProductAdminForm(ModelForm): currency_choices = get_currency_options() @staticmethod def _values_list_to_options(values_list): return [(val, val) for val in values_list] def __init__(self, *args, **kwargs): super(ProductAdminForm, self).__init__(*args, **kwargs) self.fields["currency"] = ChoiceField(choices=self._values_list_to_options(self.currency_choices)) class ProductAdmin(admin.ModelAdmin): form = ProductAdminForm Now the problem is, when I go to Django admin and want to update the currency option, it fails to save with an error saying currency is not a valid option. I understand this is due to the choice list being empty, I tried to override the clean and clean_all method but it didn't work. Which method does the admin update operation trigger? Is there a way I can use the …