Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using variables across django templates
I have a link in a layout template that another template extends. i want the link to pass in a variable thats in the template that extends the other. I want to pass the name variable in the documentPage template through the editDoc link in the layout template. can anyone think of a way to do this? thanks -
Use Escaped url in Django url regex mismatch
I'm trying to use an escaped url as a re_path variable for an object identifier in my API. The logic to connect the escaped url to an object is there, but I can't figure out why the regex is not matching. In my head, a GET request with the following url /objects/http%3A%2F%2F0.0.0.0%3A3030%2Fu%2F%3Fid%3Dc789793d-9538-4a27-9dd0-7bb487253da1/foo should be parsed into obj = 'http%3A%2F%2F0.0.0.0%3A3030%2Fu%2F%3Fid%3Dc789793d-9538-4a27-9dd0-7bb487253da1' and field = 'foo' for further processing. Ultimately, returning the object and 200. However I am getting a 404 with a very specific Django error that only proliferates when Django unfruitfully iterates through all the paths available. <HttpResponseNotFound status_code=404, "text/html"> (Pdb) response.content b'\n<!doctype html>\n<html lang="en">\n<head>\n <title>Not Found</title>\n</head>\n<body>\n <h1>Not Found</h1><p>The requested resource was not found on this server.</p>\n</body>\n</html>\n' I know the path exists as when I examine the urlpatterns, the path is present: (Pdb) pp object_router.get_urls() [ ... <URLPattern '^(?P<obj>https?[-a-zA-Z0-9%._\+~#=]+)/(?P<field>foo|bar)\/?$' [name='test-detail-foobar']> ] The url is escaped with urllib.parse.quote(obj.url, safe="") Regexs tried: r"https?[-a-zA-Z0-9%._+~#=]+" r"https?[%23A](www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}(\.[a-z]{2,6})?\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)(?=\/foo)" https://regexr.com/6ue7b r"(https?://(www.)?)?[-a-zA-Z0-9@:%.+~#=]{2,256}(.[a-z]{2,6})?\b([-a-zA-Z0-9@:%+.~#?&//=]*) -
Expand folium map size on mobile devices
I make a web app using Django, Folium. I have a navbar and a Folium map on the web page. It works fine om computers and landscape screen devices, but on portrait screen devices the map has a free space. My code for map: .... current_map = folium.Map(location=start_location, zoom_start=6) m = current_map._repr_html_() .... context = {"current_map": m} return render(request, template_name="index.html", context=context) How do I fill it? -
Issue with Blueimp Jquery FileUpload For Individual Uploads
I am having issues with individual upload cancels for blueimp jquery fileupload library, have gone through the library and the functionality isn't well documented. I don't know if anyone also has an experience with blueimp fileupload, please help me out: The code for the Upload is: 'use strict'; $(function (){ function previewDataDetail(img,imgSize,imgName){ return ` <div class="col-sm-12" id="progress_img"> <img src="${img}"> <span>${imgSize}</span> <div class="value_hold" style="display:none"> <p id="preview_name">${imgName}</p> </div> <button class="btn btn-dark">Cancel</button> <div class="progress"> <div class="progress-bar progress-bar-striped progress-bar-animated" id="progress_bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style= "width:100%"></div> </div> </div> ` } function abortUpload(e){ e.preventDefault(); var template = $(e.currentTarget).closest( '#progress_img' ), data = template.data('data') || {}; data.context = data.context || template; if (data.abort) { data.abort(); } else { data.errorThrown = 'abort'; this._trigger('fail', e, data); } } $("#uploadTrigger").click(function(){ // const url = "{% url 'property_pic' %}"; // const csrf_token = $('input[name="csrfmiddlewaretoken"]').val(); // $("#fileupload").attr('data-url', url); // $("#fileupload").attr('data-form-data', csrf_token); $("#fileupload").click() }); $("#fileupload").fileupload({ dataType: 'json', sequentialUploads: true, add: function(e,data){ var previewImg = data.files[0]; var previewUrl = URL.createObjectURL(previewImg); $("#formInput").append(previewDataDetail(previewUrl,previewImg.size,previewImg.name)) data.context = $("#progress_img #progress_bar") data.submit(); var jqXHR = data.submit().error(function (jqXHR, textStatus, errorThrown){ if (errorThrown === 'abort'){ alert('This upload has been cancelled') } }) $("#progress_img button").click((e) => { e.preventDefault(); jqXHR.abort() const snip = e.currentTarget.closest("#progress_img preview_name") console.log(snip); // data.originalFiles.forEach(i => { // if(i.name == … -
having trouble getting user authentication to work in Python
I am building a django/react app and having trouble with the backend user authentication, have not been able to debug the issue. After successfully creating an account I am now trying to login. This is the the login route I have built. @csrf_exempt @api_view(['POST']) def loginUser(request): data = request.data if request.method == 'POST': email = data['email'] password = data['password'] try: user = User.objects.get(email=email) except: message = {'detail': 'email does not match a user'} return Response(message, status=status.HTTP_400_BAD_REQUEST) username = user.username user = authenticate(request, username=username, password=password) # Returning correct username and password print('This is the username:', username) print('This is the password:', password) # returning None, even though username and password are matching the info used for signup. (confirmed on admin page) print('This is the user:', user) if user is not None: login(request, user) serializer = UserSerializer(user, many=False) message = {'detail': 'user has been logged in'} return Response(serializer.data) else: message = {'detail': 'Username or password is incorrect'} return Response(message, status=status.HTTP_400_BAD_REQUEST) Any help would be greatly appreciate it since I have been stuck on this for 2 days. -
Django many-to-one relation with 3 tables
I dont want any foreign keys directly in my users table, and by default, when I add a foreing key field in my custom User model, Django generate 2 tabels like this: When I add a many-to-many field in my Company model I get the 3 desired tables but it's made possible for the same user be in two different companys. class Company(models.Model): class Meta: verbose_name = 'Company' verbose_name_plural = 'Companys' ordering = ['name'] db_table = 'companys' id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True, verbose_name='ID Empresa') name = models.CharField(max_length=100, verbose_name='Nome') users = models.ManyToManyField(User, related_name='company', verbose_name='Users') def __str__(self): return self.name I want Django to generate an additional table with only the Foreing Keys of the two models but keep the behevior of a many-to-one relationship between the two. like this: -
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.