Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I save my Gist script tag in Ckeditor?
Quick question. I try to post the script to a Gist in Ckeditor, in my Django website. Whenever I post the < script > in the editor, it just shows up as raw code. My work around for this was editing the raw file, inserting the < script >. Which worked, except for some reason if I need to alter anything else in the code I have to reinsert it again. Any workaround for this? I was using the codeblocks feature of ckeditor, but I like the formatting of embedded gists better because it shows line numbers, etc. -
request.data is different in runserver and uwsgi
I'm sending a post request to server. I use runserver to test and I use uwsgi inside docker as well. When I use request.data to serialize the object, it works fine in run server. The output data is like [enter image description here][1] But when I use uwsgi in docker-omposer up and use the same request.data it is different. This causes it not to store in DB. [enter image description here][2] Can someone explain what is wrong here? Thanks [1]: https://i.stack.imgur.com/oFVpz.png [2]: https://i.stack.imgur.com/T6sIf.png -
Gunicorn is stuck in deadlock for python django service running in docker container
I am running a python django webhook application that runs via gunicorn server. My setup is nginx + Gunicorn + Django. Here is what the config looks like: gunicorn app1.wsgi:application --bind 0.0.0.0:8000 --timeout=0 The application runs perfectly for ~1 -2 million request, but after running for few hours the gunicorn shows in sleep state and then no more webhook event gets received root 3219 1.3 0.0 256620 61532 ? Sl 14:04 0:19 /usr/local/bin/python /usr/local/bin/gunicorn app1.wsgi:application --bind 0.0.0.0:8000 --timeout=0 The service is running in 4 different containers and within few hours this behavior is observed for 1 container and then it occurs for one or more containers in subsequent hours. I tried sending a signal to reload gunicorn config which is able to bring the gunicorn process into running state. What is curious is that when I run 4 django containers, for few requests it works perfectly well. But continuously receiving traffic causes this deadlock in one of the gunicorn worker's state and it keep on waiting for a trigger to start accepting traffic again while rest of the three gunicorn workers are healthy and running ! Question - Why does gunicorn worker process is going in sleep state(Sl)? How can … -
Docker and Django Postgresql issue
I am currently learning how to implement docker with Django and Postgres DB. Everytime I tried I run the following command: docker compose up --build -d --remove-orphans Although I can see all my images are started. Every time I tried to open my Django admin site, I cannot sign in using already registered superuser credentials. In Postgres DB PGAdmin all the data that are created previously are stored and saved correctly. But after closing my computer an I start Docker compose up previously saved data's are not recognized by the new start up even if the data still visible in my Postgres DB. How can I make the data to be recognized at start up? Here is my docker-compose.yml configurations: version: "3.9" services: api: build: context: . dockerfile: ./docker/local/django/Dockerfile # ports: # - "8000:8000" command: /start volumes: - .:/app - ./staticfiles:/app/staticfiles - ./mediafiles:/app/mediafiles expose: - "8000" env_file: - .env depends_on: - postgres-db - redis networks: - estate-react client: build: context: ./client dockerfile: Dockerfile.dev restart: on-failure volumes: - ./client:/app - /app/node_modules networks: - estate-react postgres-db: image: postgres:12.0-alpine ports: - "5432:5432" volumes: - ./postgres_data:/var/lib/postgresql environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} networks: - estate-react redis: image: redis:5-alpine networks: - estate-react celery_worker: build: … -
Django, Postman. Why the GET request doesn't respond with my API?
I am developing on my local and try to get view (non-programming term) of my API. My view (programming term) is simply looks like: class WeaponDetailsView(DetailView): model = Weapon template_name = 'weapons/weapon/details.html' I also try to get response via script: import requests url = 'http://127.0.0.1:8000/' res = requests.get(url).json() print(res) But this gives me the raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) requests.exceptions.JSONDecodeError: Expecting value: line 2 column 1 (char 1) error. So why can't I see my APIs only, and not the html body content? And why the situation changes when I implement an API View with Django Rest Framework? I mean it returns only APIs which is grate -
How to plot Django data on a Chart.js graph?
I am so tilted, so so so tilted. Been trying to work chart.js for a while now on my website I built with Django. I want to plot two fields: Dates and Scores. Dates is a date such as 1/6/2022, score is a float. My issue is that when I pass through the python list to the script it pretends it's something disgusting. But when I copy and past the list and put it into the chart's data it's fine. It only doesn't work when it thinks it's a variable which just makes no sense at all and I can't find anywhere that is talking about this. views.py def progress(response): lessons = StudentLessons.objects.get(name=response.user.email) scores = [] dates = [] for lesson in lessons.lesson_set.all(): dates.append(str(lesson.date)) scores.append(str((lesson.accuracy+lesson.speed+lesson.understanding)/3)) context = { 'dates':dates, 'scores':scores, } return render(response, "main/progress.html", context) dates = ['2022-09-27', '2022-09-28'] scores = ['4.333333333333333', '6.0'] (from console) html that displays the correct chart <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="myChart" style="width:100%;max-width:700px"></canvas> <script type="text/javascript"> var myChart = new Chart("myChart",{ type:"line", data: { labels: ['2022-09-27', '2022-09-28'], datasets:[{ borderColor: "rgba(0,0,0,0.1)", data: ['4.333333333333333', '6.0'] }] }, options:{ responsive: true, legend: { position: 'top', }, } }); </script> html that doesn't work <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="myChart" style="width:100%;max-width:700px"></canvas> <script type="text/javascript"> var … -
Table generating for web
I have a web app made in django which generates a school timetable. It takes around 5-10 minutes to generate one because it is for 25 classes with a lot of links to every teacher and class with separate timetables. I want to rewrite the whole app and if it's possible I want to make it run faster. I can use django and plain html/js/php. What should I use for this kind of problem or does it even matter if I don't use django or if there is a better framework for this beside these two. -
Is there a way to have an action with detail = True inside another action with detail = True in Django rest?
My user model has a Many to one relationship to a Clothes model and inside my User viewset I created an extra action to list the Clothes instances in relation to a specific user @action(detail=True, methods=['get'], serializer_class=UserOutfitSerializer) def outfit (self, request, pk=None): user = User.objects.get(id=pk) clothes = user.clothes_set.all() serializer = UserOutfitSerializer(user.clothes_set.all(), many=True) return Response(serializer.data, status=status.HTTP_200_OK) It's possible to make another extra action to retrive/update/delete each instance clothes for that user ('http://127.0.0.1:8000/api/users/user_id/outfit/clothes_id') and if it is, would that be a bad pratice? -
Display the dynamic table in a Django template
When I run this only code in separate python file, it will run perfectly. But using Django template the option chain does not print. Following error has been occurred: AttributeError at /nifty 'Response' object has no attribute 'META' my views code is ....... url = 'https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36 Edg/103.0.1264.37','accept-encoding': 'gzip, deflate, br','accept-language': 'en-GB,en;q=0.9,en-US;q=0.8'} session = requests.Session() request = session.get(url,headers=headers) cookies = dict(request.cookies) response = session.get(url,headers=headers,cookies=cookies).json() rawdata = pd.DataFrame(response) rawop = pd.DataFrame(rawdata['filtered']['data']).fillna(0) data = [] for i in range(0,len(rawop)): calloi = callcoi = cltp = putoi = putcoi = pltp = callvol = putvol = callpChange = putpChange = callIV = putIV = 0 stp = rawop['strikePrice'][i] if(rawop['CE'][i]==0): calloi = callcoi = 0 else: calloi = rawop['CE'][i]['openInterest'] callcoi = rawop['CE'][i]['changeinOpenInterest'] cltp = rawop['CE'][i]['lastPrice'] callvol = rawop['CE'][i]['totalTradedVolume'] callpChange = rawop['CE'][i]['pChange'] callIV = rawop['CE'][i]['impliedVolatility'] if(rawop['PE'][i] == 0): putoi = putcoi = 0 else: putoi = rawop['PE'][i]['openInterest'] putcoi = rawop['PE'][i]['changeinOpenInterest'] pltp = rawop['PE'][i]['lastPrice'] putvol = rawop['PE'][i]['totalTradedVolume'] putpChange = rawop['PE'][i]['pChange'] putIV= rawop['PE'][i]['impliedVolatility'] opdata = { 'CALL IV': callIV, 'CALL CHNG OI': callcoi,'CALL OI': calloi, 'CALL VOLUME': callvol,'LTP CHANGEC': callpChange, 'CALL LTP': cltp, 'STRIKE PRICE': stp, 'PUT LTP': pltp, 'LTP CHANGEP': putpChange, 'PUT … -
Invalid Tag static expected endblock
I am new django. I'm practicing it after finishing youtube videos. I'm facing the following error django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 42: 'static', expected 'endblock'. Did you forget to register or load this tag? The problem that it tells me that it can't find the endblock tag but I've put it at the end of the code. I don't know what causes this problem or how to solve it I need help please my html {% extends "Books/base.html" %} {% block content %} <div class="page" id="page"> <div class="main"> <div class="main-content"> {% for book in books %} <div class="container"> <div class="img"> <img src="{{ book.image.url }}" width="250px" height="300px" /> </div> <div class="title"> <a href="{% url 'details' book.id %}" target="_blank"> {{ book.title }} </a> </div> <p class="description">{{ book.mini_description }}</p> <p class="category"> {% for categ in book.category.all %} {% if categ == book.category.all.last %} {{ categ }} {% else %} {{categ}}- {% endif %} {% endfor %} </p> <h2 class="price">{{ book.price }} EGP.</h2> <h3 class="rate">{{ book.rate }}</h3> <a href="{% url 'buy' %}" target="_blank" ><button class="buy_now nav buy_now_position">Buy Now</button></a > </div> {% endfor %} </div> </div> <div class="nav-bar"> <header class="nav"> <a class="nav logo"> <img src="{% static 'images/Main Logo.png' %}" class="logo" alt="logo" /> </a> <a … -
Accessing extracted data from csv in django to create new class
Hi I’m working on a Django project where I’m iterating through a CSV file to extract data and then use that data to create an object (product). The products.models.py is structured as follows: from django.db import models class Product(models.Model): name = models.CharField(max_length=120) image = models.ImageField(upload_to='products', default='no_picture.png') price = models.FloatField(help_text='in US dollars $') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.name}-{self.created.strftime('%d/%m/%Y')}" The CSV I’m iterating through has the following structure: POS,Transaction id,Product,Quantity,Customer,Date 1,E100,TV,1,Test Customer,9/19/2022 2,E100,Laptop,3,Test Customer,9/20/2022 3,E200,TV,1,Test Customer,9/21/2022 4,E300,Smartphone,2,Test Customer,9/22/2022 5,E300,Laptop,5,New Customer,9/23/2022 6,E300,TV,1,New Customer,9/23/2022 7,E400,TV,2,ABC,9/24/2022 8,E500,Smartwatch,4,ABC,9/25/2022 Opening the csv file once it's added and iterating through it I do like this: if request.method == 'POST': csv_file = request.FILES.get('file') obj = CSV.objects.create(file_name=csv_file) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) reader.__next__() for row in reader: print(row, type(row)) # list data = ";".join(row) print(data, type(data)) # creates a str data = data.split(';') # creates a list print(data, type(data)) print(data) So far so good. I then prepare the elements by having a look at the output from the terminal: ['1', 'E100', 'TV', '1', 'Test Customer', '9/19/2022'] <class 'list'> 1;E100;TV;1;Test Customer;9/19/2022 <class 'str'> ['1', 'E100', 'TV', '1', 'Test Customer', '9/19/2022'] <class 'list'> ['1', 'E100', 'TV', '1', 'Test Customer', '9/19/2022'] Preparing an object from … -
Facebook login permissions user_photos
There are 2 profiles in process of Login. One profile can see Photos perm request, another profile does not see it. What does it mean? How can I solve it? -
Can not login as superuser in DRF
Created superuser several times with this credentials. username: admin password: root Did it with terminal and with Djnago ORM. Same result. >>> from bank.models import User >>> User.objects.create_superuser(username="admin", password="root") >>> from django.contrib.auth import authenticate >>> u = authenticate(username="admin", password="root") >>> u >>> type(u) <class 'NoneType'> >>> admin = User.objects.get(username="admin") >>> admin <User: admin> >>> admin.is_active True >>> admin.is_staff True >>> admin.is_superuser True It's started since I started using python-jwt tokens, but it fails before code goes to token part. Same login function as normal user works as it supposed to be and gives working token. @api_view(['POST']) def login_view(request): username = request.data.get("username") password = request.data.get("password") user = User.objects.filter(username=username).first() if user is None: raise exceptions.AuthenticationFailed("Invalid Credentials") if not user.check_password(password): # code fails here after trying lo log in as superuser raise exceptions.AuthenticationFailed("Invalid Credentials") token = services.create_token(user_id=user.id) resp = response.Response() resp.set_cookie(key="jwt", value=token, httponly=True) resp.data = {"token": token} return resp -
ValueError: Field 'id' expected a number but got '10.48.38.28'
I tried to search with Rest Framework a specific parameter in the sqlite using django but i get the following error: return int(value) ValueError: invalid literal for int() with base 10: '10.48.38.28' The above exception was the direct cause of the following exception: Traceback (most recent call last):... ValueError: Field 'id' expected a number but got '10.48.38.28'. [27/Sep/2022 13:23:59] "GET /sipinterface/?ipHost=10.48.38.28/ HTTP/1.1" 500 155723 MODELS class sipInterface(models.Model): siRealmId=models.CharField(max_length=75) siIpAddress=models.CharField(max_length=75) siPort=models.IntegerField() siTransportProtocol=models.CharField(max_length=75,null=True) siAllowAnonymus=models.CharField(max_length=75,null=True) ipHost = models.ForeignKey(host, on_delete=models.CASCADE) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: #nombre sing y plural de musica verbose_name="sipInterface" verbose_name="sipInterface" def __str__(self): return f"{self.siRealmId},{self.siIpAddress},{self.siPort},{self.siTransportProtocol},{self.siAllowAnonymus},{self.ipHost}" The Serializers file is the next: SERIALIZERS: from rest_framework import serializers from .models import sipInterface class sipInterfaceSerializer(serializers.ModelSerializer): class Meta: model=sipInterface fields=['siRealmId','siIpAddress','siPort','siTransportProtocol','siAllowAnonymus','ipHost'] The file of the view is the next: VIEW class sipInterfaceList(generics.ListAPIView): serializer_class=sipInterfaceSerializer def get_queryset(self): queryset = sipInterface.objects.all() ipHost = str(re.sub(r'/.*',"",self.request.query_params.get('ipHost', None))) if ipHost is not None: queryset = sipInterface.objects.filter() queryset = queryset.filter(ipHost=ipHost) #<--- THE ERROR! else: queryset = [] return queryset class sipInterfaceDetail(generics.RetrieveAPIView): queryset=sipInterface.objects.all() serializer_class=sipInterfaceSerializer def get_queryset(self): queryset = sipInterface.objects.all() ipHost = str(re.sub(r'/.*',"",self.request.query_params.get('ipHost', None))) if ipHost is not None: queryset = sipInterface.objects.filter() queryset = queryset.filter(ipHost=ipHost) else: queryset = [] return queryset I mark the line with the error with #<--- THE ERROR! Thanks for your help -
How to get string with space character in input value html
I have a class 'client' with a Charfield called 'address', this field have a space, for example 'via marconi' <div class="form-group"> <label for="address">Indirizzo:</label> <input type="text" class="form-control" id="address" name="address" value={{client.address}} Required> </div> In this case, when i get the value with "client.address" it give me only 'via' without read over the space. I'm trying to find a way for read the entire string with also the end of the string over the space character -
Virtualenv django package unresolved
I'm new to django and find my django package always unresolved, but the project runs successfully, the interpreter setting is right, the pip list shows the django package, I clip some pics here, can someone tell me how to remove these warnings? Are there any pronlems in environment variables or version conflicts? Warnings: enter image description here Interpreter setting: enter image description here project structure setting: enter image description here run/debug configuration: enter image description here -
Why do we need to login user in signup_view an login_view function? Django
So I need a theoretical answer here, not practical, I've been following this tutorial on Django anf everything seems quite understandable, but I'm not sure about one thing, so here are the views for signup page and login page: def signup_view(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() #log the user in login(request, user) return redirect("articles:list") else: form = UserCreationForm() return render(request, 'account/signup.html', {"form": form}) def login_view(request): if request.method == "POST": form = AuthenticationForm(data = request.POST) if form.is_valid(): #log in the user user = form.get_user() login(request, user) return redirect('articles:list') else: form = AuthenticationForm() return render(request, "account/login.html", {"form":form}) So my question is, why do I need to write login(request, user) twice, isn't the signup function saving the user in database and log in function simply logging it in? -
Django Error: 'utf-8' codec can't decode byte when trying to create downloadable file
I have created an app, to do some process and zip some files. Now I need to make the zip file downloadable for users, so they can download the zip file. I am working with Django and here is the in views.py: def download(request): context = {} if request.method == 'POST': if form.is_valid(): userInput = form.cleaned_data['userInput'] createFiles(userInput) filename = 'reports.zip' filepath = '/home/download/' fl = open(filepath, 'r') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response return render(request, 'download.html', context) But I am getting an error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83 in position 11: invalid start byte Which is breaking on this line: response = HttpResponse(fl, content_type=mime_type) Any suggestions how to fix this? -
How to access elements in list of dictionaries?
I’m working with a CSV file that looks as follows: POS,Transaction id,Product,Quantity,Customer,Date 1,E100,TV,1,Test Customer,9/19/2022 2,E100,Laptop,3,Test Customer,9/20/2022 3,E200,TV,1,Test Customer,9/21/2022 4,E300,Smartphone,2,Test Customer,9/22/2022 5,E300,Laptop,5,New Customer,9/23/2022 6,E300,TV,1,New Customer,9/23/2022 7,E400,TV,2,ABC,9/24/2022 8,E500,Smartwatch,4,ABC,9/25/2022 In order to grab elements out of it this gets each line into a callable line by assignment: with open(obj.file_name.path, 'r') as f: rdr = csv.DictReader(f) for row in rdr: pos = row['POS'] product = row['Product'] transaction_id = row['Transaction id'] quantity = row['Quantity'] customer = row['Customer'] date = row['Date'] try: product_obj = Product.objects.get(name__iexact=product) except Product.DoesNotExist: product_obj = None For example to print each row from the CSV I can now type: pos, transaction_id, product, quantity, customer, transaction_id, date = row print(row) Resulting in this terminal output: file is being uploaded {'POS': '1', 'Transaction id': 'E100', 'Product': 'TV', 'Quantity': '1', 'Customer': 'Test Customer', 'Date': '9/19/2022'} {'POS': '2', 'Transaction id': 'E100', 'Product': 'Laptop', 'Quantity': '3', 'Customer': 'Test Customer', 'Date': '9/20/2022'} {'POS': '3', 'Transaction id': 'E200', 'Product': 'TV', 'Quantity': '1', 'Customer': 'Test Customer', 'Date': '9/21/2022'} {'POS': '4', 'Transaction id': 'E300', 'Product': 'Smartphone', 'Quantity': '2', 'Customer': 'Test Customer', 'Date': '9/22/2022'} {'POS': '5', 'Transaction id': 'E300', 'Product': 'Laptop', 'Quantity': '5', 'Customer': 'New Customer', 'Date': '9/23/2022'} {'POS': '6', 'Transaction id': 'E300', 'Product': 'TV', 'Quantity': '1', 'Customer': 'New Customer', 'Date': '9/23/2022'} … -
get parameters in a get request in django rest framework?
I want to get the parameters sent to my rest api what I want is to obtain the parameters that to use them consume another api and return the response of the third party api but in name and comic i get None http://127.0.0.1:8000/searchComics/ {name:"3-D Man","comics":12} this is my view class MarvelApi(APIView): def get(self, request): private_key = "88958f2d87bd2c0c2fa07b7ea654bcdf9f0389b3" public_key = "8d415ffcc9add56b0a47c0a7c851afc3" ts = 1 md5_hash = "46ecbbd63108b0561b8778a57823bd34" query_params = self.request.query_params name = query_params.get('kword', None) comic = query_params.get('comic', None) end_point = f"https://gateway.marvel.com:443/v1/public/characters?ts={ts}&apikey={public_key}&hash={md5_hash}&name={name}&comic={comic}" response = requests.get(end_point) response_json = json.loads(response.text) return Response(status=status.HTTP_200_OK, data=response_json) I think the problem is these two lines name = query_params.get('kword', None) comic = query_params.get('comic', None) that do not capture the values correctly, do you know how to solve it? -
admin.SimpleListFilter with related_query_name to filter occurances
I try to filter items in a admin list: class Product(models.Model): name = models.CharField("name", max_length = 128) def associated_stores(self): stores = set([f"""{s.number}""" for sin self.store_name.all()]) if len(stores) == 0: return None return ", ".join(stores) class Store(models.Model): products = models.ManyToManyField(Product, related_name = "%(class)s_name", related_query_name = "product_store_qs", blank = True) number = ... Now I want to implement a SimpleListFilter that can filter in the products list for products that are available in no stores, or show the store names: class AssociatedStoresFilter(admin.SimpleListFilter): title = "associated stores" parameter_name = "assoc_stores" def lookups(self, request, model_admin): return [(True, "yes"), (False, "no")] def queryset(self, request, queryset): qs = queryset.annotate(assoc_stores = Case(When(product_store_qs__isnull = False, then = 1), default = 0)) if self.value() == "False": return qs.filter(assoc_stores = 0) elif self.value() == "True": return qs.filter(assoc_stores = 1) else: return queryset The filter for no stores have the product works, but the one where only products should be shown that are available in a store shows one entry for every store of a product (with all stores) instead of only one entry (with all stores) only. How do I cut down my results to hold every product only once after filtering? edit: I know I can solve my problem … -
How do I tackle this issue in my Guess The Flag Django web app
I'm completely new to Django and I'm trying to build this guess the flag web game with it. In main page when someone presses the 'play' button, he's sent to a page where a list of 4 randomly selected countries from the DB is generated, and only of one these 4 countries is the actual answer. Here's the code from views.py in my App directory : context = {} context['submit'] = None context['countries_list'] = None score = [] score.clear() context['score'] = 0 def play(request): len_score = len(score) countries = Country.objects.all() real_choice = None if request.POST: get_guess = request.POST.get('guess') print(request.POST) if str(get_guess).casefold() == str(context['submit']).casefold(): score.append(1) else: score.clear() len_score = len(score) choices = random.sample(tuple(countries),4) real_choice = random.choice(choices) context['countries_list'] = choices context['submit'] = real_choice context['score'] = len_score return render (request, 'base/play.html', context) Everything works as expected when there's only one person playing, or the site is opened in only one tab. The issue here is one someone else opens the site or it's opened in more than one tab, the score gets reset and a new list of random countries is generated for all users, so your guess will never be right! How do I go about to solve this? Again, I'm completely … -
Test Django ModelForm fails but html is present?
Trying to write a very simple test for the start of a ModelForm in Django. My Model: # models.py class Grade(models.Model): paper = models.ForeignKey( Paper, on_delete=models.PROTECT, related_name="grades" ) exam = models.ForeignKey( Exam, on_delete=models.PROTECT, related_name="grades" ) level = models.ForeignKey( Level, on_delete=models.PROTECT, null=True, blank=True, related_name="grades", ) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) created_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_created_by" ) updated_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_updated_by" ) deleted_at = models.DateTimeField(blank=True, null=True) class Meta: verbose_name = "Grade" verbose_name_plural = "Grades" My form looks like this: # forms.py class GradeForm(ModelForm): class Meta: model = Grade fields = [ "exam", "level", "paper", "created_by", "deleted_at", "updated_by", ] My tests look like this: #test_forms.py class GradeForm(TestCase): def setUp(self): self.grade = GradeFactory() def test_empty_form_fields(self): # THIS PASSES form = GradeForm() self.assertIn("created_by", form.fields) self.assertIn("deleted_at", form.fields) self.assertIn("exam", form.fields) self.assertIn("level", form.fields) self.assertIn("paper", form.fields) self.assertIn("updated_by", form.fields) def test_empty_form_html_elements(self): form = GradeForm() # THESE THREE ASSERSTIONS FAIL: # But I can see the HTML in the debugger if I print(form.as_p()) # And the HTML is exactly as it is below in the assertions... self.assertInHTML( '<select name="exam" required id="id_exam">', form.as_p(), ) self.assertInHTML( '<select name="paper" required id="id_paper">', form.as_p(), ) self.assertInHTML( '<select name="level" id="id_level">', form.as_p(), ) def test_form(self): form = GradeForm( data={ "expectation": self.grade.exam.id, "summary": … -
Is the Django Two-Factor Authentication framework working with MongoDb?
i have been trying to implement the Django Two-Factor Authentication tool in my project and was not able to make it work. I am getting until the log in page but when I actually try to log in I am getting a weird Database Error with no provided exception message. Keyword: None Sub SQL: None FAILED SQL: ('SELECT "otp_static_staticdevice"."id", "otp_static_staticdevice"."user_id", "otp_static_staticdevice"."name", "otp_static_staticdevice"."confirmed", "otp_static_staticdevice"."throttling_failure_timestamp", "otp_static_staticdevice"."throttling_failure_count" FROM "otp_static_staticdevice" WHERE ("otp_static_staticdevice"."user_id" = %(0)s AND "otp_static_staticdevice"."confirmed")',) Params: ((4,),) Version: 1.3.6) When checking the requirements it states that version 1.0 of django-formtools is supported. However my project does not run with this version of formtools at all. Also on their github the build is shown as failing. I however have seen it working in other projects. Do I get the errors due to me using djongo and MongoDb as a Database? Or is my fear true and the tool is not working and 2FA should be implemented on my own? Thank you very much in advance -
Why is my Django view hanging when I use asyncio.gather on a sync_to_async function call, but not when I call it directly?
I have a Django view that calls an asgiref.sync.async_to_sync function that queries a remote API - I'm updating payslip data for a bunch of Employees. Within one of these calls I have to access the DB again so have a asgiref.sync.sync_to_async decorated function to gather that data. I run the Employee update function calls concurrently using asyncio.gather, but this hangs indefinitely and never even enters the DB call - this occurs even if I only have one call in the gather list. Awaiting the function works fine though. Everything is running as an ASGI app under Uvicorn. Any ideas? Here's a minimal reproduction: @sync_to_async def _get_database_employee_payslips(employee_data): print(f"Entering DB function") return employee_data @async_to_sync async def get_full_employees_data(_, __): print(f"This works") ret = await _get_database_employee_payslips({'id': 1625841}) print(f"Got {ret}") print(f"This doesn't") ret = await asyncio.gather(*[ _get_database_employee_payslips({'id': employee_id}) for employee_id in [1625841] ], return_exceptions=True) print(f"We're hung in the above call") return ret and the results: INFO 2022-09-27 14:20:20,234 on 10776 140271592661440 Application startup complete. DEBUG 2022-09-27 14:20:22,163 middleware 10776 140271484180032 process_request DEBUG 2022-09-27 14:20:22,163 model_factory 10776 140271484180032 No maximum request body size is set, continuing. DEBUG 2022-09-27 14:20:22,183 model_factory 10776 140271484180032 Created new request model with pk 161dfa90-4082-4ef1-8ab0-84d613c25550 This works Entering DB function Got {'id': …