Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dumpdata in .json collides in UTF-8 problem
I archived migrations in .json file. (venv) D:\scraping_service>python manage.py dumpdata scraping > scraping.json PyCharm informs that "File was loaded in the wrong encoding: 'UTF-8'" And Cyrillic symbols are not displaying. How to deal with this, if, in theory, UTF-8 is the right encoding for Cyrillic symbols? -
merge two id data in python
I want to merge two different id conversation data. I tried something like this below but didn't got helpful, If anybody could help me for what i exact want to achieve would be much appreciated. thank you so much in advance. output result: "data": [ { "id": 13, "conversation": [ { "id": 31, "from_user": "shopowner", "to_user": "carowner", "message": "hello", } ], }, { "id": 14, "conversation": [ { "id": 32, "from_user": "carowner", "to_user": "shopowner", "message": "hey", } ], } ] expected result: "data": [ { "conversation": [ { "id": 31, "from_user": "shopowner", "to_user": "carowner", "message": "hello", }, { "id": 32, "from_user": "carowner", "to_user": "shopowner", "message": "hey", } ], }, ] what i tried is: for record in data: data1 = str(record['conversation']) data2 = str(record['id']) from itertools import chain all_results = list(chain(data1,data2)) sort_data = all_results.sort(key=lambda x: x["created_on"], reverse=True) main_data = [x for x in record['conversation']] print(main_data) If anybody could help me for what i exact want to achieve would be much appreciated. thank you so much in advance. -
Call a particular function of Class based view Django from urls.py
I have this views.py where I've implemented Class based views, but let's say I want to call a function get_featured_products when the url is https://localhost:8000/featured_products. What sould my urls.py look like to call the get_features_products function? from django.shortcuts import render from rest_framework import views from rest_framework.response import Response from .models import * from .serializers import * # Create your views here. class ProductView(views.APIView): model= Product serializer = ProductSerializer def get(self,request): qs = self.model.objects.all() serializer = self.serializer(qs, many=True) return Response(serializer.data) def post(self,request): serializer = self.serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error_messages()) def put(self,request,pk): product = Product.objects.get(id=pk) serializer = self.serializer(instance=product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error_messages) def get_featured_products(self,request): #some code here return None How should I refer to get_featured_products in my urls.py -
How to display Console output or progress bar in Django fronted html?
In my python Django project, I have some background process and it will take 2 to 3 minutes for complete. in between the user close the browser or tab, the process will be stopped. So i am trying to display the console out put (same as " print() ") in front end HTML pages on real time or show a Progres bar with Live status. kindly advise me how to do this. (I have tried with Django Messages and JavaScript DOM based on change Text functions. but it need to wait until complete all the process to return the function or pass the data via context, so that method not success in my case.) -
dropdown select list for django
I am learning Django right now and I try to add a dropdown list at the website and the page will change after users submit their selection. At form.py: class platformSelectForm(forms.Form): platformsList = ( ('all', 'Please Select'), ('NS', 'Nintendo Switch'), ('PS4', 'PlayStation4'), ('PS5', 'PlayStation5'), ('XBO', 'Xbox One'), ('XS', 'Xbox Series S/X'), ); platforms_Select = forms.ChoiceField(widget = forms.Select, choices = platformsList, required = False); At view.py: class showGameLists(TemplateView): template_name = "showList/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs); platformSelect = platformSelectForm(self.request.POST or None); context['platformSelect'] = platformSelect; At urls.py: from django.urls import path; from .views import showGameLists; urlpatterns = [ path('', showGameLists.as_view(), name='home') ] At home.html: <form method = 'POST' action = '/'> {% csrf_token %} {{ platformSelect.as_p }} <input type='submit' value='Submit' /> </form> right now, I can show the list and submit button. But I try lots of ways to get the value from the drop list, but it also wrong me: [17/Jan/2021 11:15:29] "POST / HTTP/1.1" 405 0 Method Not Allowed (POST): / Method Not Allowed: / what show I do? Thank you. -
Is this a circular import?
(follow up to: The included URLconf 'appName.urls' does not appear to have any patterns in it ) My site project directory looks like: (cryptocurrency, cryptoboard, cryptousers, frontend, leads, polls are apps). I think that: setup_debug_table.py(cryptocurrency): import random from datetime import timedelta from django.utils.datetime_safe import datetime from django.utils.timezone import now from .coins_constants import NO_OF_DAYS, NO_OF_HOURS, coins_ids from .models import Currency, Transaction, DebugConf from cryptoboard.cryptousers.models import CryptoUser def init_debug_tables(): # Check if debug table has already been initialized debug_conf = DebugConf.objects.all() if debug_conf.exists(): return # Clear tables CryptoUser.objects.all().delete() Currency.objects.all().delete() Transaction.objects.all().delete() specifically, line: from cryptoboard.cryptousers.models import CryptoUser is what's causing the error (CryptoUser is a model in a different app (cryptousers)), somewhat similar to this answer. models.py, on the other hand, looks fine: models.py(cryptocurrency) from django.db import models class DebugConf(models.Model): is_setup = models.BooleanField(default=False) debug_setup_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.is_setup class Currency(models.Model): currency_name = models.CharField(max_length=100, unique=True) currency_value = models.FloatField() currency_value_in_dollars = models.FloatField() currency_value_in_dollars_date = models.DateTimeField() def __str__(self): return self.currency_name class Transaction(models.Model): transaction_type = models.CharField(max_length=200) transaction_amount = models.FloatField() transaction_date = models.DateTimeField(auto_now_add=True) transaction_currency = models.ForeignKey(Currency, on_delete=models.CASCADE) transaction_buyer = models.ForeignKey('cryptousers.CryptoUser', related_name='transaction_buyer', on_delete=models.CASCADE) transaction_seller = models.ForeignKey('cryptousers.CryptoUser', related_name='transaction_seller', on_delete=models.CASCADE) def __str__(self): return self.transaction_currency Stack trace: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: … -
Django orm on apple m1
I'm trying to get concrete number of records in django model with 1m+ records through python manage.py shell using docker on apple m1 machine. Query: Model.objects.all()[:200000] But shell fails with message Killed. On machine with linux everything works fine. Any idea? -
Django doesn`t create locale files
I'm new at Django and can't solve the problem. I wanna realize multi-language on my django project but when I type django-admin makemessages -l ru, Django doesn`t create locale folder with files in it. I did everything according to the documentation. Maybe my English is bad. This is my settings from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'ru' USE_I18N = True LANGUAGES = [ ('ru', _('Russian')), ('uz', _('Uzbek')), ] This is views.py file from django.utils.translation import gettext as _ def index(request): phone = _('Welcome') return HttpResponse(phone) But in header.html (layout file) django translate one word, "Home" to "Начало" <li><a href="{% url 'index' %}" style="font-size: 18px;">{% trans "Home" %}</a></li> Thank you a lot -
Django RestFramework IsOwnerOrReadOnly
I create my permission class for everyone can read object and only admin create object. But when i log out and try to create object, permission class allowing me. What am i missing? models.py class Book(models.Model): title = models.CharField(max_length=20) content = models.TextField() page = models.IntegerField() views.py class BookAPIView( mixins.CreateModelMixin, generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = BookSerializer queryset = Book.objects.all() def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) permissions.py class IsAdminOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method == 'GET': return True return request.user.is_staff -
Testing a query parameter in django restframework
I am testing a query parameter in djnago restframework to retrieve the detail of an object. The query works in the browser but not the test. I think I am not calling the response correctly with: response = self.client.get(reverse('quote-requests:get-calculator-detail', kwargs={'calculator_code': self.calc1.calculator_code})) the apps urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('api/v1/quote-requests/', include('quote_requests.urls')), ] which includes the quotes.urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from quote_requests import views router = DefaultRouter() router.register('get-calculator', views.CalculatorCodeDetailViewSet, basename='get-calculator') app_name = 'quote-requests' urlpatterns = [ path('', include(router.urls)), ] The viewset is: class CalculatorCodeDetailViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = CalculatorCodeSerializer lookup_field = ('calculator_code') def get_queryset(self): return ( Calculator.objects.filter( calculator_code = self.request.query_params.get('calculator_code',) ) ) The CalculatorCodeSerializer is: class CalculatorCodeSerializer(serializers.ModelSerializer): class Meta: model = Calculator fields = ( 'name', 'calculator_code', ) The test is: def test_retrieving_calculator_detail_with_calculator_code(self): ''' test retrieving detail of a calculator ''' self.calc1 = Calculator.objects.create( name = "Calculator 1000", calculator_code = "HH1000", ) response = self.client.get(reverse('quote-requests:get-calculator-detail', kwargs={'calculator_code': self.calc1.calculator_code})) serializer = CalculatorCodeSerializer(self.calc1) self.assertEqual(response.data, serializer.data) This yields the error: Traceback (most recent call last): File "/app/quote_requests/tests/test_calculators_api.py", line 149, in test_retrieving_calculator_detail_with_calculator_code self.assertEqual(response.data, serializer.data) AssertionError: {'detail': ErrorDetail(string='Not found.',[14 chars]nd')} != {'name': 'Calculator 1000', 'calculator_cod[368 chars].25'} When checking the browser link: http://localhost:8000/api/v1/quote-requests/get-calculator/?calculator_code=HH1000 This works but test … -
Replace image src path using span
Is there any way how to replace the path location using span or etc. that comes from the Jquery, or is there any shorcut in Django?, Currently as you can see I'm trying to override the path that comes from my jquery src="/media/<span id=image></span>" It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance Jquery $(document).on('click', 'a[data-role=show_scanned]', function(){ let csrf = $('input[name=csrfmiddlewaretoken]').val(); var path = $(this).attr('id'); var assign = $("#image").html(path); $("#scanned_show").modal('show'); }); html retrieve <img class="card-img img-fluid mb-1" src="/media/<span id=image></span>" alt="Card image cap" style="width: 900px;height: 600px;"> -
How do I clear previous AJAX response data (NOT html/form data)? - Django/AJAX
I've built a Django app that submits an AJAX post request to my database. The initial post request works fine, but every previous request is also returned after the first response. Bottom line: Is there any way to clear the previous AJAX request/responses? Here's the first response when I start my server and submit my first request (the request is for pk:1): MedInput page loaded (index):46 Med Input Form Submitted (index):49 csrfmiddlewaretoken=i889gLsqdY9glqI59wRXLTOVehz9Lmp1i5IRikOsgvrGdBD9OpISolDrJ8pqJDmV&input_meds=lisinopril (index):53 (index):60 [{…}] (index):61 0: {model: "medrec_app.medication", pk: 1, fields: {…}} length: 1 __proto__: Array(0) This is what happens when I submit another request (this request is for pk:3): ... Med Input Form Submitted (index):49 csrfmiddlewaretoken=i889gLsqdY9glqI59wRXLTOVehz9Lmp1i5IRikOsgvrGdBD9OpISolDrJ8pqJDmV&input_meds=lisinopril (index):53 (index):60 (2) [{…}, {…}] (index):61 0: {model: "medrec_app.medication", pk: 1, fields: {…}} 1: {model: "medrec_app.medication", pk: 3, fields: {…}} length: 2 __proto__: Array(0) And here's what happens when I request pk:1 and pk:3 at the same time: ... Med Input Form Submitted (index):49 csrfmiddlewaretoken=i889gLsqdY9glqI59wRXLTOVehz9Lmp1i5IRikOsgvrGdBD9OpISolDrJ8pqJDmV&input_meds=lisinopril (index):53 (index):60 (4) [{…}, {…}, {…}, {…}] (index):61 0: {model: "medrec_app.medication", pk: 1, fields: {…}} 1: {model: "medrec_app.medication", pk: 3, fields: {…}} 2: {model: "medrec_app.medication", pk: 3, fields: {…}} 3: {model: "medrec_app.medication", pk: 1, fields: {…}} length: 4 __proto__: Array(0) I only want the responses from the … -
Updating the bulk_create objects in django
i have created the bulk_create and now i am not able to update that bulk objects.just pasting the piece of code of bulk_create. here is my views.py (specific code of bulk_create): UnsecuredTermLoanSetting.objects.bulk_create( [ UnsecuredTermLoanSetting(provience=provience_bc,perchentage=unsecured_rate_bc,cad=unsecured_cad_bc,mnthly_payment_percentage=unsecured_income_bc,min_days=unsecured_minimum_bc,max_days=unsecured_maximum_bc), UnsecuredTermLoanSetting(provience=provience_ab,perchentage=unsecured_rate_ab,cad=unsecured_cad_ab,mnthly_payment_percentage=unsecured_income_ab), UnsecuredTermLoanSetting(provience=provience_mb,perchentage=unsecured_rate_mb,cad=unsecured_cad_mb,mnthly_payment_percentage=unsecured_income_mb), UnsecuredTermLoanSetting(provience=provience_sk,perchentage=unsecured_rate_sk,cad=unsecured_cad_sk,mnthly_payment_percentage=unsecured_income_sk), UnsecuredTermLoanSetting(provience=provience_on,perchentage=unsecured_rate_on,cad=unsecured_cad_on,mnthly_payment_percentage=unsecured_income_on), UnsecuredTermLoanSetting(provience=provience_qc,perchentage=unsecured_rate_qc,cad=unsecured_cad_qc,mnthly_payment_percentage=unsecured_income_qc) ] ) Everything is working fine object creation has been done.But the question is how can i update those objects in one command. or something like that. -
showing am pm time in django to show when is morning when is evening
I want to show when a user log-in in my site he show when is Good Morning or When is Good Evening. django template either “good morning or afternoon” depending on time of day. Current template code is : {% if hour < 12 %} morning {% elif hour > 12 %} afternoon {% endif %} -
Django 3 rendering markdown break on newline
I have literally tried all the current markdown rendering libraries for Django (also not so current) Django Markdownify, Django Markdown 2 and Markdown Deux) and all have the same problem as described in this old question: How do I make django's markdown filter transform a carriage return to <br />? basically carriage returns is disregarded on rending. If I do {post.body|markdown|linebreaksbr}} it always results in 2 <p><p>1 line</p><br><br><p>1 line</p><br><br><p>2lines </p><br><br><p>2 lines </p><br><br><p> so my options are either none or 2 BR. I am confident that there is an easy solution for this. I can't believe that none of the Django libraries provides this minimal functionaly. -
How to make it possible to add more than one form for a user
I am having trouble creating a model for user availability I already have something like this models.py class Availability(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) date = models.DateField(null=True) starting_hour = models.TimeField(auto_now_add=False, auto_now=False, null=True) ending_hour = models.TimeField(auto_now=False, auto_now_add=False, null=True) def __str__(self): return str(self.user) When a user tries to add an availability for another day of the week, a message appears that the availability for that user already exists I would appreciate any help -
How to create delete button for deleting a record in django
I am trying to delete a record My views.py file is def AnnouncementDelete(request, pk): announcement = get_object_or_404(Announcement, pk=pk) if request.method=='POST': announcement.delete() return redirect('/') return render(request, 'classroom/announcement_confirm_delete.html') and my html file is {% extends "classroom/base.html" %} {% load crispy_forms_tags %} {% block content %} <form action="{% url 'classroom:AnnouncementDelete' announcement.id %}" method="post"> {% csrf_token %} <input type="submit" value="Delete cat"> </form> {% endblock content%} my url.py file has the pattern url(r'^delete/(?P<pk>[0-9]+)/$', views.AnnouncementDelete, name='AnnouncementDelete'), and the model from where I want to delete the record is class Announcement(models.Model): title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) def __str__(self): return self.title when I am trying http://127.0.0.1:8000/classroom/delete/1/ it is giving me the following error NoReverseMatch at /classroom/delete/1/ Reverse for 'AnnouncementDelete' with arguments '('',)' not found. 1 pattern(s) tried: ['classroom/delete/(?P[0-9]+)/$'] Also i am a beginner to django and not very familiar with ```url(r'^delete/(?P<pk>[0-9]+)/$', views.AnnouncementDelete, name='AnnouncementDelete'),``` way. I generally use the ```path`` way. -
Get all items from one model on condition that is in other model
Hi i was snooping around stack but answers are confusing or not working, you can see my models how can I get all OrderItems made by user that have complete=True in Order. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_oredred = models.DateField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) transaction_id = models.CharField(max_length=200, null=True) -
How can I run a Django 3 project with a MySQL server set on a NAS (Synology DS120J) using phpMyAdmin and MariaDB 10?
I appreciate the fact that the topic is quite specific, but I have been struggling to find documentation on such setup. I am working on a Django 3 project using Python 3.9, instead of SQLite3, the application would be using a MySQL server hosted on a Synology DS120J NAS, this is done via phpMyAdmin and MariaDB 10. Basically, my objective is to run the Django 3 application from my PC (Windows 10), and the MySQL server from the NAS. Both are sharing the same local network. Is anyone using a similar setup? If so could you please provide with some guidance? At the moment here is the DATABASES section of the settings.py file from the application: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'gaia', 'USER': 'root', 'PASSWORD': [phpMyAdmin password], 'HOST': '127.0.0.1', 'PORT': '[port number of the MariaDB 10 server on phpMyAdmin]' } } I launch the application using the following command: python manage.py runserver 192.168.0.2:[port number of the NAS]. When doing so, I get the following error message: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (10061)"). I have searched for this error message but didn’t get anything very helpful as I wasn’t sure whether any of the … -
Cannot resolve keyword 'name' into field. Choices are: categoria, categoria_id, detalle_compra,
I don't understand what I'm doing wrong. I am trying to do an autocomplete with the data from the Product table, I don't know what the reason is since I mention the name of the product but toa it as "name". I've done it but I keep getting this error: Cannot resolve keyword 'name' into field. Choices are: categoria, categoria_id, detalle_compra, ... Models class Producto(models.Model): id_producto = models.AutoField(primary_key=True) categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE) def __str__(self): return self.nombre def toJSON(self): item = model_to_dict(self) return item class Meta: verbose_name = 'Producto' Views def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'autocomplete': productos = Producto.objects.filter(name__icontains=request.POST['term']) for i in productos: data = [] item = i.toJSON() item['value'] = i.nombre data.append(item) else: JS $("#search").autocomplete({ source: function (request, response) { $.ajax({ url: window.location.pathname, type: 'POST', data: { 'action': 'autocomplete', 'term': request.term }, dataType: 'json', }).done(function (data) { response(data); }).fail(function (data) { alert("Error"); }).always(function (jqXHR, textStatus, errorThrown) { }) }, I have verified that it is not "name" however in none of the files I have made that equivalent. I hope you can help me -
Pylint-django raising error about Django not being configured when that's not the case (VSCode)
Pylint-django worked just fine up to version 2.3.x but since 2.4.0 it reports an error on every python-django file: Django was not configured. For more information runpylint --load-plugins=pylint_django --help-msg=django-not-configuredpylint(django-not-configured) This happens on VSCode and I believe I have it correctly configured: { "python.linting.pylintArgs": [ "--load-plugins", "pylint_django", "--load-plugins", "pylint_django.checkers.migrations", "--disable=C0114, C0115, W0222", "--disable=imported-auth-user", "--disable=invalid-name", "--disable=line-too-long" ] } This worked perfectly fine, as I said, up to v.2.3. I raised an issue on their repository but regrettably it was dismissed with little to no visible effort to address it. For the time being I'm staying with v.2.3.0, which lints with no issues with the above configuration, but would like to know if this is a bug or otherwise. Did any get into this issue or is it there anything else I'm missing? -
Prepend Serialized object with name
I have the following setup for my ListSerializer, which is called with a URL looking like "api/tax/2021-03-30": models.py class CityTax(models.Model): class Meta: verbose_name = "City Tax" verbose_name_plural = "City Taxes" season = models.ForeignKey(Season, on_delete=models.CASCADE, null=True) hotel = models.ForeignKey(Hotels, on_delete=models.CASCADE) EUR = models.DecimalField(max_digits=5, decimal_places=2) USD = models.DecimalField(max_digits=5, decimal_places=2) serializers.py class TaxSerializer(serializers.ModelSerializer): hotel = serializers.CharField(source="hotel.abbrev") season = serializers.CharField(source="season.title") class Meta: model = CityTax exclude = ['id'] api_views.py class TaxList(ListAPIView): serializer_class = TaxSerializer def get_queryset(self): """ Get city tax for appropriate season according to date of arrival """ url_date = date.fromisoformat(self.kwargs['start_date']) seasons = Season.objects.all() selected_season = Season.objects.get(start_date__lte=url_date, end_date__gt=url_date) return CityTax.objects.filter(season__title=selected_season) which returns a response that looks as follows: [ { "hotel": "DDC", "season": "A20", "EUR": "1.00", "USD": "1.19" }, { "hotel": "DSF", "season": "A20", "EUR": "1.13", "USD": "1.34" }, ] How can I prepend the result to look like this: [ "DDC" { "hotel": "DDC", "season": "A20", "EUR": "1.00", "USD": "1.19" }, "DSF" { "hotel": "DSF", "season": "A20", "EUR": "1.13", "USD": "1.34" }, ] I've been trying to figure out how to make this happen, but I feel like I'm looking in the wrong places (nesting serializers?) Thanks in advance! -
Not able to view/download Recipe 1m+ dataset
I have registered on: http://im2recipe.csail.mit.edu/dataset/login/ Post registration I am redirected to page saying verification failed with following error. "You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code." I did not get any verification mail too. Need help !! -
Load user from Firebase to Django
I am trying to load all the user from Firebase to Django Server. I have tried to read https://docs.djangoproject.com/en/3.1/howto/auth-remote-user/ but still can not figured out how to implement this function. How can I do that? or If anyone have a better idea can you suggest me. -
python3 django manage.py runserver
I'm running Django and I can't figure out why it's coming out like that. It turns out that Python and Django are installed. enter image description here