Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: cannot import CSS file from static
Django returns 404 error code while trying to import style.css file Hi, I have problem with loading static files. Error occurred in my main HTML file (frame.html - base for other files). I made everything for correct work of static files, here's all of the applications (code, images) to my problem: File system: ├── jdn ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── main ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── models.py ├── pdf.py ├── templates └── main ├── create.html ├── frame.html ├── main.html ├── minauth.html ├── report.html ├── searchinit.html ├── searchres.html ├── univerauth.html └── viewuser.html ├── tests.py ├── urls.py └── views.py ├── manage.py ├── media └── main ... └── static ├── admin ├── css ... └── main └── css └── style.css urls.py(core): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('main.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urls.py(app): from django.urls import path from . import views urlpatterns = [ path('', views.main, name='main'), path('token/', views.get_token, name='get_token'), path('create/', views.create_user, name='create_user'), path('search/', views.search_user, name='search_user'), path('token_report/', views.get_min_tok, name='get_min_tok'), path('report/', views.view_report, name='view_report'), path('view/<int:id>', views.view_user, name='view_user') ] settings.py: import os from pathlib import Path … -
MongoDB error in Django Admin interface: "Select a valid choice. That choice is not one of the available choices."
I am using Django with MongoDB with Djongo as the driver. I have the following two models: from djongo import models from djongo.models.fields import ObjectIdField, Field # Create your models here. class Propietario(models.Model): _id = ObjectIdField() Nombre = models.CharField(max_length=50) def __str__(self): return f"{self.Nombre}" class Vehiculo(models.Model): _id = ObjectIdField() Propietario_Vehiculo = models.ForeignKey(Propietario, db_column='Propietario_Vehiculo', on_delete=models.CASCADE) Modelo = models.CharField(max_length=25) Capacidad = models.IntegerField() Cilindraje = models.IntegerField() Placa = models.CharField(max_length=6) SOAT_Fecha = models.DateField() Operacion_Fecha = models.DateField() def __str__(self): return f"{self.Modelo} de {self.Propietario_Vehiculo}" Using the Django shell I am able to create and save Propietario objects and to link Vehiculo objects to their respecting owners using ForeignKey. However, any time I use the Django admin interface and input a Propietario to a new Vehicle, or try to save and existing one created with the Django shell, I get the error Select a valid choice. That choice is not one of the available choices. Any help would be greatly appreciated -
"Import "django.http" could not be resolved from source"
Just started learning Django by following the official documentation and came across this error. Naturally, I googled it to try and find a fix, but nothing helped. Everybody is saying to choose the right interpreter, but for me the right interpreter was chosen from the start, the one in the virtual environment folder (idk if that's how you say it, like I said I'm new so the terminology is still confusing) and it is still not working. -
How can I convert django serializer result to dict?
I want to send result of django serializer with help of requests library content = ParsingResultSerializer(instance=parsing_res, many=True).data # parsing_res is a django queryset print("XXXX_ ", content, flush=True) # prints OrderedDict [OrderedDict([('film_info', {'search_query': 'Джанго освобожденный', 'film': {'id': 8, 'suffixes': [], 'name': 'Джанго освобожденный', 'is_site_search': False, 'external_id': -1}}), ('url', 'https://kino-ep.net/4087-dzhango-osvobozhdennyy-2012.html'), ('priority', 21), ('search_request', 14317), ('page_checks', [OrderedDict([('id', 91845), But I need a dict, because I want to send the dict like this: response = requests.request("POST", url, headers=headers, data=content) How can I convert django serializer result to dict? I read about this way from django.core import serializers querydata = serializers.serialize("json",query) but how can i use my ParsingResultSerializer? -
How can I make a progressive login-rate throttle in Django?
I'm working on a Django/DRF app, and I'm trying to implement an API throttle that will have an increasingly-long delay for failed login attempts. Eg. lock the user out for 1 minute after 3 failed attempts, 10 minutes after 6 fails, 30 minutes after 9, etc., similar to what phones do and to what is fairly common to login pages in general. I was surprised to find that there doesn't appear to be a progressive throttle already built in to Django or DRF given how common that login scenario is... DRF Throttle option: The Django Rest Framework APIView provides a throttle_classes field & a get_throttles() method, and it has a handful of general throttles for doing a fixed-rate throttle delay. I can kind-of mimic a progressive rate by adding a list of throttles, like so: def get_throttles(self): return [ MyCustomThrottle('3/m'), MyCustomThrottle('6/10m'), MyCustomThrottle('9/30'), ] and then add a custom get_cache_key() method to MyCustomThrottle that returns a unique key that doesn't collide with the other throttles in the list. That almost works - it works for blocking a bot that just has its foot on the gas - however, it has a couple of problems: DRF throttles don't have an easy way … -
Store dic data after axtraction from database it is showing str type in django models
actually i am storing multiple data in django models.. class Spare(models.Model): vendor_name = models.CharField(max_length=100, blank=True, null=True) date = models.DateField(blank=False, null=False) # details fields sl_no = models.TextField(blank=True, null=True, default='{}') product_name = models.TextField(blank=True, null=True , default='{}') quantity = models.TextField(blank=True, null=True) cost = models.TextField(blank=True, null=True) # total fields from quantity and cost amount = models.FloatField(blank=True, null=True, default=0.0) But if i want to get data inthe form of dictionry but it's showing str type so i can't render into django template And how can i render data into django template -
How to override the update action in django rest framework ModelViewSet?
These are the demo models class Author(models.Model): name = models.CharField(max_lenght=5) class Post(models.Model): parent = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_lenght=50) body = models.TextField() And the respective views are class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostStatSerializer I am trying to perform an update/put action on PostViewSet and which is succesfull, but I am expecting different output. After successful update of Post record, I want to send its Author record as output with AuthorSerializer. How to override this and add this functionality? -
Django request.GET.get returns None
my view code is like this: def price(request): a = request.GET.get('apple') return render(request, 'price.html', {'a': a}) my html file is like: <form action="price/" > <label form='price/'>Qualitiy:</label> <input type="number" name={{ser.Name}}> <input type="submit" value="Buy"> </form> The url showed when submitted is: http://127.0.0.1:8000/web/meat_series/price/?apple=1 My expected result is '1'{{}} should be the apple.I have tried many times but it still show none.Can anyone help me? -
Сombine mutations in one in Strawberry Graphql
How to combine mutations in one? @strawberry.type class Mutation: @strawberry.mutation def login(self, email: str, password: str) -> LoginResult: @strawberry.type class Mutation: @strawberry.mutation def create_post(self, title: str, text: str) -> CreatePostResult: schema = strawberry.Schema(mutations = ....) -
Django validate queryset None
I have a queryset in order to check if the result is Null or exists cupon_existente = Orden.objects.filter(user = self.request.user, ordenado= False).values_list('promo', flat=True) when the result is 'None' and I want to validate like this: if cupon_existente: True else: False it validates as 'True' how can I validate that None is actually 'False' or 'NULL' ? -
How to implement a login page using Django Channels
I ma trying to make a server using Django and Channels and I want to make a login page. After some googling I have found answers on how to implement the backend, but what I want to know is: What should I do when it comes to the frontend and how can I link this to the backend? -
DJango GET Request from database into JSON
I got a question with my Django project. I have a database and want to get data into JavaScript with a fetch request. The data should just be in JSON. This was my attempt with Serializer. Is there a more easy way, than writing a whole serializer.py. Does anybody have an idea what to do. JavaScript: fetch('', { method: 'GET', }) .then(response => response.json()) .then(data => { console.log(data); }); DJango views.py: def ausgeben(request): if request.method == 'GET': ausgeben = Schraube.objects.all() serializer = SchraubeSerializer(schrauben, many=True) return JsonResponse(serializer.data, safe=False) return render(request, 'AR-Ausgeben.html', all_items) -
Django Summernote clean() got an unexpected keyword argument 'styles' in DjangoForms
I have a Django app hosted on Heroku. I have Summernotes installed on the Django forms, however, when I submit the forms I get the error: clean() got an unexpected keyword argument 'styles' Exception Location: /app/.heroku/python/lib/python3.10/site-packages/django_summernote/fields.py, line 18, in to_python I can edit this file on the local host and remove styles=STYLES and it will work on localhost but I am unable to edit this on Heroku. This error also shows up if i try and edit via the admin. I'm lost on what to try next. Thank you in advance. from django.db import models from django.forms import fields import bleach from django_summernote.settings import ALLOWED_TAGS, ATTRIBUTES, STYLES from django_summernote.widgets import SummernoteWidget # code based on https://github.com/shaunsephton/django-ckeditor class SummernoteTextFormField(fields.CharField): def __init__(self, *args, **kwargs): kwargs.update({'widget': SummernoteWidget()}) super().__init__(*args, **kwargs) def to_python(self, value): value = super().to_python(value) return bleach.clean( value, tags=ALLOWED_TAGS, attributes=ATTRIBUTES, styles=STYLES) class SummernoteTextField(models.TextField): def formfield(self, **kwargs): kwargs.update({'form_class': SummernoteTextFormField}) return super().formfield(**kwargs) def to_python(self, value): value = super().to_python(value) return bleach.clean( value, tags=ALLOWED_TAGS, attributes=ATTRIBUTES, styles=STYLES) I do have this in the settings files but it doesn't do anything: STYLES = [ 'background-color', 'font-size', 'line-height', 'color', 'font-family' ] My models.py from django.db.models.signals import post_save, post_delete from django.db import models from model_utils import Choices from django.contrib.auth.models import User … -
Add multiple products in session [Django]
I would like to add several products to build my basket, but each time I add another product it overwrites the first one, how do I add several products in session? Views.py def cart_add(request, code): dico={"produits":[{'code':'MLO31','nom':'banane sucré','prix':1500}, {'code':'BRAD5','nom':'pomme de terre','prix':1800}]} mes_produits=dico['produits'] session=request.session selected_product = next((item for item in mes_produits if item["code"] == code), None) if selected_product != None: session['nom']=selected_product.get('nom') session['prix']=selected_product.get('prix') contex={'nom':session['nom'],'prix':session['prix']} return render(request, 'cart/cart_detail.html',contex) cart_detail.html {% for key,value in request.session.items %} Nom : {{request.session.nom}} Prix : {{request.session.prix}}<br> {% endfor %} -
How do I filter on related objects that's fetched by prefetch_related without executing additional SQL queries?
The below snippet is from Django doc: https://docs.djangoproject.com/en/4.1/ref/models/querysets/ >>> pizzas = Pizza.objects.prefetch_related('toppings') >>> [list(pizza.toppings.filter(spicy=True)) for pizza in pizzas] The second line executes additional SQL queries. Is there a Django native way of writing the above that filters in memory instead of executing SQL against db? alternatively I can just write this without generating more SQL queries: [[topping for topping in pizza.toppings if topping.spicy == True] for pizza in pizzas] -
HackerNews API extraction error - TypeError: list indices must be integers or slices, not str
Trying to run this code to get the topstories from hacker news is giving me this error 'TypeError: list indices must be integers or slices, not str', the error is generated at story = data['story'] from multiprocessing import context from django.shortcuts import render import requests # Create your views here. def index(request): #make an api call and save response url = f'https://hacker-news.firebaseio.com/v0/topstories.json' response = requests.get(url) data = response.json() story = data['story'] context = { 'story': story } return render(request, 'SyncNews/index.html', context) What can I do to correct this error as I'm following a video showing a similar project but this error was not seen, I've also tried removing the '' but receive an error 'UnboundLocalError at / local variable 'story' referenced before assignment' story = data['story'] -
Gmail SMTP Connection "unexpectedly closed" after sending some mails w/ multithreading
I'm trying to use a multithreading approach to speed up sending multiple individual emails using the Django framework and the Gmail SMTP, but I'm running into issues with my connection being dropped It is important to know that I can manage to send about 50 or 55 emails untill my connection is dropped with this error: smtplib.SMTPServerDisconnected: Connection unexpectedly closed I can't use Django send_mass_email method because I need to be able to register if each mail is sent or failed in a database for auditing purposes My code looks like this: class Threading(Thread): def __init__(self, emails): self.emails = emails Threading.thread(self) def thread(self): queue = Queue() #4 worker threads for x in range(4): worker = SenderWorker(queue) worker.daemon = True worker.start() for email in self.emails: queue.put( email ) queue.join() And the SenderWorker class: class SenderWorker(Thread): def __init__(self, queue): Thread.__init__(self) self.queue = queue def run(self): start = datetime.now() while True: email = self.queue.get() try: Email.sendEmail( email ) #method for sending and logging a single email sent finally: self.queue.task_done() My SMTP config looks like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'anon@anonymous.com' SERVER_EMAIL = 'anon@anonymous.com' EMAIL_HOST_PASSWORD = '*******' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER I've tried so far: … -
How to generate html test report in selenium while triggering my test with Django and Plain html as my test script is running but generating nothing?
This is my viws.py file # Create your views here. def test_home(request): return render(request, 'Acode.html') def end_home(request): return render(request, 'After.html') @csrf_exempt def run_home(request): if request.method == 'POST': objs = json.loads(request.body) for val in objs: if val=='1.1': l= login() l.setUpClass() l.test_menu() l.tearDownClass() if val=='1.2': l= create_course_test() l.setUpClass() l.test_admin_Page() l.tearDownClass() if val=='1.3': l= create_course_test_draft() l.setUpClass() l.test_admin_Page() l.tearDownClass() content = '<p>dummy content</p>' return HttpResponse(content) // Test.Login_Menu_Test file: @classmethod def setUpClass(cls): const = 'https://trainingroot.z29.web.core.windows.net/' cls.driver.get(const) cls.driver.maximize_window() def test_menu(self): self.const = 'https://trainingroot.z29.web.core.windows.net/' currentList = self.driver.find_elements(By.TAG_NAME, 'a').sort() previousList = Project_urls.urls.sort() WebDriverWait(self.driver, 10).until( EC.presence_of_element_located( (By.XPATH, '//*[@id="single-spa-application:@Training"]/div/div/div[1]/p'))) if currentList == previousList: self.driver.get(self.const + 'home') self.driver.get(self.const + 'course category') self.driver.get(self.const + 'calender') self.driver.get(self.const + 'FAQ') self.driver.get(self.const + 'expert') self.driver.get(self.const + 'requesttraining') self.driver.get(self.const + 'myachievements') else: print('Some thing is missing') @classmethod def tearDownClass(cls): cls.driver.close() cls.driver.quit() print('Test Completed') if name == 'main': unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='../Selenium/Reports')) // my code is generating test reports only when I trigger it from the terminal but I want to trigger it with the Django application... // If I put the last statement inside the teardown function, then it doesn't start and may be the root cause of the problem -
Lack of Log Entry for Unhandled Error in Server Side SuiteScript 2.x
I suppose that this is more of a curiosity as opposed to an actual issue, but I thought I'd ask about it anyway. There are times when an uncaught error occurs in a server-side NetSuite script using SuiteScript 2.0/2.1 (2.x), but instead of seeing a "SYSTEM" scripting log entry, there's nothing. It gives the appearance of a script just stopping for no reason. Now, I know this can easily be avoided by wrapping everything within a try-catch block, but that's not what I'm trying to discuss here. Does anyone have any insight into why a script would just stop without any SYSTEM error logging? It's just something I find interesting given that with the 1.0 API uncaught errors would always get logged. And it's not a guarantee that an uncaught error won't be logged as a SYSTEM log. It seems more common with map/reduce scripts, but unless memory is not serving correctly I believe that I have seen it happen with suitelets and user event scripts, too. Just thought that I'd pose the question here to see if there was anyone who might know a little something about it. -
How can i make my input in my templates save in same template page and in database using django. Please help i am new here
I created a model. i want my input data from my template page to show on that same page after clicking submit and that same data should save in my database in the model -
What are Django swappable models?
What are swappable models in Django? And Why sometimes when we do a migration a swappable dependency appears in Django migration files? I have searched for this concept in Django but I did not understand what it really does?! -
How to limit form submit request in Django app
I want to limit submitting request for visitors(anonymous) in my django app. Suppose 10 or 50 limits per day/month. If they try to search more than my given limit I want to show a message "you have reached your daily or monthly limit!" How can I do this? Here is views: def homeview(request): if request.method == "POST" and 'text1' in request.POST: text1 = request.POST.get('text1') text2 = request.POST.get('text2') data = my_custom_function(text1, text2) context = {'data': data} else: context = {} return render(request, 'home.html', context) here is form in template: <form action="" method="POST"> {% csrf_token %} <input class="form-control m-3 w-50 mx-auto" type="text" name="text1" id="text1" placeholder=""> <input class="form-control m-3 w-50 mx-auto" type="text" name="text2" id="text2" placeholder=""> <input class="btn btn-primary btn-lg my-3" type="submit" value="Submit"> </form> -
Upgrading Django 3.1.7 to 4.0.7 along with python 3.10 facing issues in project
Below are the error when try to run the project using django 4.0.7. If I downgrade django to 3.1.7 everything work fine. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/lib/python3.10/site-packages/django/core/management/init.py", line 398, in execute autoreload.check_errors(django.setup)() File "/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/lib/python3.10/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/lib/python3.10/site-packages/django/apps/config.py", line 126, in create mod = import_module(mod_path) File "/usr/lib/python3.10/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "/rest_registration/apps.py", line 3, in import rest_registration.checks # noqa File "/rest_registration/checks.py", line 33, in def auth_installed_check(): File "/lib/python3.10/site-packages/django/core/checks/registry.py", line 52, in inner raise TypeError( TypeError: Check functions must accept key arguments (**kwargs). -
i am trying to visit the admin link in my django server link, but i keep getting a, "TypeError at /admin". i did notice the "venv" folder gives a sign
#admin.py from django.contrib import admin Register your models here. from .models import Student admin.site.register(Student) #models.py class Student(models.Model): id = models.CharField(max_length=50) surname = models.CharField(max_length=50) first_name = models.CharField(max_length=50) gender = models.CharField(max_length=6) course = models.TextField() -
Facet Filter List using django-filter
I'm trying to build a facet Filter using django-filter. Also in filter, I have Postgres full-text search. Filter and search work good, but I don't know how to build a facet Filter. For example, I want that when I select Chinese, then I see count each value and related value in filter. Could you please give me any advice how to build it? models.py class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey( "Authors", on_delete=models.SET_NULL, null=True, blank=True, ) subject = TreeManyToManyField("Subject") published_date = models.DateField(blank=True, null=True) language = models.ForeignKey( "Language", on_delete=models.SET_NULL, null=True) class Subject(MPTTModel): name = models.CharField( max_length=1000, unique=True, ) class Language(models.Model): name = models.CharField( max_length=255, unique=True, ) class Authors(models.Model): name = models.CharField( max_length=255, unique=True, ) filters.py class BookFilter(django_filters.FilterSet): search = django_filters.CharFilter( method="my_custom_filter", widget=TextInput( attrs={ "class": "form-control", "placeholder": _("Type to search"), } ), ) language = django_filters.ModelMultipleChoiceFilter( field_name="language", queryset=Language.objects.order_by("name"), widget=forms.CheckboxSelectMultiple(), ) subject = django_filters.ModelMultipleChoiceFilter( field_name="subject", queryset=Subject.objects.all(), widget=autocomplete.ModelSelect2Multiple(} ), ) class Meta: model = Book fields = { "subject", "language", "published_date", } def my_custom_filter(self, queryset, name, value): q = value return ( queryset.annotate( rank=SearchRank(vector, q), similarity=TrigramSimilarity("title", q) + similarity=TrigramSimilarity("author", q) ) views.py def BookListView(request): book = Book.objects.all() filter = BookFilter(request.GET, queryset=book) context = { "filter": filter, "book": book, } return render(request, "book.html", context) …