Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make Django Data-Url Attribute string form to work in .prepend
In my javascript .prepend action, how to I make the data-url attribute a string so the script works? script.js $("#file-table tbody").prepend( "<tr><td><a href='" + data.result.url + "' target='_blank'>" + data.result.name + "</a></td><td class='delete'><button type=submit data-id='file-{{file.id}}' data-url="{% url 'esr_submit:delete_file' file.pk %}" class='file-delete-btn btn btn-danger btn-sm'>X</button></td></tr>" ) -
How to execute a method on every objects of a queryset in Django and return a list?
I have a ForeignKey relation between two models and I would like to execute a method on all objects and return the result in a list (or on every objects of a queryset). How can I do that? For example: status = Market.objects.all().is_update() print(status) [True, False, True] if all(status): pass This is how my models look like: class Exchange(models.Model): pass class Market(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, related_name='market', null=True) update = models.BooleanField(null=True, default=None) def is_update(self): # do stuff return True # or return False And this is how I do actually, but there must be a single line solution: upd = [] for market in Market.objects.all(): upd.append(market.is_update()) Thank you -
Uploading CSV files to S3 directly through Django
I am creating a django application which is connected to Amazon S3 to save user upload files. This is done using django-storages. During the course of the app a CSV file is generated. I am able to save the file locally. But how can I upload the file directly to S3 without saving it locally? I have tried using StringIO but that generates a Unicode Error. Any suggestions/solutions will be much appreciated! -
Django how to separate MultiSelectFields
I have multiselectfield for choice categories, I need it because users will set many categories. I made query by display as RadioSelect, but now I want to display it with icons, next to selector. Every each categories should have different icon. This is my form class SearchForm(forms.Form): nazwa = forms.CharField(max_length=50, label="", required=False, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Wpisz nazwe firmy...', 'label': 'nazwa'})) kategoria = forms.ChoiceField(choices=JOB_CHOICES, # empty_label='Wybierz kategorie...', widget=forms.RadioSelect(attrs={'class': 'slice slice-xs bg-section-secondary', })) And this is my photo what i actually have And how i want to display it : [ -
Updating progress bar in Django with values from python file without Celery and Ajax
I am very new to Django. I am trying to create a progress bar in index.html file, which will check for the completion of a particular task in python file and send the status continously (through render) to index.html file. The html file will have progress bar which will continuously monitor the progress and update it on the fly. I have seen posts about progress bar with celery , but it is not supported in windows. Please excuse me for mistakes since it is my first post here. -
Which is the best place to learn Django from? [closed]
I want to learn something new after flutter where should I learn Django from any good YouTube Video link? -
How to process a file uploaded using a form in Django?
I built a form with a FileField in order to upload file to be processed. Strangely it seem that file is closed before I can do anything with in the view. I encounter a ValueError after validating the form: "I/O operation on closed file" I can see that file is properly detected but closed when attempting to read it. Note: Django version 2.2.25. forms.py class FileImportForm(forms.Form): headers = ["lastname","firstname","gender","title","entity","email","company","address","phone"] file = forms.FileField(label='CSV file',validators=[CsvFileValidator(headers)]) def clean_file(self): file = self.cleaned_data['file'] return file views.py @login_required def file_import(request): if request.method == 'POST': form = FileImportForm(request.POST,request.FILES) if form.is_valid(): if request.FILES['file']: file_post = request.FILES['file'] # Offending line below (I/O operation on closed file) file_content = file_post.read().decode('UTF-8') return redirect("/foo") else: form = FileImportForm() return render(request,"file_import.html", { 'form': form }) How to properly process uploaded file (read, etc..)? -
Django no module named 'main'
I was working on a Django project on my PC, Then I create a app named "register" and I'm getting a weird error when I try to run manage.py runserver: im using Python 3.8.3. this error occurs when i added forms for registration. File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python38\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'main' my settings.py: DEBUG = True ALLOWED_HOSTS = ['*'] SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'simple2', "crispy_forms", 'main.apps.MainConfig', 'register.apps.RegisterConfig', 'register' ] ... -
How can i get {{form}} value with javascript?
there is a piece of my html code: <!-- STEP 1: class .active is switching steps --> <div data-step="1" class=""> <h3>Załóż fundację:</h3> <div class="form-group form-group--inline"> <label> Nazwa <input type="text" name="name" id="name" /> </label> <label> Opis <input type="text" name="description" id="description" /> </label> </div> <div class="form-group form-group--buttons"> <button type="button" class="btn next-step">Dalej</button> </div> </div> <!-- STEP 2 --> <div data-step="2"> <h3>Podaj typ fundacji</h3> <div class="form-group form-group"> {{form1}} </div> <div class="form-group form-group--buttons"> <button type="button" class="btn prev-step">Wstecz</button> <button type="button" class="btn next-step">Dalej</button> </div> </div> In the step1, i am able to get the values from inputs by id, like: var name = document.getElementById('name').value; How can i do such a thing with the {{form1}}, it is kind of select field: class AddFundationTypeForm(forms.Form): type = forms.ChoiceField(choices=type_of_organization) type_of_organization is a a dict, with 3 key-value pairs. -
I added a mobile column in auth_user in postgres(working on django).But getting error:User() got an unexpected keyword argument 'mobile'
This is my views.py from django.shortcuts import render, redirect from django.conf.urls import url from .models import Category,Product from django.contrib.auth.models import User, auth def signup(request): if request.method == "POST": first_name=request.POST['first_name'] last_name=request.POST['last_name'] email=request.POST['email'] mobile=request.POST['mobile'] password=request.POST['password'] cpassword=request.POST['cpassword'] user=User.objects.create_user(first_name=first_name,last_name=last_name,email=email,mobile=mobile,password=password) user.save(); return redirect('/') else: return render(request,"signup.html") I added a column directly in postgres named mobile and didnt make any kind of changes in django regarding that.Please help me in proceeding -
django Localdate doesn't return correct date
I am running a django where i have some sort of conditions written based on the date. My views.py file from django.utils import timezone def my_method(current_date=timezone.localdate()): logger.info(f"Current date is obtained as {current_date}") Whenever i load the page, my views.py internally calls this method and the date doesn't gets updated daily. In settings.py TIME_ZONE = 'PST8PDT' USE_TZ = True Irrespective of today's date, it always prints old dates and after few days the date gets updated to correct date and the same date gets continued for next 4-5 days. What is that i am doing wrong here ? P.S. I have also tried using python's native datetime.date.today() which resulted in same abnormal behavior. -
I have an error in my Django accounts app
I was following the tutorial on https://simpleisbetterthancomplex.com/series/2017/09/25/a-complete-beginners-guide-to-django-part-4.html and I have an error message which says that account_views is not defined. In my urls.py file which is located in C:\Users\vitorfs\Development\myproject\myproject. Here is the code from django.conf.urls import url from django.contrib import admin from accounts import views as account_views from boards import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^signup/$', accounts_views.signup, name='signup'), url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'), url(r'^boards/(?P<pk>\d+)/new/$', views.new_topic, name='new_topic'), url(r'^admin/', admin.site.urls), ] The error is on line 25, url(r'^signup/$', accounts_views.signup, name='signup'), which states that account_views is not defined. I would like to know why I am getting this error, and also, can you show me how to fix this error? -
Facing error when I deploy my django app on heroku
Hey I am facing these error when I try to deploy django project on heroku can anyone please help me to solve these error these error occur when I run these command git push heroku master on my cmd ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/deployex.git' -
The request is invalid. Details: parameters : Invalid JSON. A token was not recognized in the JSON content
I'm trying to post to the azure search service using a django post request. I'm getting an issue saying my JSON is invalid, but it passes validation in JSON validators. This is my function. def uploaddd(request): url = 'https://hs.search.windows.net/indexes/hotels/docs/index?api-version=2020-06-30' data = { "value": { "@search.action": "upload", "HotelId": "133", "HotelName": "Secret Point Motel", "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", "Description_fr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", "Category": "Boutique", "Tags": ["pool", "air conditioning", "concierge"], "ParkingIncluded": "false", "LastRenovationDate": "1970-01-18T00:00:00Z", "Rating": 3.60, "Address": { "StreetAddress": "677 5th Ave", "City": "New York", "StateProvince": "NY", "PostalCode": "10022", "Country": "USA" } } } headers = {'Content-Type': 'application/json', 'api-key': 'key'} response = requests.request('POST', … -
Transfer data | Django Heroku
How to transfer data from the local database to the production database for Django app deployed in Heroku. I've just deployed my project, but after the migration, the models was empty. -
Django - How and Where to sort self-referencing model by function
I have a self-referencing model "Location" like this : class Location(BaseArticle): name = models.CharField(max_length=200) parent_location = models.ForeignKey("self", blank=True, null=True, help_text="Fill in if this location is a smaller part of another location.", on_delete=models.SET_NULL) description = HTMLField(blank=True, null=True, help_text="A description of the location and important features about it") def __str__(self): parent_location_string = "" parent_location = self.parent_location while parent_location is not None: parent_location_string = f'{parent_location.name} - {parent_location_string}' parent_location = parent_location.parent_location return f'{parent_location_string}{self.name}' Now when I use Locations with generic Update/Create Views I get a drop-down menu of all locations, since they're ForeignKeys and that's just how generic views and forms handle ForeignKeys. I would like to have the list of locations in the dropdown alphabetically sorted, but not by the name-field of a location, but by it's __str__() method, e.g. through sorted(location_list, key=lambda x:str(x)). Time is generally not an issue, I am working with small datasets (<500 entries) that are unlikely to grow beyond 500. What I tried so far: Since I'm trying to sort with a function, I can't sort in the model through the Meta classes "ordering" option Sorting in the Manager by overwriting get_queryset() and using sorted() loses me all the abilities of queryset objects, since sorted() returns a list. … -
Frequent data migrations for adding similar data in Django
In my current project we need to add plenty of new database instances (and in future we will have to do that as well) which are very similar and simple. I've decided to do that using data migrations rather than doing it manually (to prevent errors and save time). But after some time data migrations came problematic because of merging conflicts, migration conflicts etc. We need some alternative. I thought about some script which when ran will feed/sync database with specified objects in e.g. dictionary. Is it ok approach? Is there more common good practice for such case? Thank you -
Problems with django api on second request
I am working on a flutter app for creating schedules for teachers. I created a Django project to generate a schedule based on the data in the post request from the user. This post request is sent from the flutter app. The Django project doesn't use a database or anything, It simply receives the input data, creates the schedule and returns the output data back to the user. The problem is that the process of creating the schedule only works 1 time after starting the Django server. So when I want another user to send a request and receive a schedule I have to restart the server... Maybe the server remembers part of the data from the previous request?? I don't know. Is there somekind of way to make it forget everything after a request is done? When I try to repeatedly run the scheduler without being in a Django project it works flawlessly. The Scheduler is based on the Google cp_model sat solver. (from ortools.sat.python import cp_model). The error I get when running the scheduler the second time in a Django project is 'TypeError: LonelyDuoLearner_is_present_Ss9QV7qFVvXBzTe3R6lmHkMBEWn1_0 is not a boolean variable'. Is there some kind of way to fix this … -
Django Elasticsearch DSL - How to Index models with UUID fields
As the title suggests, I'm wondering if it is possible to index UUIDFields() within the Document model? I've traweled the documentation, sunscrapers documentation and a few other resources - but I can seem to find anything/implementations of solutions? -
How to limit int values and str length in a re_path URL
I have a url that takes an int kwarg: re_path(r'^posts/(?P<signature>\w+)/(?P<post_id>[0-9]+)/$', post_detail_view) How do I: limit this so the post_id can only be 1 to 10 (inclusive)? Ie. not 0 or anything 11 and above. limit signature to be 128 chars or less? -
how to display total orders in django template within a loop
hie i want to display the order for each customer within a loop this is may view def clientes(request): all_clientes = Utilizadores.objects.filter(user_type='cliente') all_orders = Checkout.objects.all() context={'all_clientes':all_clientes,'all_orders':all_orders} return render(request,'todos-clientes.html',context) my template: {% for all_clientes in all_clientes %} <div class="item_wrapp"> <div class="contxt _7000"> <div class="img-def-doc-2 _9090903"> {% if all_clientes.imagem%} <div class="img_cliente"style="background-image: url({{ all_clientes.imagem.url }}");> </div> {% else %} <div class="img_cliente"></div> {% endif%} </div> <div class="main_name_do_wrapp"> <div class="nome_produto">{{all_clientes.nome}}</div> </div> <div class="extra_item_1_wrapp produto"> <div class="data provincia_cliente">{{all_clientes.provincia}}</div> </div> <div class="extra_item_1_wrapp produto"> {% for all_orders in all_orders %} {% if all_orders.user_id == all_clientes.id %} <div class="data num_encomendas_cliente">{{ all_orders.user_id|length }} encomendas </div> {% endif %} {% endfor %}` any help i would appreciate thank you. -
If user leaves the page delete object in django
I have a coupon system and i want to delete it from the order once the user leaves the checkout page, i tried Checkout page : window.onbeforeunload = function(e) { $.ajax({ url: "{% url 'mainapp:delete_coupon' %}", type: "post", async: false, data:{ 'user':request.user, } }); console.log('print yes'); return undefined; }; Views: def delete_coupon(request): if request.method == "POST": user = request.POST['data'] print(user) else: print('somethin') -
Filter on annotation in Queryset (Django)
I have following situation: Every Site can have multiple users, one user is the owner. When listing all the sites I want to order on the owner's name. There is no field in the Site model 'owner' so this needs to be done via annotations?. I have following code now: sites = Site.objects.all() sites = ( sites.prefetch_related( Prefetch( "users", queryset=UserSite.objects.filter(owner=True).defer( "user__first_name" ), ), ) .annotate(owner_name=F("users__user__first_name")) ) So I try to create the "owner_name" field. But the thing is, when a site has multiple users it doesn't filter on the owner=True and so the ordering is not correct. Can't I just do something like this: .annotate(owner_name=F("users__user__first_name").filter(users_owner=True)) -
Django find unique combination of ids in queryset
For example I have a model named User that have fields first_name and last_name how I can find ids of unique combinations objects? My progress for now: User.objects.values( 'first_name', 'last_name' ).annotate( names_count=Count(F('first_name') + F('last_name')) ).filter( names_count__gt=1 ).values( 'first_name', 'last_name' ) But this finds only duplicates first_name and last_name and I need objects ids. -
How to get array data within particular indexes in django-rest-framewr
Suppose I have array data stored in my Postgres, such as "citations": [ "82", "60", "53", "45", "43", "41", "41", "33", "28", "27", "25", "23", "20", "19", "17", "16", "15", "15"] Can I access elements within certain indexes from the citations array through a GET request? For example, a (hypothetical) query such as http://127.0.0.1:8000/users?query=citations?start_index=0?end_index=4 would return the elements 82,60,53,45,43 ? This would help me for creating an infinite scrolling for my JavaScript front-end.