Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to populate a select field in django from remote json API and validate it?
I have a model based on geographical data. I'm using an API provided by the French Government using zipcodes to retrieve related city names. For avoiding mispellings or typos, I'm planning to use a select box (which acts as an input field server-side) populated with the results of this API depending on the zipcode provided by the user. Client-side, its working. I'm able to make jQuery populate the select options correctly. Anyway, server-side, the validation is not working. I was able to make it work using a custom class : class DynamicChoiceField(forms.ChoiceField): def valid_value(self, value): return True But this is always returning True. How can Django handle that type of field which is (for me) quite common ? Thanks in advance for your help :) -
Insert icons into third td while two further tds are empty
I need some help with jQuery to insert two icons into td id="person-action-{{ person.id }}" while two futher tds with the same {{person.id}} are empty f.e. <td id="person-phone-{{ person.id }}"></td> <td id="person-email-{{ person.id }}"></td> <td id="person-action-{{ person.id }}"></td> I've just made some simple code. $(document).ready(function(){ var emptyPhone = $('#person-phone-{{ person.id }}').is(':empty') var emptyEmail = $('#person-email-{{ person.id }}').is(':empty') $('#person-action-{{ person.id }}').each(function(){ if (emptyPhone || emptyEmail ){ // do something } }); }); -
How to force redirect_uri to use HTTPS with python-social-app?
I am using django framework with python-social-app and have an error while trying to login with Facebook login button. My app consists of three docker containers: Django app. Database. NGINX + SSL cert. Here is my error: Authentication process canceled: URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs. Blockquote and here is the URL that i can see while trying to login https://www.facebook.com/v2.9/dialog/oauth?client_id=247739632734206&redirect_uri=http%3A%2F%2Fwww.DOMAN_NAME.com%2Fcomplete%2Ffacebook%2F&state=7AySpKwDWAKtiIxP75LBIPqwQNWSu36y&return_scopes=true The problem, as i can see it, is that redirect_uri starts with HTTP and not with HTTPS. Django==2.2 social-auth-app-django==3.1.0 social-auth-core==3.1.0 My best guess about the problem is that Django app don't "know" that it's running behind the NGINX+SSL and generates the redirect_uri with HTTP protocol instead of HTTPS. Facebook settings has correct redirect URI that starts with HTTPS. The problem is not specific to Facebook, redirect_uri for Google has the same problem. How can I force the python-social to to use HTTPS? -
Periodic tasks not scheduling using celery beat
I am using django celery beat in my django project.This is my code in tasks.py #tasks.py from celery import shared_task @shared_task def newtask(): f = open("test.txt", "a") f.write("test\n") f.close() #settings.py CELERY_BEAT_SCHEDULER ="django_celery_beat.schedulers:DatabaseScheduler" I run celery beat using this command celery -A app worker -B -l INFO And then I setup my tasks from admin panel to be executed at 16:53.The task doesn't get executed.What could be the issue? EDIT) If I first setup my task from admin panel and then start the celery beat worker then my task gets executed but If I setup the task after after starting the worker it doesn't work.What could be the reason? I have attached screenshot for refrenece -
Zip and download files as a stream with Django / AWS S3
I've a need to allow users to download contents of an entire folder on S3, via my django app. Typically, I'd want to create a zip file (using files retrieved from boto3) then send it back as a response. This great blog post from botree shows how. However, this could be a lot of data and this code stores (in memory, or with some adaptation, on the HDD) all of it on my server as an intermediary step. I don't want to store a preprocessed zip file on S3, as this would substantially increase storage cost (as well as requiring a frequent task runner to update it), and I can't simply store a zip instead of the folder because of other S3 integrations and versioning. The question I've read about StreamingHttpResponse, where I append bytes gradually as they're calculated in a response, but have never used it. Can I do that in this case (e.g. append bytes as they're fetched from AWS?) and if so, how? Note: It doesn't have to be .zip, it can be .tar.gz or similar if that works! -
Gunicorn cannot not find modules
I am trying to run a django-docker image via gunicorn. However, gunicorn does not find my modules. I tried to use gunicorn in a venv. (adding CMD exec source venv/bin/activate in the Dockerfile.) This is also not working. What am i doing wrong? Dockerfile FROM python:3.6.7 MAINTAINER Jasper ADD . /usr/src/app WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt EXPOSE 8000 CMD exec gunicorn bomt_project.wsgi:application --preload --bind 0.0.0.0:8000 --workers 3 I expect the server to be running on port 8000. The output however is ModuleNotFoundError: No module named 'widget_tweaks' -
Get all django warnings in logs
I'm using the django logger: https://docs.djangoproject.com/en/2.2/topics/logging/ and sometimes I log some warnings: try: some code except: logger.warning("something bad happened, but move forward") Now at the end of my program I want to supply the user with all the warnings, so I'm looking for something like logger.getAllWarnings(). Is there a method like that or I have to keep a list of warnings that I pushed to it and then get it at the end? -
Django filter on relational data
I defined some models in Django with relationships. When I want to get data by filtering relation data I got error. Models: class User(models.Model): UserId = models.CharField(max_length=255, primary_key=True) Username = models.CharField() RelatedPerson = models.ForeignKey( People, db_column='PersonId', on_delete=models.CASCADE, ) class Staff(models.Model): RelatedUser = models.ForeignKey( User, on_delete=models.CASCADE, db_column='StaffUserId', related_name='RelatedUser' ) My query is this: staff = Staff.objects.filter(RelatedUser__UserId=user_id).first() And this is the error I get : django.db.utils.ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'id'. (207) (SQLExecDirectW); [42S22] [Microsoft][ODBC Driv er 13 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") -
Django: How to get the data from a form
I am trying to create a fake payment method when a user decide to rent a car, then can click pay, so i created a form Pay to get the information, but when user clicks pay the data stores immediately to db, what i am trying to do is creating a second step like, here is your entered info are you sure you want to pay? And then proceed, that's why i was thinking to extract the data from the form and save it temporarily and only after use clicks yes, I am sure or something, then save to db. The answer is fine to be theoretically because this is a learning project. {% extends "base.html" %} {% block content %} <div class="container"> <div class="card-header bg-info text-white"> <h4> <i class="fas fa-cc-visa"></i> Pay </h4> </div> <div class="card-body"> <form class="form form-horizontal" action="{% url "pay_car" car_id %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Proceed" class="btn btn-primary" style="clear:both; margin: 10px 0"/> </form> </div> </div> {% endblock %} -
Apply modifications on QuerySet's annotation
Having a following model I need I need to apply some function on the each record's image_url (pre-sign it with expiration token). class Item(models.Model): name = models.CharField() image_url = models.CharField() # other fields omitted and a query set qs = Item.objects.filter(q).annotate(name=F('name'), image_url=F('image_url)).values('name', 'image_url').annotate(count=Count('name')) I solved it with mapping a function to the resulting list as here: def update_url(x): x['image_url'] = create_presigned_url(x['image_url']) return x sale_items = map(lambda x: update_url(x), list(qs)) Is there a better way, can it be applied on the query set before list() evaluation? -
How to display a tree in select2?
I have a Categories tree (MP_Node). It is necessary to display them in the form of a tree at the select2. models.py class Category(MP_Node): .... forms.py class ProductCreateForm(forms.ModelForm): class Meta: model = Product fields = ( ...., 'category', .... ) def __init__(self, *args, **kwargs): super(ProductCreateForm, self).__init__(*args, **kwargs) self.fields['category'].empty_label = None self.fields['category'] = ModelChoiceField(queryset=Category.objects.all(), widget=forms.Select( attrs={'class': 'select2', 'style': 'width: 165px'})) html <div class="field inline select"> <label for="id_category" class="subhead">Категория:</label> <select name="category" style="width: 165px" required="" class="select2 select2-hidden-accessible" id="id_category" tabindex="-1" aria-hidden="true"> <option value="" selected="">---------</option> <option value="1">Food</option> <option value="4">Meal</option> <option value="2">Sweet</option> <option value="3">Milk</option> <option value="9">Sport</option> <option value="6">Football</option> <option value="7">Ball</option> <option value="5">Form</option> <option value="8">Shirt</option> <option value="10">T-Shirt</option> <option value="11">Attribute</option> </select> <span class="select2 select2-container select2-container--default select2-container--focus" dir="ltr" style="width: 165px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-id_category-container"><span class="select2-selection__rendered" id="select2-id_category-container"><span class="select2-selection__placeholder"> </span></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span> </div> I get select Food Meal Sweet Milk Sport Football Ball Form Shirt T-Shirt Attribute Need to receive Food Meal Sweet Milk Sport Football Ball Form Shirt T-Shirt Attribute -
How to highlight searched queries in result page of Django template?
I have the following search query in views.py: class SearchView(View): def get(self, request, *args, **kwargs): queryset = BlogPost.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) | Q(content__icontains=query) ).distinct() context = { 'queryset': queryset, 'query': query, } return render(request, 'blogs/search_result.html', context) and if I search a word like Tesla the results shown in result template is as below: Please help me, how do I highlight the searched query in yellow color in Django templates? Thank you for help! -
Django: How To Build Canteen Menu Booking System To Avoid Co-Occurrence Book?
So basically I am in the project for creating a kiosk application for a canteen. In general, this is the flow of the kiosk application that I want: The user selects the food/drinks. The user enters his table number. The kiosk checks the stock of the user's foods/drinks. If it is available, proceed otherwise cancel it. The kiosk books the items for preventing other kiosk application ordering that items since the items are limited (for example only 50 units). The booking will expire at a certain time. (For example, the user forgets to bring his debit card so he will leave the kiosk). The user makes payment. The kiosk POST the order to the web server. Order is done. The kiosk print the receipt. This is my current model: Menu Item class Menu(models.Model): image = models.ImageField(upload_to=path_and_rename) name = models.CharField(max_length=100) price = models.IntegerField() category = models.IntegerField() //Food or Drink availability = models.BooleanField(default=False) qty = models.IntegerField(default=100) //It will reach 0 when sold out. sellerID = models.ForeignKey(Seller, on_delete=models.PROTECT) Order class Order(models.Model): cardID = models.IntegerField() amount = models.IntegerField() time = models.DateTimeField(auto_now_add=True) Order Detail class OrderDetail(models.Model): orderID = models.ForeignKey(Order, on_delete=models.PROTECT) menuID = models.ForeignKey(Menu, on_delete=models.PROTECT) price = models.IntegerField() qty = models.IntegerField() tableNumber = models.IntegerField() done = … -
Anyone can connect Hitcorp/ZKTeco Accessdoor device with django?
Anyone can connect accessdoor device of ZKTeco/Hitcorp to Django Project? I got some tutorial in google,but its just for python2 and oodo project Can someone help me? Thanks You can see the photos below https://www.bukalapak.com/p/perlengkapan-kantor/alat-kantor/mesin-absensi/bouy1h-jual-magic-ms8800-rfid-access-door-keypad-lan?blca=SEUSC-TESTC&blpt=SEUSC-TESTC&gclid=Cj0KCQjwzunmBRDsARIsAGrt4muOWux8nBkPocMPBlEQw9aWrFVfsf7zQtz2tcwH0rZyLEqHOBKscUgaAsz1EALw_wcB Magic MS8800 RFID Access Door - Keypad - LAN -
Django filter icontains returns no results when string contains whitespace - mysql.connector.django
I have a search autocomplete box that returns courses when users enter a query string. This is working fine on my development server, but when deployed to live it only returns results when the user enters a single word and not multiple words separated by spaces. This is an issue as the course titles can contain spaces. For reasons beyond my control, I am having to use mysql.connector.django as the database backend. I have limited access to the configuration of the database. This is the code that works in development but not in live when querying the same database: courses = (Course.objects.filter(module__open=True, module__term__academic_year__live=True) .filter(title__icontains=query) .distinct() .order_by('category__title', 'title')) These are the database settings: DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', ... 'PORT': '3306', 'OPTIONS': { 'use_pure': True } } } use_pure is set due to this bug. I am aware that MySQL queries do not factor in case by default, but I would have thought that using icontains would still return results. -
Auto submitting a form when user is out of the page
I'm trying to figure how to auto submit a form once the user is out of the page. Is there a way? Code: <form class="carform" method="get"> <input type="hidden" name="number_plate" value="{{ car.number_plate }}"> </form> So when a user clicks a back button or type in another url, the form will automatically submit the form, so it can send the value inside the form and other views can catch the get method. -
How to work with foreign key in django template and forms?
I have a special form which represent me a list of data, but the problem is that it works very slowly, so is there something like django autocomplete_fields for forms? my form: class TripSearchForm(forms.Form): departure = forms.ModelChoiceField(queryset=Place.objects.places_for_segment()) destination = forms.ModelChoiceField(queryset=Place.objects.places_for_segment()) def places_for_segment(self): return Place.objects.filter(Q(role=Place.CITY) | Q(role=Place.VILLAGE) | Q(role=Place.TOWN)) -
Django: How to get an amount of posts from db in a ListView
I have this ListView and at now it takes every Car obj from database and posts in homepage, how do i limit to only take an x amount of posts? class CarListView(ListView): model = Car template_name = 'home.html' context_object_name = 'cars' ordering = ['-created'] paginate_by = 6 -
Django: Invalid block tag on line 41: 'endblock', expected 'empty' or 'endfor'
I am working on a project right now, particularly on the CRUD phase. I am also new on the Django framework, but I knew some basic stuff about it. I did everything stated on the manual but it's weird because I got this kind of error. I am using Django 2.2. Here's my code, by the way. base.html <!-- base.html --> <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title>{% block title %}Title{% endblock %}: CAO-SMS Admin</title> {% load static %} <link rel = "stylesheet" href = "{% static 'fisher_prof/style.css' %}"/> </head> <body> {% block body %}Body{% endblock %} </body> </html> list.html <!-- Displays the whole database (fisher) --> {% extends 'fisher_prof/base.html' %} {% block title %} Fisher's Information {% endblock %} {% block body %} <br> <center> <h1>Fisher's Database</h1> <table class = "table table-striped table-bordered table-sm"> <thead class = "thead-dark"> <tr> <th>ID&nbsp&nbsp</th> <th>Fisher's Last Name</th> <th>Fisher's First Name</th> <th>Fisher's Middle Name</th> <th>Mobile Number</th> <th>Actions</th> </tr> </thead> {% for fisher in fishers %} <tr> <td>{{fisher.last_name}}</td> <td>{{fisher.first_name}}</td> <td>{{fisher.mid_name}}</td> <td>{{fisher.cell_num}}</td> </tr> {% endfor %} </table> <br> <br> </center> {% endblock %} Then when I run it, Django tells me this: "Invalid block tag on line 41: 'endblock', expected 'empty' … -
Clone model field created with Django faker during test
I use Django Faker to generate ramdom data and it works great. I need to check in a model that two fields responsible and customer in a peculiar situation are identical. Here is my factory class: class FirstQuoteRequest(DjangoModelFactory): label = Faker("sentence") description = Faker("sentences") customer = SubFactory(UserFactory) responsible = customer By typing responsible = customer, I thought I'd add a clone of customer value but in this case, it's a clone of the function that returns a ramdom value which is not what I want. I thought of using @post_generation like this: @post_generation def responsible(self, create: bool, extracted: Sequence[Any], **kwargs): self.responsible = self.customer self.save() But it raises an Integrity error. Is it a way to have this equalization between customer and responsible? Which one? -
How to raise multiple non-field errors
The clean method is the place to raise non-field errors: def clean(self): cleaned_data = super(MyForm, self).clean() if condition1(cleaned_data['f1'], cleaned_data['f2']): raise ValidationError('Condition1 error') if condition3(cleaned_data['f3'], cleaned_data['f4']): raise ValidationError('Condition2 error') But what if I want to raise both so that the user sees all errors at once instead of having to correct them one by one? This is possible with field errors passing a dictionary to ValidationError, but what about non-field errors? -
How can I restrict file type for the the wagtail.documents.blocks.DocumentChooserBlock?
So I would like to restrict the type of file that an admin can choose to upload to the CMS using the wagtail.documents.blocks.DocumentChooserBlock. I can't seem to find any documentation anywhere. This is the most I have found http://docs.wagtail.io/en/v2.0/topics/streamfield.html#documentchooserblock. I looked through the code to see if they render an input field perhaps. But its a button. <button type="button" class="button action-choose button-small button-secondary">Choose a document</button> That opens a chooser model that selects previously uploaded documents or upload a new one. I have also looked to find the template files for the chooser. But I have not been able to find where that input is located. It seems like a lot of work to override the chooser template. Here I am adding the DocumentChooserBlock. class IndicatorWidgetsBlock(blocks.StreamBlock): flourish = blocks.StructBlock( [ ('label', blocks.CharBlock(required=False, help_text="This widget's tab label on the indicator")), ('title', blocks.CharBlock(required=True)), ('hide_title', blocks.BooleanBlock(default=False, required=False)), ('html_file', DocumentChooserBlock(required=True)), ('sdg', blocks.ChoiceBlock(required=False, choices=sdg_choices, label='SDG Goal')), ('source', blocks.RichTextBlock( features=['link'], required=False)), ], icon='code', template='takwimu/_includes/dataview/code.html' ) class Meta: icon = 'form' I want to restrict the type of file uploaded. -
How can i insert a python script of recommandation in Django?
i'm new with django framework, and i try to develop a web page HTML with django, and i want to insert my python script of recommendation. My goal is to have a page like as Amazon (is just an exercice for me, for learn to devlope with django). my page have image of products like coca cola, beer, eggs ... and what i want is, when a user clicked on beer for exemple, he redirect him in a new page and recommande him to buy an other product with him beer like peanut . Actualy, i developed my HTML page. and i don't know, how can i do to communicate my click in image and my python script. I don't know if i'm clear or not. if anyone can help me thank's for advenced -
Is there a better way to access list element?
I'm doing a tournament manager in Python 3.7.3 working with Django. I have a "Team" model which contain a foreign key to a "Pool" model. I'd like to update fields of my team instances in a specific way (depending on the number of pools). And then in my template I'd like to display pools and teams associated to the pools. I wrote this code and for me, it's good (but no): views.py teams = Team.objects.filter(category=category).order_by('position') ... pools = Pool.objects.filter(phase=phase) pool_count = pools.count() pools_list = list(pools) teams_list = list(teams) x_prec = -1 x = 0 for team in teams: if x > x_prec: team.pool = pools_list[x] team.save() print("asc: " + str(pools_list[x])) x_prec = x x = x + 1 if x == pool_count: x_prec = 0 x = -1 if x < x_prec: team.pool = pools_list[x] team.save() print("desc: " + str(pools_list[x])) x_prec = x x = x - 1 if x == -pool_count: x_prec = -1 x = 0 ... template {% extends 'base_tournament.html' %} {% load crispy_forms_tags %} {% block title %} Tournament {% endblock %} {% block navbar_manage %} {% include 'navbar_manage.html' %} {% endblock %} {% block content %} <h1>Phase started</h1> {% for pool in pools %} <h3>{{ … -
I want to make a questionnaire form that asks questions based on answers given
I want to develop a simple questionnaire system in Django such like: Dialog example: Are you hungry? (Yes/No) Yes: What would you like to eat? (Hamburger/Pizza/Pop Corn/Chicken) Hamburger: Nice, I will order a hamburger for you! Pizza: Would you like pizza with mushrooms? (Yes/No) Yes: Ok, I will order the best pizza in town for you No: No? Well... stay hungry then No: Ok. Call me when you're hungry. How it can be done?