Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using multiprocessing with a dictionary that needs locked
I am trying to use Python's multiprocessing library to speed up some code I have. I have a dictionary whose values need to be updated based on the result of a loop. The current code looks like this: def get_topic_count(): topics_to_counts = {} for news in tqdm.tqdm(RawNews.objects.all().iterator()): for topic in Topic.objects.filter(is_active=True): if topic.name not in topics_to_counts.keys(): topics_to_counts[topic.name] = 0 if topic.name.lower() in news.content.lower(): topics_to_counts[topic.name] += 1 for key, value in topics_to_counts.items(): print(f"{key}: {value}") I believe the worker function should look like this: def get_topic_count_worker(news, topics_to_counts, lock): for topic in Topic.objects.filter(is_active=True): if topic.name not in topics_to_counts.keys(): lock.acquire() topics_to_counts[topic.name] = 0 lock.release() if topic.name.lower() in news.content.lower(): lock.acquire() topics_to_counts[topic.name] += 1 lock.release() However, I'm having some trouble writing the main function. Here's what I have so far but I don't know exactly how the arguments should be passed. def get_topic_count_master(): topics_to_counts = {} raw_news = RawNews.objects.all().iterator() lock = multiprocessing.Lock() with multiprocessing.Pool() as p: Any guidance here would be appreciated! -
Django ORM __in but instead of exact, contains case insensative?
I am currently trying to use the Django ORM to query the Recipe model's ingredients. class Recipe(models.Model): account = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True) name = models.TextField(null=True, blank=True) class RecipeIngredients(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) ingredient = models.TextField(null=True, blank=True) What I have so far is ingredients = ["eggs", "bacon", "potato"] recipes = Recipe.objects.filter( recipeingredients__ingredient__in=ingredients ).alias( ningredient=Count('recipeingredients') ).filter( ningredient__gte=len(ingredients) ) From my understanding of this answer this will return all the items that contain only "eggs", "bacon", and "potato", but not say Eggs or Scrambled EGGS. Is there anyway to adjust this to have it search for all items that contains the ingredients and case insensative? -
Django: Avoid users uploading files, use their local storage instead?
So I have a Python script that extracts data from .ifc (3D models for the AEC Industry) files to a .csv or .xlsx and I would like to make it available in a web app. The files can get pretty big (> 400MB) and users are rarely owners of these files, so they are probably not allowed to upload them. So I am looking for a way to avoid the file upload. Is something like that possible with a Django App? Or should I look into creating a desktop app with some other framework? -
Radio button not saving selected option when refreshed (Django)
i have been having issues with my django ecommerce application one part of my application the user is meant to check a radio button the issue <input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}" value="{{option.id}}"> my ajax $('input[type=radio][name=deliveryOption]:checked').on('change', function (e) { e.preventDefault(); $.ajax({ type: "POST", url: '{% url "checkout:cart_update_delivery" %}', data: { deliveryoption: $(this).val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { document.getElementById("total").innerHTML = json.total; document.getElementById("delivery_price").innerHTML = json.delivery_price; }, error: function (xhr, errmsg, err) {}, }); }); once i check the radio button, everything works fine but once i refresh the page, the selected radio button disappears but the radio button value is still stored in session. how do i fix it in such a way that even though i refresh the page, the selected radio button would still be selected. -
Can Djago create a database query that returns a dictionary of dictionaries?
Can Djago create a database query that returns a dictionary of dictionaries? The model contains a foreign key. Using these keys, I would like to have the query results sorted out. I would then like to provide these results using a rest framework. Illustration model: class Record(BaseModel): evse = models.ForeignKey( 'core.Evse', verbose_name=_('EVSE'), related_name='record_evse', on_delete=models.CASCADE, ) current_rms_p1 = models.FloatField( _('Current RMS P1'), default=0, validators=( MinValueValidator(0), MaxValueValidator((2**16 - 1) * 0.1), ) ) current_rms_p2 = models.FloatField( _('Current RMS P2'), default=0, validators=( MinValueValidator(0), MaxValueValidator((2**16 - 1) * 0.1), ) ) current_rms_p3 = models.FloatField( _('Current RMS P3'), default=0, validators=( MinValueValidator(0), MaxValueValidator((2**16 - 1) * 0.1), ) ) View: class RecordListAPIView(generics.ListAPIView): queryset = Record.objects.all() serializer_class = RecordSerializer def get_queryset(self): return Record.objects.all() How to edit a query to get this result? { "evse 1": [ { "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 }, { "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 } ], "evse 2": [ { "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 } ] } Or this result: [ [ { "evse": 1, "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 }, { "evse": 1, "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 } ], [ { "evse": 2, "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0, } ] ] -
widgets for Category choice in Django
I just want add a class 'form control' in category choices class BlogForm(forms.ModelForm): # blog_title= forms.TextInput(label='Title',widget=forms.TextInput(attrs={'class':'form-control'})) # blog_content= forms.Textarea(label='Blog Content',widget=forms.Textarea(attrs={'class':'form-control'})) # blog_image= forms.ImageField(label='Blog Thambnail',widget=forms.ClearableFileInput(attrs={'class':'form-control'})) class Meta: model=Blog fields=['blog_title','category','blog_content','blog_image'] widgets={ 'blog_title':forms.TextInput(attrs={'class':'form-control'}), 'blog_content':forms.Textarea(attrs={'class':'form-control'}), 'category':forms.? 'blog_image':forms.ClearableFileInput(attrs={'class':'form-control'}), } is there any specific input field for that?i have given a question mark there. -
('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'hostname'
I have successfully deployed my django web application through Microsoft IIS FastCGI. So look wise my website seems to be fine. But after submitting the form on the website I am getting a database mssql error. So in the error, the username after the word USER is showing different from the username I have mentioned in views.py to establish a connection with the database. The username which is visible in the error is actually the hostname of the server on which I am deploying the web app (The sql server is in another server having another hostname). I am not able to figure out why the username is getting changed automatically and then giving an error. P.S - The web application is working fine without the deployment. Error views.py -
JSON local file retrieval with internationalization in django
I am making a website in django and have included internationalization. The internationalization works fine on other pages, except for when I am trying to retrieve a json file. The search takes in a word, then finds the corresponding JSON file in the javascript file (below). The search was working without issue until I added internationalization. Now I can see that when jquery goes to get the file, it includes the i18n abbreviation on the front, resulting in a 500 error. I have tried parsing the file location but the abbreviations are always added in getJSON. How do I fix this issue? The error specifically that shows in the console is: GET http://localhost:8000/en/static/assets/chowords/amo.json 500 (Internal Server Error) It makes sense that that is an error since the json file is actually at http://localhost:8000/static/assets/chowords/amo.json I tried storing the files in a directory "en" with static nested inside, but that did not resolve the issue. Code for reference: Javascript file new URLSearchParams(window.location.search).forEach((value,name)=>{ console.log(name) console.log(value) var fileword = value; var url = "./static/assets/chowords/" + fileword + ".json"; var xhr = new XMLHttpRequest(); xhr.open('HEAD', url, false); xhr.send(); console.log(xhr) document.getElementById("wordsearched").innerHTML =`<h1>${fileword} </h1>` if (xhr.status == "404") { //console.log("File doesn't exists"); let div = document.createElement('p') div.innerHTML … -
How to remove double quote from key value in dictionary
I have this payload: "cardType": "CHOICE", "step": 40, "title": {"en-GB": "YOUR REPORT"}, "description": {"en-GB": ""}, "options": [ {"optionId": 0, "text": {"en-GB": "Ask me"}}, {"optionId": 1, "text": {"en-GB": "Phone a nurse"}}, {"optionId": 2, "text": {"en-GB": "Download full report"}}, ], "_links": { "self": { "method": "GET", "href": "/assessments/898d915e-229f-48f2-9b98-cfd760ba8965", }, "report": { "method": "GET", "href": "/reports/17340f51604cb35bd2c6b7b9b16f3aec", }, }, } I then url encode it like so and redirect to a report view: url = reverse("my-reports") reverse_url = encodeurl(data, url) The urlencode output is returned as this: "/api/v2/ada/reports?cardType=CHOICE&step=40&title=" "%7B%27en-GB%27%3A+%27YOUR+REPORT%27%7D&description=" "%7B%27en-GB%27%3A+%27%27%7D&options=" "%5B%7B%27optionId%27%3A+0%2C+%27text%27%3A+%7B%27en-GB" "%27%3A+%27Ask+me%27%7D%7D%2C+%7B%27optionId%27%" "3A+1%2C+%27text%27%3A+%7B%27en-GB%27%3A+%27Phone+a+nurse" "%27%7D%7D%2C+%7B%27optionId%27%3A+2%2C+%27text%27%3A+%7B" "%27en-GB%27%3A+%27Download+full+report%27%7D%7D%5D&_links=" "%7B%27self%27%3A+%7B%27method%27%3A+%27GET%27%2C+%27href%27%" "3A+%27%2Fassessments%2F898d915e-229f-48f2-9b98-cfd760ba8965" "%27%7D%2C+%27report%27%3A+%7B%27method%27%3A+%27GET%27%" "2C+%27href%27%3A+%27%2Freports%2F" "17340f51604cb35bd2c6b7b9b16f3aec%27%7D%7D" In my report view I get the payload from the url query string: class Reports(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def get(self, request, *args, **kwargs): result = request.GET data = result.dict() print(data) Now the problem is that the output of the transferred data which is printed above has quotes for nested keys. { 'cardType': 'CHOICE', 'step': '40', 'title': "{'en-GB': 'YOUR REPORT'}", 'description': "{'en-GB': ''}", 'options': "[{'optionId': 0, 'text': {'en-GB': 'Ask me'}}, {'optionId': 1, 'text': {'en-GB': 'Phone a nurse'}}, {'optionId': 2, 'text': {'en-GB': 'Download full report'}}]", '_links': "{'self': {'method': 'GET', 'href': '/assessments/898d915e-229f-48f2-9b98-cfd760ba8965'}, 'report': {'method': 'GET', 'href': '/reports/17340f51604cb35bd2c6b7b9b16f3aec'}}" } Notice the double quote in the "description", "options" keys … -
Why empty response headers after ajax call?
I post to Django 4 from index.html ajax call function check() { $.ajax({ url: '{% url "cb" %}', type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify({username: "{{request.user.username}}"}), headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken, }, success: function (response) { if (response.balance == true) { message = 'OK' $('#customModal').attr('class', 'alert alert-success').html(message); // exit from func } else { message = 'Awaiting' $('#customModal').attr('class', 'alert alert-info').html(message); } }, error: function (response) { console.log(response); }, }); } $(document).ready(function(){ setInterval(check,60000); }); view.py def cb(request): print(request.headers) When ajax call from localhost , response headers is ok {'Content-Length': '32', 'Content-Type': 'application/json', 'Host': '127.0.0.1:8000', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': 'http://127.0.0.1:8000/payment', 'X-Requested-With': 'XMLHttpRequest', 'X-Csrftoken': 'wNCgxlQH0L2KhDxUkZ9uDE5zGdnbhejyynbmBEhhsU7J4HXfcmztxY69Zr9A3jbe', 'Origin': 'http://127.0.0.1:8000', 'Dnt': '1', 'Connection': 'keep-alive', 'Cookie': 'csrftoken=yeNnsws4zk4UBKo7qJe5GrP92Vz5Gh7wbcTqHHDNZtTjPEdlu31I6T3dXIKi3w8S; sessionid=u448kfdu0dovpgad2aj2ig0fuitgrj7o', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin'} When I open index.html from server public ip, the result of response print(request.headers) HostConnectionContent-LengthUser-AgentAcceptAccept-LanguageAccept-EncodingContent-TypeCookieCache-Control -
I am facing Multiple dictionary key value error in djnago
Csv_file=request.files[‘csv’] i am getting multiple dictionary key values error Csv_file = request.files.get(‘csv’) If i use this one I couldn’t able to file validation Name=csv_file.name Size=csv_file.size Here i am getting no attribute name and size -
How to set foreign key default field type?
I have simple model: id type is int(10) class Client(models.Model): name = models.CharField(max_length=45) surname = models.CharField(max_length=45) And second model with foreign key referencing Client table. from django.contrib.auth.models import User class ExtendedUser(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) client = models.ForeignKey('Client', on_delete=models.DO_NOTHING, blank=True, null=False, default=1) class Meta: managed = True db_table = 'extended_user' When I run python manage.py makemigrations and python manage.py migrate y have: 1215, 'Cannot add foreign key constraint' SHOW ENGINE INNODB STATUS; -> FOREIGN KEY (client_id) REFERENCES client(id): Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. SQL sentence python .\manage.py sqlmigrate principal 0136: ALTER TABLE extended_user ADD COLUMN client_id bigint DEFAULT 1 NOT NULL , ADD CONSTRAINT extended_user_client_id_e51a6e7c_fk_client_id FOREIGN KEY (client_id) REFERENCES client(id); ALTER TABLE extended_user ALTER COLUMN client_id DROP DEFAULT; I tried client = models.ForeignKey('Client', on_delete=models.DO_NOTHING, blank=True, null=True, default=1) but still same error. Why Django is using bigint when I have primary key Int? How can I specify foreign key field type? -
Create or update related model object using Django management command
I need to periodically check on the status of a list of urls and report on their status. I created 2 models, one that has the list of main urls and another that holds all the sublinks on the pages of the main url. Model 1 class Site(CreationModificationDateBase, SoftDeletionModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250, unique=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) url = models.URLField(unique=True) status_code = models.CharField(max_length=3, blank=True, default="") status_message = models.CharField(max_length=255, blank=True, default="") def __str__(self): return f'{self.name}' Model 2 class Link(CreationModificationDateBase, SoftDeletionModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) site = models.ForeignKey(Site, on_delete=models.DO_NOTHING, blank=True, null=True) url = models.CharField(blank=True, max_length=250, default="") status_code = models.CharField('Site Status', max_length=3, blank=True, default="") status_message = models.CharField(max_length=255, blank=True, default="") def __str__(self): return f'{self.url}' class Meta: ordering = ('url',) verbose_name = "link" verbose_name_plural = "links" I have this method on Model1 that returns the status code and message from the ListView on load. def get_links(self): data = requests.get(self.url).text soup = BeautifulSoup(data, features="html.parser") anchors = soup.find_all("a") links = [] links_status = [] for link in anchors: link_href = link.get("href") if f"https" in link_href: links.append(link_href) elif f"http" in link_href: links.append(link_href) elif f"/" in link_href and len(link_href) > 1 and self.url not in link_href: links.append(self.url + link_href) for ll in links: … -
Django Rest nested serializers multiple model CRUD operations using mixins
I'm trying to implement CRUD operation with nested serializer with multiple data models so that I can write all field at once when I call the API endpoint. Should I use some sort of filtering or for loop ? I've not found similar post that is using mixins Django-Rest nested serialization OneToOne Django rest framework- writable(create,update) double nested serializer models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" class HomeworkSerializer(serializers.ModelSerializer): class Meta: model = Homework fields = __all__ class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" class All_Serializer(serializers.ModelSerializer): students = serializers.SerializerMethodField() homeworks = serializers.SerializerMethodField() courses = serializers.SerializerMethodField() def get_students(self, obj): students = obj.student_set.all() serializer = StudentSerializer(students, many=True) return serializer.data def get_homeworks(self, obj): homeworks = obj.homework_set.all() serializer = HomeworkSerializer(homeworks, many=True, read_only=True) return serializer.data def get_coruses(self, obj): courses = obj.courses_set.all() serializer = CourseSerializer(courses, many=True, read_only=True) return serializer.data class Meta: model = Student fields = ('student_id','firstName','age','homeworks','courses') … -
customizing django shell, injecting variables from a script
(likely was answered before, but no luck finding it) Every time I open a Django shell, I execute the same sequence of commands to get the environment set up, mostly loading JSON files which represent API responses, then doing data transformations to get the objects. Naturally, I started looking for a way to pre-initialize the environment with a script. I got as far as writing the script, which can be manually executed in a shell. However, a custom admin command doing all these things eludes me. Specifically, the line run_command('shell') starts a new process, which doesn't have any of the objects I've prepared in the script (as it ran in another process, duh). -
Django Keyerror on runserver until many restarts
I hope you can help me, I have a project with Django 2.2.25 and docker, but suddenly this error is showing: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check all_issues = self._run_checks( File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.8/site-packages/debug_toolbar/apps.py", line 37, in check_middleware if is_middleware_class(GZipMiddleware, middleware): File "/usr/local/lib/python3.8/site-packages/debug_toolbar/apps.py", line 81, in is_middleware_class middleware_cls = import_string(middleware_path) File "/usr/local/lib/python3.8/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/shared/middleware.py", line 8, in <module> from shared.exceptions import JsonNotFound File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 682, in _load_unlocked KeyError: 'shared.exceptions' I believe … -
Drop down menu implementation
Im making a job searching website using django. I think a nice touch is to have a couple of options where when you press them a drop down menu comes down with more options. For example a salary option and when it is pressed you see a couple of different salaries and when one of them is pressed a new query is sent out to the database. Lets say we only want jobs that pay more than 50,000. What would a query like that look like -
How do I get django decouple to use my updated env vars?
I use DECOUPLE in my Django project and its awesome. However, I recently changed an env variable to a new key and after restarting the server, it still used the old env key. I used a print statement to see the key being used. Does it cache the old one and still use it ? If so, how do I clear it? My workaround for now is just to rename the key when i update the var. Any help would be greatly appreciated. Many thanks A. -
Django IntegerField min length numbers
MinValueValidator How can i define the min length of the IntegerField? nummer = models.IntegerField( unique=True, validators=[MaxValueValidator(99999999), MinValueValidator(00000001), ]) Error Message: SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers -
Recommendation for the creation of a complex web application
My goal is to create a complex and modern web application, however, it has been three years since I last developed. I was using Spring API REST for the backend and React for the frontend at the time. Are there any other more interesting choices for you to consider? I heard about Django for the backend, what do you think? I would like to have a frontend that allows me to create a lot of interaction with the user (React?). A backend that allows to provide APIs usable by the frontend. -
How can i get username througth queryset?
I have some model: class Comments(models.Model): user = models.ForeignKey(User, related_name='user_comment', on_delete=models.CASCADE) heading = models.CharField(max_length=100) score = models.IntegerField(default = 1, validators=[MinValueValidator(1), MaxValueValidator(5)]) text = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_at',] def __str__(self): return self.heading And i when make .get request in shell: Comments.objects.get(pk=1).user I get: <User: user9> But when i make that request: Comments.objects.filter(pk=1).values('user') I get: <QuerySet [{'user': 9}]> For some reason, in the queryset I get only id, but not username. Due to the peculiarities of my application, I need to use exactly .filter or .all (), so I must somehow get the username in the queryset. Please help me. -
How to use filter method for user model in another model (django)
I have a custom user model : # accounts > models.py > ... class MyUser(AbstractUser): ... fallowing_tags = models.ManyToManyField('posts.tag', blank=True) and i want to filter all users who fallowed a specefic tag: from accounts.models import MyUser as User # ---- or ----- from django.contrib.auth import get_user_model User = get_user_model() class Tag(models.Model): name = models.SlugField(max_length=50, unique=True) @property def fallowers(self): return User.objects.filter(fallowing_tags=self) But the program gives an error: File "~/path/to/blog/accounts/models.py", line 13, in <module> from posts.models import Tag, Post File "~/path/to/blog/posts/models.py", line 3, in <module> from accounts.models import MyUser as User ImportError: cannot import name 'MyUser' from partially initialized module 'accounts.models' (most likely due to a circular import) (~/path/to/blog/accounts/models.py) -
What are the default expiry time for Access Token and Refresh Token? (Django GraphQL JWT)
I use Django GraphQL JWT. Then, I could set the expiry time for Access Token and Refresh Token in "settings.py" as shown below: # "settings.py" from datetime import timedelta GRAPHQL_JWT = { "JWT_VERIFY_EXPIRATION": True, "JWT_LONG_RUNNING_REFRESH_TOKEN": True, "JWT_EXPIRATION_DELTA": timedelta(minutes=60), # For "Access Token" "JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=180), # For "Refresh Token" } Now, I want to ask: What are the default expiry time for Access Token and Refresh Token in Django GraphQL JWT? -
How do I create range slider in django?
I want this type of slider in django I have searched a lot but I am not getting this particular slider, any help would be appreciated. -
django - nothing under added model
What i am trying to tackle is best shown in pics , enter image description here Whenever I try to click on View others to see everything in the Recently added genre it leads to the following page enter image description here What am i doing wrong? to make reading shorter for you guys - movie_category is what I am trying to access here movie\urls.py from django.urls import path from .views import MovieList, MovieDetail, MovieCategory, MovieLanguage, MovieSearch, MovieYear app_name = 'movie' urlpatterns = [ path('', MovieList.as_view(), name='movie_list'), path('category/<str:category>', MovieCategory.as_view(), name='movie_category'), path('language/<str:lang>', MovieLanguage.as_view(), name='movie_language'), path('search/', MovieSearch.as_view(), name='movie_search'), path('<slug:slug>', MovieDetail.as_view(), name='movie_detail'), path('year/<int:year>', MovieYear.as_view(), name='movie_year'), ] views.py from django.views.generic import ListView, DetailView from django.views.generic.dates import YearArchiveView from .models import Movie, MovieLinks # Create your views here. class HomeView(ListView): model = Movie template_name = 'movie/home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['top_rated'] = Movie.objects.filter(status='TR') context['most_watched'] = Movie.objects.filter(status='MW') context['recently_added'] = Movie.objects.filter(status='RA') return context class MovieCategory(ListView): model = Movie paginate_by = 2 def get_queryset(self): self.category = self.kwargs['category'] return Movie.objects.filter(category=self.category) def get_context_data(self, **kwargs): context = super(MovieCategory, self).get_context_data(**kwargs) context['movie_category'] = self.category return context Models.py STATUS_CHOICES = ( ('RA', 'RECENTLY ADDED'), ('MW', 'MOST WATCHED'), ('TR', 'TOP RATED'), ) class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = …