Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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': … -
Django- disallow url in robots.txt that contains variable [duplicate]
In my App I use an API to handle likes for blog posts. The urls are structured like path('post/<int:pk>/<slug:slug>/', views.DetailPostView, name='post-detail'), path('post/<int:pk>/like', PostLikeToggle.as_view(), name='like-toggle'), path('api/post/<int:pk>/like', PostLikeAPIToggle.as_view(), name='like-api-toggle'), The issue is google search console is giving me errors because it is trying to index the likes url and not the true url. How would I prevent the likes URL's from being index by google as I cannot find a way to pass variables in robots.txt or is there a different way to prevent these pages from being indexed. Update: Based on the suggested post I'm just a bit confused on how to implement this. Is it just as simple as Disallow: /*/like Would this block a url such as /post/999/test/unsportsmanlike/foo Updated: I discovered the google robots.txt Tester and was able to determine that the above query works -
django - server is slow to render response, how to manage user experience
My django app is responding slowly on some pages. While I'm working on improving the query efficiency, indexing on the db, etc, my question is how to manage the user experience. What I think is to run some kind of waiting icon, but my research only finds js that works on page loading delays once the browser receives the new page (e.g some element within the document takes time to present). I'm asking about after the user clicks on a url, the message goes off to the server, and before the server responds with a page. The browser shows the "old" page while the server churns away generating the new page. The only clue the user has that something is processing is the "stop/refresh" icon in the url bar is an "x" (in firefox). Are there any ideas, standard approaches, or solutions on how to approach the user experience while the next page is being "resolved/generated?" I guess I could move the offending elements to an API so the response comes more quickly and the do the "working" icon while the page finishes loading. But, suppose that's not something we'd like to do if possible (at least right now). Thanks … -
WebSocket connection is not return any data?
I run this code the handshake and connection work fine but I don't get any results after I run the client.even though the code is working perfectly without any issues. is there any idea to fix the problem? note: I'm using graphql and Django framework in my project import asyncio import graphene from channels.routing import ProtocolTypeRouter, URLRouter class Query(graphene.ObjectType): hello = graphene.String() @staticmethod def resolve_hello(obj, info, **kwargs): return "world" class Subscription(graphene.ObjectType): """Channels WebSocket consumer which provides GraphQL API.""" count_seconds = graphene.Float() async def resolve_count_seconds(root, info): for i in range(10): yield i await asyncio.sleep(1.) schema = graphene.Schema(query=Query, subscription=Subscription) class MyGraphqlWsConsumer(channels_graphql_ws.GraphqlWsConsumer): """Channels WebSocket consumer which provides GraphQL API.""" schema = schema async def on_connect(self, payload): pass application = channels.routing.ProtocolTypeRouter({ "websocket": channels.routing.URLRouter([ django.urls.path("graphql/", MyGraphqlWsConsumer.as_asgi()), ]) }) ASGI_APPLICATION = 'graphql_ws.urls.application' client: from graphql_client import GraphQLClient ws = GraphQLClient('ws://localhost:8000/graphql/') def callback(_id, data): print("got new data..") print(f"msg id: {_id}. data: {data}") query = """ subscription { countSeconds } """ sub_id = ws.subscribe(query, callback=callback) -
Since django 4.1, templates are cached with DEBUG=True. Is this solution right?
As described in the documentation, since 4.1 the default behavior for template loading changed drastically. If I understand it right, until 4.0 it worked like this: With DEBUG enabled, the templates are loaded in every request, therefore if you keep making changes and reloading while working on a template, you always see the latest version. With DEBUG disabled, the templates are cached when initializing the application, therefore you can only see changes in your templates if you also restart the application. That way, the template caching was seamlessly enabled in production which is great. Now this ticket proposal was included and, if I get it correctly, the template loading method must be specified and it's not anymore tied to DEBUG setting, AND, by default are cached. We want the original behavior so the frontend developer can see the changes without having to restart the app, and we also want the production deployment to have the caching enabled, so we did this: develop_loaders = [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ] production_loaders = [ ("django.template.loaders.cached.Loader", [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", "path.to.custom.Loader", ]) ] TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ "templates", ], "OPTIONS": { "context_processors": [ "maintenance_mode.context_processors.maintenance_mode", "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "wagtail.contrib.settings.context_processors.settings", ], "loaders": develop_loaders … -
searchable and able to sleelct all options in Django
How can I make a form that I can do these with: 1_ seaerchable choice field like cities. 2_a button that make me able to select all of cities. -
NoReverseMatch , Reverse for 'profilepage' with arguments '('',)' not found. 1 pattern(s) tried: ['profilepage/(?P<pk>[^/]+)/\\Z']
def profilki(request): profilki = profile.objects.all() context = {'profilki':profilki } return render(request,'base/profilki.html',context) def profilepage(request,pk): user = Trainingvalue.objects.get(id=pk) trainingplan = Trainingvalue.objects.all() profilepage= profile.objects.get(id=pk) user_training= Trainingvalue.objects.filter(user=profilepage.user) context ={‘user_training’:user_training,‘user’:user,‘profilepage’:profilepage, ‘trainingplan’:trainingplan,} return render(request, 'base/profilepage.html' , context) url : path (‘profilepage/str:pk/’,views.profilepage, name=“profilepage”) profilepage in context profile page has an attribute id profilepage.id entity does not provide value - yet i can access it through the borwser… so technically this should work in html template: profile i get error: Reverse for 'profilepage' with arguments '('',)' not found. 1 pattern(s) tried: ['profilepage/(?P<pk>[^/]+)/\\Z']