Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I index a Boolean Field with low 'True' cardinality MySQL?
I have a MESSAGE table with 1M rows (and growing). Every query for messages involves selecting rows WHERE isRequest = True or WHERE isRequest = False, but never both. This table is written to extremely frequently and I need to maintain fast writes (as users love to send messages to each other with low latency). Also note that the MESSAGE table currently has no column indexes other than the primary key. 95% of the rows have isRequest = False and only 5% of rows have isRequest = True. Is it more performant to index the isRequest boolean field in such a scenario? In addition, I understand that indexing columns consumes memory but is this overhead equivalent for all column data types including, in my case, boolean values? -
Django: HTML "audio" button not playing specific filename
I've encountered a very strange error and am wondering if any of you fine folks know what is going wrong. I am trying to build a website in Django which at certain points needs .wav static files to play. Usually, the html audio element will do this. However, when the name of the file is "3.wav", the file will not load, even though they are identical files. views.py: ... return render(request,"polls/exam_question.html", context) static folder: 2.wav 3.wav polls/exam_question.html (Working): {% load static %} <audio controls src="{% static '2.wav' %}"></audio> polls/exam_question.html (Not Working): {% load static %} <audio controls src="{% static '3.wav' %}"></audio> Any suggestions will be very greatly appreciated! -
link to django password reset not displaying
the link to password reset is not showing console output of password reset Hi there, Someone asked for a password reset for the email address root@gmail.com, Follow the link below: http://127.0.0.1:8000 {% url 'password_reset_confirm' uidb64=uid token=token %} i used below code for my urls and i created all templates html files but the link not showing path("accounts/", include("django.contrib.auth.urls")), -
Django Formsets Errors: Unexprected Keyword Argument 'auto_id'; and Failed Lookup for key [form]
I keep getting errors when trying to render formsets. I have tried virtually everything under the same, but 2 recurring errors: When I use crispy formset: VariableDoesNotExist at /real_property Failed lookup for key [form] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'formset': }] When I use {{ formset }}. RealProperty() got an unexpected keyword argument 'auto_id' Here is my abridged models.py: class RealProperty(models.Model): auto_increment_id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, primary_key=False, on_delete=models.CASCADE) no_real_property = models.BooleanField("No interest in real property", blank=True) Here is my forms.py: class RealPropertyForm(forms.ModelForm): class Meta: model = RealProperty # exclude = ['user'] fields = ['no_real_property', 'real_property_description', 'real_property_location', 'real_property_type', 'real_property_purpose', 'real_property_who_ownership', 'real_property_ownership_type', 'real_property_interest', 'real_property_current_value', 'real_property_secured_claim1_text', 'real_property_secured_claim1_type', 'real_property_secured_claim1_amount', 'real_property_secured_claim2_text', 'real_property_secured_claim2_type', 'real_property_secured_claim2_amount', 'real_property_secured_claim3_text', 'real_property_secured_claim3_type', 'real_property_secured_claim3_amount', ] def __init__(self, *args, **kwargs): # self.user = kwargs.pop('pass_id') super(RealPropertyForm, self).__init__(*args, **kwargs) # REAL PROPERTY FORM ATTRIBUTES self.fields['real_property_description'].widget.attrs[ 'placeholder'] = 'Provide an easily identifiable name for this ' \ 'property' self.fields['real_property_location'].widget.attrs[ 'placeholder'] = 'Street address, city, state, zip' self.fields['real_property_secured_claim1_text'].widget.attrs[ 'placeholder'] = 'Claimant # 1: Name, Address, Phone' self.fields['real_property_secured_claim2_text'].widget.attrs[ 'placeholder'] = 'Claimant # 2: Name, Address, Phone' self.fields['real_property_secured_claim3_text'].widget.attrs[ 'placeholder'] = 'Claimant # 3: Name, Address, Phone' # REAL PROPERTY FORM self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Save and Continue')) self.helper.layout = Layout( ... I … -
How to combine Filterview with Formview?
I want to add Search Box in Django-Tables2 and Download Form. I made it by referring to the site below. https://django-tables2.readthedocs.io/en/latest/pages/filtering.html Below is my code. view.py from django_filters.view import FilterView from django_tables2 import SingleTableMixin from django_views.generic import FormView class TestView(SingleTableMixin, FilterView, FormView): template_name = "mytemp.html" # Table with Search Box model = MyModel filterset_class = MyFilter table_class = MyTable # Form form_class = MyForm success_url = "mytemp.html" def form_valid(self, form): ''' Download Def ''' mytemp.html {% load static %} {% load render_table from django_tables2 %} {% load bootstrap3 %} <!-- Table with Search Filterset Form --> {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} {% render_table table 'django_tables2/bootstrap.html' %} <!-- Download Form --> <form method="post"> {% csrf_token %} {{ forms.down.as_p }} <input type="submit"> </form> [Current action] If made as above, only Form of FilterView declared first in View is generated, and FormView is not. [Expected action] Both FilterView and FormView form should come out. -
how-do-i-alter-an-uploaded-file-content-in-django-before-its-saved-and upload it gain [closed]
I want to make file converter app in Django though i am stuck in initial phase , As a newbie to Django, I could not find any up-to-date example/snippets. May someone post a minimal but complete (Model, View, Template) example code to do so? i need to choose a file from system and before uploading it I want to modify that file and then want to upload it say just add one line at the end file type = txt file. -
Wagtail migration fails when using django-tenants or django-tenant-schemas
I'm trying to set-up a Wagtail-based SaaS application using django-tenants in order to have a single Postgres schema for each tenant. I have installed django-tenants strictly following the documentation on ReadTheDocs and I successfully managed to migrate the public schema. However, when I add the first tenant via Django Admin, migration wagtailcore.0037_set_page_owner_editable fails with the following error: tenants_1 | Applying wagtailcore.0037_set_page_owner_editable... db_1 | ERROR: cannot ALTER TABLE "wagtailcore_page" because it has pending trigger events db_1 | STATEMENT: SET CONSTRAINTS "wagtailcore_page_owner_id_fbf7c332_fk_auth_user_id" IMMEDIATE; ALTER TABLE "wagtailcore_page" DROP CONSTRAINT "wagtailcore_page_owner_id_fbf7c332_fk_auth_user_id" db_1 | ERROR: cannot DROP TABLE "wagtailcore_groupcollectionpermission" because it has pending trigger events db_1 | STATEMENT: DROP SCHEMA "tenant_galilei" CASCADE tenants_1 | Internal Server Error: /django-admin/customers/client/add/ tenants_1 | Traceback (most recent call last): tenants_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute tenants_1 | return self.cursor.execute(sql, params) tenants_1 | psycopg2.errors.ObjectInUse: cannot ALTER TABLE "wagtailcore_page" because it has pending trigger events tenants_1 | Internal Server Error: /django-admin/customers/client/add/ tenants_1 | Traceback (most recent call last): tenants_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute tenants_1 | return self.cursor.execute(sql, params) tenants_1 | psycopg2.errors.ObjectInUse: cannot ALTER TABLE "wagtailcore_page" because it has pending trigger events tenants_1 | tenants_1 | tenants_1 | The above exception was the direct cause of the … -
Django Convert All Webp Images In Template To Png/Jpg Just On Apple Safari Browsers
If using webp images by default in Django, how would you go about converting the webp images from the database to either png or jpg just on Apple Safari browsers while keeping the default webp for every other browser? Would Pillow be the way to do this? How would you combine it into the views and the template for loop? from PIL import Image image = Image.open("test.webp").convert("RGB") image.save = ("test.jpg", jpeg) image.save = ("test.png", png) Detect User Agent: https://pypi.org/project/django-user-agents/ Maybe an alternative would be to detect the user agent in the headers? Would the converted images need to be stored in the project_name/media/ folder (which is where {{ object.thumbnail.url }} currently points to? Or would it go into project_name/static/? Maybe the images could be deleted (cron job maybe) after the Safari session closes or changes to a different view? Not sure the best way to do this. Code: HTML: {% for object in object_list %} <img src="{{ object.thumbnail.url }}" alt="{{ object.thumbnail_alt }}"/> {% endfor %} Models.py: class Course(models.Model): thumbnail = models.ImageField(blank=True, null=True, max_length=255) thumbnail_alt = models.CharField(blank=True, null=True, max_length=120) Views.py: class CourseListView(ListView): model = Course template_name = 'courses/course_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) … -
How can I replicate "bulk_delete()" functionality in Django? [duplicate]
In Django's ORM you are able to bulk_create(objs) where objs is a list of Model objects. I have a long list of Model objects that I would like to bulk_delete, is this possible? -
Django: How to render/refresh web page multiple times
I'm not sure how to render/refresh page multiple times during one execution. Example: I'm running selenium tests on the background and I would like to update page after each run. Each test returning some data and separately they are working perfectly. def runtest1(request): title = Task.objects.get(test_name='runtest1').title test_result = calculate_words(title) update_tests('runtest1', test_result) return test_result def runtest2(request): title = Task.objects.get(test_name='runtest2').title test_result = test_links(title) update_tests('runtest2', test_result) return test_result and then render def index(request): tasks = Task.objects.all() test_result = TestResult('', '', '') if request.GET.get('runtest1'): test_result = runtest1(request) if request.GET.get('runtest2'): test_result = runtest2(request) context = {'tasks': tasks, 'test_result': test_result} return render(request, 'tasks/list.html', context) I would like to run all these tests in one run and update page after each test. Something like this: def run_all(request): runtest1(request) runtest2(request) return runtest3(request) Could you please help me to solve this issue? -
How can I render a Django template tag stored in a TextField?
I have a Django site where I can publish short news articles. My articles regularly contain links to other pages on the site, and I'd rather use <a href="{% url 'spam' %}"> to link to the page instead of hardcoding the url like <a href="/spam"> in case I end up changing my URL scheme later. I'm displaying the contents of the TextField in my page template using the safe tag like this: {{ article.body|safe }} so I can put HTML in the contents of the body field of my Article model. What do I have to do in my page template so I can render Django template tags when they're stored in a TextField? -
Defining a property method in Django with a ForeignKey
I'm working with my Django app, in which I have two models: Store and Turn. There is a one-to-many relationship where a store has many turns that need to be processed. This is the code: class Store(models.Model): name = models.CharField(max_length=20) adress = models.CharField(max_length=40) image = models.ImageField(upload_to=) @property def average_wait_time(self): return #here's the problem def __str__(self): return self.name class Turn(models.Model): store = models.ForeignKey(Store, on_delete=models.SET_NULL, null=True) creation_time = models.TimeField(auto_now=True) completion_time = models.TimeField(blank=True, null=True) def complete(self): self.completion_time = timezone.now() def __str__(self): return f'Turno a las {creation_time} para el Negocio {completion_time}' As you can see, I have a @property method that I need to use in order to calculate the average wait time in a store, determined by the average of the turn durations. How can I make this work? I cannot access the Turn model from the 'Store' model... -
How to check if Django Queryset returns more than one object?
Basically I have what I'm hoping is a simple issue, I just want to check if the Queryset contains more than one object but I'm not sure how to do it? What I've written (that doesn't work) is below. {% if game.developer.all > 1 %} <h1>Developers:</h1> {% else %} <h1>Developer:</h1> {% endif %} -
Why does django's `apps.get_model()` return a `__fake__.MyModel` object
I am writing a custom Django migration script. As per the django docs on custom migrations, I should be able to use my model vis-a-vis apps.get_model(). However, when trying to do this I get the following error: AttributeError: type object 'MyModel' has no attribute 'objects' I think this has to do with the apps registry not being ready, but I am not sure. Sample code: def do_thing(apps, schema_editor): my_model = apps.get_model('app', 'MyModel') objects_ = my_model.objects.filter( some_field__isnull=True).prefetch_related( 'some_field__some_other_field') # exc raised here class Migration(migrations.Migration): atomic = False dependencies = [ ('app', '00xx_auto_xxx') ] operations = [ migrations.RunPython(do_thing), ] A simple print statement of apps.get_model()'s return value shows the following: <class '__fake__.MyModel'>. I'm not sure what this is, and if it is a result of not being ready. -
Run Gunicorn service on DigitalOcean starting a Django project
I have the following systemd file at /etc/systemd/system/gunicorn.service [Unit] Description=Gunicorn daemon for Django Project Before=nginx.service After=network.target [Service] WorkingDirectory=/home/serverapp ExecStart=gunicorn --name=avesoft --bind unix:/home/serverapp/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py WebApp.wsgi:application Restart=always SyslogIdentifier=gunicorn User=root Group=www-data [Install] WantedBy=multi-user.target When I manually change the directory to /home/serverapp and run gunicorn --name=avesoft --bind unix:/home/serverapp/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py WebApp.wsgi:application everything works fine and Nginx connects to my Django app through Gunicorn. But by rebooting the server, I get Bad Gateway error that seems Gunicorn has not started working. I don't get what is the reason behind my service file not working. -
With Django Factory Boy, how do I generate a factory for a foreign key?
I'm using Django 3 with Factory Boy 2.12.0. I have the following models. Notice the second depends on the first ... class ContactMethod(models.Model): class ContactTypes(models.TextChoices): EMAIL = 'EMAIL', _('Email') PHONE = 'PHONE', _('Phone') type = models.CharField( null=False, max_length=5, choices=ContactTypes.choices, ) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) class Meta: unique_together = ('phone', 'email',) class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() I want to create a factory to generate the Coop model, so I tried the below (included contact method factories as well) ... class PhoneContactMethodFactory(factory.DjangoModelFactory): """ Define Contact Method Factory for a phone number """ class Meta: model = ContactMethod type = ContactMethod.ContactTypes.EMAIL phone = "8005551234" class EmailContactMethodFactory(factory.DjangoModelFactory): """ Define Contact Method Factory for emails """ class Meta: model = ContactMethod type = ContactMethod.ContactTypes.EMAIL email = "test@example.com" class CoopFactory(factory.DjangoModelFactory): """ Define Coop Factory """ class Meta: model = Coop name = "test model" enabled = True phone = PhoneContactMethodFactory() email = EmailContactMethodFactory() web_site = "http://www.hello.com" @factory.post_generation def addresses(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A … -
Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response - Django
I am using Django with Django rest framework to host my api's (localhost:8000), and use vue js running on node js server (localhost:8080) to call the apis to view it. when I try to use vue axios to call a rest api I get this response: Access to XMLHttpRequest at 'http://localhost:8000/api/getJobs' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. My Django setting.py is (I installed cors headers / allow all origins) but no luck, here is my code: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'app_dashboard', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True //My rest api in view and also associate a url for it in urls.py @api_view(['GET']) def get_jobs(request): #... code goes here return HttpResponse(json_obj, content_type="application/json" ) Any solution? Note: I already seen a lot of post like this cors enable in Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response but didn't work! -
Difference between django vs django 2.2?
I noticed on a Youtube Channel, CodingEntreprenuers, that he has tutorials for django. On his github, there are just "tryDjango" and "tryDjango2.2". I was wondering what differences that they have and I'd like to get recommendations from you gurus to choose which version is better for me^^ My Skill Level: Python: Intermediate C: Intermediate-ish, probably a beginner, it's an ancient language Linux: Been on it for about 1 year, a bit familiar with terminal Trying to make the best out of quarantine, help. Keep Safe -
why is my code overriding my base.html navbar?
So, I am creating a profile page and the JS script I need is overriding my base.html navbar. How can can I get it to not do that? Basically it's moving my navbar to the left only on this specific page. I am not sure how I can keep the navbar intact without taking the JS script entirely away. profile.html {% extends "dating_app/base.html" %} <title>Profile</title> <!DOCTYPE html> {% block head %} <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> </head> {% endblock %} {% block content %} <title>Profile</title> <div class="container"> <div class="row"> <div class="panel panel-default"> <div class="panel-heading"> <h4 style="color:#CB2603 " >My Profile</h4></div> <div class="panel-body"> <div class="col-md-4 col-xs-12 col-sm-6 col-lg-4"> <img alt="User Pic" src="{{ profile.photo.url }}" id="profile-image1" class="img-circle img-responsive"> </div> <div class="col-md-8 col-xs-12 col-sm-6 col-lg-8" > <div class="container" > <h2>{{ profile }}</h2> </div> <hr> <ul class="container details" > <h3 >About me</h3> <p><span style="width:50px;margin:50px"></span>{{ profile.description }}</p> </ul> <hr> {% if user.id == profile.id %} <p><a style="color:#CB2603 " href="{% url 'dating_app:update_account' profile.id %}">edit profile</a></p> {% endif %} </div> </div> </div> </div> {% endblock content %} base.html {% load bootstrap4 %} {% load static %} {% load unread_messages_counter %} <!-- Navbar is located in this file --> <!doctype html> <html lang="en"> <head> <!-- … -
my UpdateView in CBV for formset not saving the form
i want to update my formset , but it wont be updated , only the parent fields will be updated if you could do something with my issue let me know please , i will appreciate your helps .. this is my UpdateView class MyUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView): model = MyModel form_class = MyModelForm template_name = 'template/template.html' def get_context_data(self,*args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['formset'] = MyUpdateInlineFormSet(self.request.POST,instance=self.object) data['formset'].full_clean() else: data['formset'] = MyUpdateInlineFormSet(instance=self.object) return data def form_valid(self,form): self.object = form.save() context = self.get_context_data() formset = context['formset'] with transaction.atomic(): if formset.is_valid() and form.is_valid() and formset.cleaned_data!={}: formset.instance = self.object formset.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('my_app:invoice',kwargs={'pk':self.object.pk}) and this is my inlineformset MyUpdateInlineFormSet= inlineformset_factory( MyModel,MyChild,form=MyChildForm,fields=( some fields ),extra=1) i much appreciate your helps ... -
Ensure 2 choice fields on a record are not equal in Django
I have a model with 2 CharFields selected from nearly the same list of choices. They are the same except for the 2nd inclination having a "None" option. class Pawn(models.Model): primary_inclination = models.CharField(max_length=30, choices=PRIMARY_INCLINATION_CHOICES) secondary_inclination= models.CharField(max_length=30, choices=SECONDARY_INCLINATION_CHOICES) I want to ensure the same value can not be selected for both fields. For example, if my choices are selected from A, B, C, then A and B is fine, but A and A is not. It is ok for another Pawn to also have A and B. Some things I've looked into: Specifying unique fields in Meta, but this makes the inclinations only selectable by 1 Pawn unique_together, no other pawn can have the same values for the two fields -
What is the best way to allow change permissions depending of some conditions in django rest framework?
I am building an api with Django rest framework and I am using ModelViewSet with a CustomObjectPermissions and it is working fine for any user with the right permission but I want know how can I allow any user to update his own profile? I mean this user can not update other users but if the user id is the current user id he can update some columns. This user does not have any django permission, he have just access to the app.Finally, I want to use this with DjangoObjectPermissions. Views.py here I want to allow any user update his own profile from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import status, permissions, generics, viewsets from rest_framework.response import Response from rest_framework.views import APIView from .serializers import MyTokenObtainPairSerializer, UserSerializer from .models import User from authentication.permisssions import CustomObjectPermissions class ObtainTokenPairView(TokenObtainPairView): permission_classes = (permissions.AllowAny,) serializer_class = MyTokenObtainPairSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ permission_classes = (CustomObjectPermissions,) queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permissions.py from rest_framework import permissions class CustomObjectPermissions(permissions.DjangoObjectPermissions): """ Similar to `DjangoObjectPermissions`, but adding 'view' permissions. """ perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], 'HEAD': ['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } -
Why isn't Django connecting to SQL Server 2019?
Please see below screenshots as to existing configuration (password hidden due to security reasons). Databases Screenshot 1 Python Packages The error that is returned when I attempt to run the server is either SQL Server v15 is not supported or Django 3.0 is not supported. Does anyone have the same issue and a clean-cut solution for resolution? -
'RelatedManager' object is not iterable -> add all() -> 'list' object has no attribute 'all'
Sorry if my wording is weird; I'm not overly familiar with Django Models. I want our API's list of category Tags, which is an instance of our TagCollection model: categories, new = TagCollection.objects.get_or_create(name="Category") I want to then loop over these Tags, held in the tag_set attribute of TagCollection: for category in categories.tag_set: This gave me the error TypeError: 'RelatedManager' object is not iterable. I looked it up, and as this thread mentioned (as well as many others), I needed to add .all() in order to iterate. So I tried that: for category in categories.tag_set.all(): And received the error AttributeError: 'list' object has no attribute 'all'. What gives? I thought it was a RelatedManager? Any help would be greatly appreciated. -
Django automatically run redis server
So I have a Django app that has a live chat build using channels. I am using Redis for the channels layer and every time I want to run the app I have to run the Redis server first. How can I make it so the Redis server runs together with the Django app? And if I host the app how will this work - like how would I run Redis server if I host it on Heroku for example? Thanks in advance!