Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display template before running certain code in the view with Django
I have a Django site. One of my pages loads just some HTML and it is very quick at loading. I am adding some code that will send me a email when this page loads but the code takes a few seconds to execute. Instead of holding the entire page back waiting on this code to execute is it possible to display the template and then run this code? This is what I am running: msg = EmailMessage('Request Callback', 'Here is the message.', to=['email@yahoo.com']) msg.send() -
doesn't an epxlicit app_label
When i starting a new app, every time i getting this error. "RuntimeError: Model class JabaGames.apps.mainsite.models.games doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS." My other apps is renamed to short version 'appname' and i had same problem, but i fixed it, i don't know how. This error shows when i create a new app named "comments" my settings.py INSTALLED_APPS = [ 'users', 'comments', 'crispy_forms', 'blog', 'mainsite', 'grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] my comments/models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings import JabaGames.apps.mainsite.models class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey('article', on_delete=models.CASCADE) (trying to make a foreign key to other app, when i got an error (if you guys will tip me how to correctly import other model, i will be so happy) ) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.user.username) def __str__(self): return str(self.user.username) apps.py from django.apps import AppConfig class CommentsConfig(AppConfig): name = 'comments' every single app has a same code as comments/apps.py (is it a bad practice) -
How to implement QR code cross login from mobile app as authentication method for website or webapp in a vendor agnostic way?
I am using Django 2.2 for my webapp. And I have been looking for tutorials that cater for QR code cross login to webapp using mobile app. Basically the workflow is like this: expected workflow User arrives at website on desktop Given a choice of username/password or QR code login (We assume user is registered) User chooses QR code to login User is prompted to install mobile app (can be android or iOS) User installs mobile app and logins using username/password. On mobile app, user then agrees to future login using QR code as alternative (this is done once) After this, in future logins, when User chooses QR code to login as per step 3. They use the mobile app to scan QR code generated on the website login page. The mobile app then uses FaceID or FingerPrint ID (assuming iOS) to then allow login. The user presses a Yes button on the mobile app to confirm login. Somehow the webapp is notified dynamically and allows login on the desktop browser. I don't quite get how the mobile and the web app at the backend all work with one another to achieve this seamlessly. What I did find I did … -
Set ID to a field value
I have a form that a user can submit but I want the ID of the form to be the value of a certain field. For example, if a user submits a Recipe form for "pasta", I want the form ID to be "pasta". Then the user can access the recipe by entering the URL http://127.0.0.1:8000/recipe/pasta. I feel like this needs to be done in the view and urls file. views.py class CreateRecipeView(CreateView): form_class = RecipeForm(auto_id=recipe_name) # This would be the value of the recipe_name def get_success_url(self): return reverse("recipe_update/{}/".format(recipe_name)) urls.py path('recipe_update/<str:pk>/', views.UpdateRecipeView.as_view(), name='recipe_update') -
Django _set.add() method doesn't do what I hope it would, but does not give me any errors either
So, I am working on a Django-based website (Django 3) and I am trying to use a file to add certain elements into the database. While reading the file and its data works smoothly, the script seems to stop abruptly on this line: studentClass.student_set.add(student) Right before that, I have lines like these being executed with no problem: school = get_object_or_404(School, pk=form.cleaned_data['school'].pk) studentClass, created = StudentClass.objects.get_or_create( school=school, name=form.cleaned_data['name'], grade=form.cleaned_data['grade'] ) . . . print("\nSUCCESS!\n") print("\nAttempting to add {} to {}".format( student, studentClass)) studentClass.student_set.add(student) <---- SUSPECTED CULPRIT! The output from the print statement to the console: Attempting to add (<Student: 1 - Jessica>, False) to 1 - HenMei The second print("SUCCESS!") statement is not executed, thus I am quite sure that studentClass.student_set.add(student) is the line that's causing some trouble. Since I am a beginner, I may very well be wrong. Models are defined as follows: class StudentClass(models.Model): school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=25) grade = models.PositiveSmallIntegerField(default=1) class Meta: ordering = ['grade', 'name'] def __str__(self): return "{} - {}".format(self.grade, self.name) class Student(models.Model): studentClass = models.ManyToManyField(StudentClass) student_number = models.PositiveSmallIntegerField() first_name = models.CharField(max_length=50) gender = models.CharField(max_length=6, default='Female') class Meta: ordering = [F('student_number').asc(nulls_last=True)] def __str__(self): return "{} - {}".format(self.student_number, self.first_name) Last but not least, … -
Iterate in django views
I have problem with iteration all over the list in django views.py file from django.shortcuts import render, redirect, HttpResponse from django.views.decorators.http import condition import time import roundrobin STATES = [ "hello", "world" ] get_roundrobin = roundrobin.basic(STATES) def test(request): for i in get_roundrobin(): return HttpResponse(i) Django answers me only first symbol of the each element of the STATES list, I mean django return "h" then "w" instead "hello" then "world", how to fix it? -
Create object and child objects in DRF
I have 2 Serializers, Order and OrderDetail: class OrderSerializer(serializers.ModelSerializer): detail = serializers.SerializerMethodField() class Meta: model = Order fields = ['pk', 'user', 'date', 'status', 'detail '] def create(self, validated_data): order= Order.objects.create(**validated_data) detail_data = validated_data.pop('detail') if detail_data : for detail in detail_data : OrderDetail.objects.create(order=order, **detail) return order def get_detail(self, obj): """obj is an order instance. Return list of dicts""" queryset = OrderDetail.objects.filter(order= obj) return [OrderDetailSerializer(m).data for m in queryset] and class OrderDetailSerializer(serializers.ModelSerializer): """ Just in case if its needed for create for multiple instances """ def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(OrderDetailSerializer, self).__init__(many=many, *args, **kwargs) order = serializers.PrimaryKeyRelatedField(queryset=Order.objects.all()) product = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all()) class Meta: model = OrderDetail fields = ['pk', 'order', 'product', 'quantity','individual_price'] In postman I send: { "user": 1, "date": "2020-06-02", "status": "Approved", "detail": [ { "product": 2, "quantity": "3", "individual_price": "15.00" }, { "product": 1, "quantity": "1", "individual_price": "10.00" } ] } And it throws the following error: KeyError at /api/v1/order/ 'detail' Request Method: POST Request URL: http://localhost:8000/api/v1/order/ Django Version: 3.0.3 When I print the data its showing this: {'user': <User: test>, 'date': datetime.date(2020, 6, 3), 'status': 'Approved'} Seems like detail its a read only field, dont know if its for the SerializerMethodField. About that, I need detail with … -
Django Require Particular Version of Python to be Used
I edited my settings.py file to have the following at the very bottom: [requires] python_version="3.7" When I run python manage.py runserver, I get the following error message: NameError: name 'requires' is not defined what am I doing wrong? -
Not able to add message when a search is not met in the database
I am trying to add a message to the template when a search is not yet in the DB. So, there is an view from tour_store app which retrieves the data from the db and loads into the destination.html template: tour_store/destinations function: def destinations(request): destinations = Destinations.objects.all() return render(request, 'destinations.html', {'destinations': destinations}) and search/do_search function: def do_search(request): if request.method == "GET": # 'q' is the name in the search form // tour_title is the name that will be searched from Destination model destinations = Destinations.objects.filter(location__icontains=request.GET['q']) return render(request, 'destinations.html', {'destinations': destinations}) the place the search form is main.html: <form action="{% url 'search' %}" method="GET" class="header__search"> <div class="input-group search-input"> <!-- Change the search input phrase here --> <input type="text" name="q" placeholder="Search for `Thailand`." class="form-control"> <div class="input-group-append"> <button class="btn btn-warning" type="submit" name="button"><i class="fas fa-search"></i></button></div> </div> </form> destination.html {% for destination in destinations %} {% if destination in destinations %} <div class="row" data-aos="fade-up" data-aos-anchor-placement="top-bottom" data-aos-duration="1000"> <div class="col-md-7"> <a href="{% url 'destinationDetails' id=destination.id %}"> <img class=" embed-responsive img-fluid rounded mb-3 mb-md-0" src="{{ destination.image.url}}" alt=""> </a> </div> <div class="col-md-5 "> <h3>{{destination.tour_title}}</h3> <h6>{{destination.location}}</h6> <p >{{destination.description|safe|slice:":150"}}...</p> <p class="text-secondary"><i class="text-info far fa-calendar-check"></i> <strong>{{destination.booking_start_date}} - {{destination.booking_end_date}}</strong></p> <h3>€ {{destination.price}}</h3> <a class="btn btn-info rounded py-2 btn-block" href="{% url 'destinationDetails' id=destination.id %}"> View … -
How do I hash a file name when saving file to model django?
How does hashing work with models? I want to hash the name of video files that upload to my model. models.py class VideoUpload(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True) -
Preserve user input after submitting in Django form
I am trying to create a website using Django. I am not familiar with Django and I have a problem. I would like to create a form that has file selection for video uploading and two different buttons which are “Upload” and “Save”. I don't want to save video directly to the database using one button. Because of that, I need two buttons. When a user selects a file and clicks the “Upload” button, the video should be uploaded. Then, if the user clicks the “Save” button, the video should be saved into the database(model). There is no problem in the video selection and uploading process. However, when I click the “Save” button, the video cannot be saved since the video vanishes after clicking the “Upload” button. HTML file: <form method="post" enctype="multipart/form-data" id="form1"> <div class="form-group" > <label for="exampleFormControlFile1">Upload your video: </label> {% csrf_token %} {{ form.as_p }} </div> <button class="btn btn-primary btn-lg" name="upload_bttn" id="bttn1" type="submit" >Upload</button> <button class="btn btn-primary btn-lg" name="save_bttn" type="submit" >Save</button> <p>Uploaded file: <a href="{{url}}" target="_blank">{{url}}</a></p> views.py def video_upload(request): context = {} if request.method == 'POST' and 'upload_bttn' in request.POST: uploaded_file = request.FILES['videofile'] task_name = request.POST['task'] env_name = request.POST['environment'] light_name = request.POST['lightcondition'] fs = FileSystemStorage() file_name = fs.save(uploaded_file.name, … -
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.