Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django asgi Single thread executor already being used, would deadlock deployment error
my run command for django asgi application using gunicorn looks like this: gunicorn -b '0.0.0.0:8000' myproject.asgi:application -w 4 -k uvicorn.workers.UvicornWorker --access-logfile /logs/access.log --access-logformat "%(h)s %(l)s %(u)s %(t)s %(r)s %(s)s %(b)s %(f)s" >> /logs/error.log When I try to access any endpoint of the application, I get Single thread executor already being used, would deadlock error. I am using following package versions: Django=3.2.4 asgiref==3.4.0 uvicorn==0.15.0 gunicorn==20.1.0 -
Django star rating system AJAX and JavaScript
I am trying to implement a star rating system on a Django site. I have found the following, and like the style of the stars here: https://www.w3schools.com/howto/howto_css_star_rating.asp Currently have a limited understanding of JavaScript, AJAX and Django. Does anyone know how to use the stars in the above example combined with AJAX and Django, so you are able to update the database (models) without a page refresh when a user selects a rating? It is also important that users are only able to vote once, i.e. they are not allowed to rate a page twice. For this, there must be an IP check. I am confused about the code and I need help. models.py: class Rating(models.Model): ip = models.CharField(max_length=15) post = models.ForeignKey(Post, related_name='ratings', on_delete=models.CASCADE) score = models.IntegerField(default=0, validators=[ MaxValueValidator(5), MinValueValidator(0), ] ) def __str__(self): return str(self.pk) views.py: def RatingView(request): obj = Rating.objects.filter(score=0).order_by("?").first() context ={ 'object': obj } return render(request, 'blog/post_detail.html', context) # def get_client_ip(self, request): # x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') # if x_forwarded_for: # ip = x_forwarded_for.split(',')[0] # else: # ip = request.META.get('REMOTE_ADDR') # return ip def RateView(request): if request.method == 'POST': element_id = int(request.POST.get('element_id')) val = request.POST.get('val') print(val) obj = Rating.objects.get(id=element_id) obj.score = val obj.save() return JsonResponse({'success':'true', 'score': val}, safe=False) … -
Pass video uploaded via django to cv2
I am uploading video via django and want to process it using cv2. This is how video uploaded via django is accessed. video_obj = request.FILES['file_name'] Next i want to pass it to opencv. I dont want to save video in disk first and then acess it via cv2 using following code cap = cv2.VideoCapture(vid_path) I tried passing this video_obj to VideoCapture this way video_obj = request.FILES['file_name'] cap = cv2.VideoCapture(video_obj) But i got following error Can't convert object of type 'TemporaryUploadedFile' to 'str' for 'filename' VideoCapture() missing required argument 'apiPreference' (pos 2) -
Django: Foreign Key to User -> Form is not validating because field is required
I'm currently creating a Registration-Page with two parts One part is about the Username and a Passwort. The second part is about choosing the own PC-Configuration After defining everything, the User can register to get to the Main-Page. Therefore I got a Model called "PC_Configuration" with a bunch of Foreign-Keys to the different Database-Models of the Processors/Graphicscards etc.: class PC_Configuration(models.Model): user = models.ForeignKey(User, related_name='user_id', on_delete=models.DO_NOTHING) processor = models.ForeignKey(Processors, related_name='processor_id', on_delete=models.DO_NOTHING) graphicscard = models.ForeignKey(Graphicscard, related_name='graphicscard_id', on_delete=models.DO_NOTHING) os = models.ForeignKey(OS, related_name='os_id', on_delete=models.DO_NOTHING) ram = models.ForeignKey(RAM, related_name='ram_id', on_delete=models.DO_NOTHING) harddrive = models.ForeignKey(Harddrive, related_name='harddrive_id', on_delete=models.DO_NOTHING) Also, there is one ForeignKey to the User to connect the Configuration to the respective User-ID. Inside views.py, I've been creating a DropdownForm for all the Dropdown-Fields which the User shall choose on his own: class DropdownForm(forms.ModelForm): class Meta: model = models.PC_Configuration exclude = [] def __init__(self, *args, **kwargs): super(DropdownForm, self).__init__(*args, **kwargs) self.fields['processors'].queryset = DropdownForm.objects.all() self.fields['processors'].label_from_instance = lambda obj: "%s" % obj.name self.fields['graphicscard'].queryset = DropdownForm.objects.all() self.fields['graphicscard'].label_from_instance = lambda obj: "%s" % obj.name self.fields['os'].queryset = DropdownForm.objects.all() self.fields['os'].label_from_instance = lambda obj: "%s" % obj.name self.fields['ram'].queryset = DropdownForm.objects.all() self.fields['ram'].label_from_instance = lambda obj: "%s" % obj.name self.fields['harddrive'].queryset = DropdownForm.objects.all() self.fields['harddrive'].label_from_instance = lambda obj: "%s" % obj.name But regarding the fact, that the User-ID shall … -
Blank page showing in django server after adding python in index.html file
please help i'm following a tutorial and not showing desierd output in the server page. Every thing was going smoothly until the index.html page content not shown This is my index.html file <!DOCTYPE html> <html lang="eng"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script> <title>document</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> </head> <body> <div class="container"> <div class="row"> **{% for Product in product_objetcs %}** <div class="col-md-3"> <div class="card"> <img src="{{ product.image }}" class="card-img-top"> <div class="card-body"> <div class="card-title"> **{{ product.tittle }}** </div> <div class="card-text"> **{{ product.price }}** </div> </div> </div> **{% endfor %}** </div> </div> </div> </body> </html> this is my views page from django.shortcuts import render from.models import Product # Create your views here. def index(request): product_objects = Product.objects.all() return render(request, models "my models page looks like this" from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=200) price = models.FloatField() discount_price = models.FloatField() category = models.CharField(max_length=200) description = models.TextField() image = models.CharField(max_length=300) -
How to setup Openwisp-radius with Django
Hello kindly help with is error, i am trying to get started with openwisp-radius with django project. after setting up my django project with openwisp radius when i run py manage.py migrate i run into this error Applying openwisp_radius.0013_remove_null_uuid_field...Traceback (most recent call last): django.db.utils.OperationalError: (1280, "Incorrect index name 'nas_uuid_694a814a_uniq'") -
django (errno: 150 "Foreign key constraint is incorrectly formed")')
recently when in want to migrate my model I encountered this error in django: "(errno: 150 "Foreign key constraint is incorrectly formed")')" class PartCategory(models.Model): name=models.CharField("نام",max_length = 50) code=models.CharField("کد",max_length = 50,unique=True) description=models.CharField("توضیحات",max_length = 50) priority=models.IntegerField("اولویت", null=True) isPartOf = models.ForeignKey('self',on_delete=models.CASCADE,verbose_name="زیر مجموعه",null=True,blank=True) def __str__(self): return self.name class Meta: db_table = "partcategory" -
Cloudinary Image Upload errpr in django python while hosted in pythonanywhere
So i use pythonanywhere to host a django website where pictures are uploaded and shown the uploaded pictures are stored in cloudinary showing the pictures is working fine but when i upload a post i get this error: Error at /post/ Unexpected error - MaxRetryError("HTTPSConnectionPool(host='api.cloudinary.com', port=443): Max retries exceeded with url: /v1_1/meme-topia/image/upload (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f8d77f41370>: Failed to establish a new connection: [Errno 111] Connection refused'))") Models file: from django.db import models from cloudinary.models import CloudinaryField # Create your models here. class MemeImg(models.Model): Title = models.CharField(max_length=500) Post_Img = CloudinaryField('image') def __str__(self): return self.Title Forms file: from django import forms from .models import MemeImg class PostImg(forms.ModelForm): class Meta: model = MemeImg fields = '__all__' And then the source code link:https://github.com/Shadow-Knight503/memoster503.git Please help -
Django/Vue session data for login in development mode
I have a Django/Vue app. I want to login my user to my app but I don't know how it works in the development mode. For production, I build my vue files and access them via Django views so in production, sessions are simply managed by Django. This is OK. But in development mode, I access the FE via a different port. In this case, when I login my user, how Django know that this user is logged in? What should I do to make this happen as in Production without extra configurations? If extra configurations are needed, what are they? -
Django comments xtd giving me error 404 when posting a comment
I have implemented Comments XTD package to allow users to comment in my Article model. Everything works great except the fact that when I am clicking Send I get Error 404. Comment and I need to manually come back to the article to see my newly added comment. I also receive email notification so the only problem is with url that is being generated once I click Send. Could you please tell me how to fix it? article_detail.html <div id="comments" class="pb-4 mb-4"> {% get_comment_count for article as comment_count %} {% if comment_count %} <h5> {% blocktrans count comment_count=comment_count %} There is {{ comment_count }} comment below. {% plural %} There are {{ comment_count }} comments below. {% endblocktrans %} </h5> <hr /> {% endif %} {% if article.allow_comments %} <div class="comment"> <H4 class="">Post your comment</H4> <div class="well"> {% render_comment_form for article %} </div> </div> {% else %} <h5 class="">Only moderators can add comments in this article</h5> {% endif %} {% if comment_count %} <hr /> <ul class="media-list" id="comment-list" style="text-align: left;"> {% render_xtdcomment_tree for article allow_feedback show_feedback allow_flagging %} </ul> {% endif %} </div> urls.py in my articles app urlpatterns = [ path('articles/', views.articles_view, name='articles'), path('article/<slug:slug>', views.ArticleDetailView.as_view(), name='article'), ] urls.py in … -
Django REST Framework - how to start functions on backend after event on frontend
I'm creating webapp and using DRF on the server. I want to start function on server, after event on frontend (for example - button clicked) Example: User is typing '2021' in input field on frontend and click the button ,,generate" The '2021' is transfering to function ,generate_list_of_sundays(year)' on server The function return list of all sundays in typed year List is displayed to user on frontend Of course this is simple example. I want to know how to get this type of communications between frontend and backend. -
Complex annotation to get all statuses for each user counted
In my leads table I need to count the number of leads for each status for each user. Is there a way to do that by arm annotate ? Right now I have something like this: leads.objects.values("created_by","status").annotate(total=Count("status")).order_by("created_by") and output is like: [{'created_by':"Andrew Ray', "status":'ACTIVE", 'total':4}, {'created_by':Andrew Ray', "status":'LOST", 'total':2}, {'created_by':Andrew Ray', "status":'WON", 'total':1}] is there a way to get it like this: [{'created_by':"Andrew Ray', "ACTIVE" : 4, "LOST": 2, "WON":1}] Active Won Lost are a values of STATUS field in leads model there is also another there and I would like to make key and value pai for each of them for each user (CharField) -
django 4.0rc1 and django-taggit "TypeError: get_extra_restriction() missing 1 required positional argument: 'related_alias'" on filtering by Tag
After upgrading Django to 4.0rc1, wherever I try to filter Objects by it's Tag (django-taggit) entrys = Entry.objects.filter(tags__name__in=["Tag1", "Tag2"]) or entrys = Entry.objects.filter(tags__id=tag.id) I get the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1189, in execute_sql sql, params = self.as_sql() File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 545, in as_sql from_, f_params = self.get_from_clause() File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 833, in get_from_clause clause_sql, clause_params = self.compile(from_clause) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 463, in compile sql, params = node.as_sql(self, self.connection) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/datastructures.py", line 81, in as_sql extra_cond = self.join_field.get_extra_restriction(self.table_alias, self.parent_alias) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/fields/reverse_related.py", line 168, in get_extra_restriction return self.field.get_extra_restriction(related_alias, alias) TypeError: get_extra_restriction() missing 1 required positional argument: 'related_alias' Does anyone have a solution or a workaround? -
Django logger does not log below warning level on server
I cannot get the django logger log below WARNING level on my web server. The below configuration logs as intended on localhost dev server, but not on my web server (Nginx, gunicorn). The log file as defined in the file handler is created and logs are written to it, but only logs of level WARNING and above. My goal is to log INFO level logs as well (such as GET requests). I found this discussion (https://stackoverflow.com/questions/65362608/), but it didn't help. I tried configuring root logger for INFO level by adding '': {#same settings as in below django logger} to loggers, but that did not have any effect. I restarted both Nginx and gunicorn. #in settings.py DEBUG = False LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'detailed': { 'format': '{levelname} {asctime} {message}', 'style': '{', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', } }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/django.log', 'formatter': 'detailed' }, 'mail': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_false'], } }, 'loggers': { 'django': { 'handlers': ['file', 'mail'], 'level': 'INFO', 'propagate': True, }, }, } Any ideas what might be causing the issue? -
How to put appropriate keyboard after clicking on the form in Django?
I just built one app, but that app needs language that is not English to type in.I want user to get a keyboard of that language after clicking the text field to type something. Is that possible in Django? When I don't have any keyboard, my Android just gives me English keyboard, which is not what I want. I don't want to change in settings. I want my user in any part of the world to get as a user experience keyboard of that language, no matter is it on computer or on mobile device. -
how can i implement django input form with the default values
writing an online store I have a form to add items to cart with different quantities. I have implemented this through "TypedChoiceField": class CartAddProductRetailForm(forms.Form): quantity = forms.TypedChoiceField( choices=PRODUCT_RETAIL_QUANTITY_CHOICES, coerce=int, label='quantity', ) But it looks ridiculous. Can you tell me how to implement it with a "CharField" or "DecimalField" with a default '1' value. quantity = forms.DecimalField(max_value=999, min_value=1, ) Thanks! -
How to display the category 1 item into category 2 based on UID in Django Model?
How to display the category 1 item into category 2 based on UID in Django Model? Category_1: UID Item 1 A 1 B 2 C 2 D expected result: Category_2: UID Category_1 Cateogry_1_Des 1 1 A 2. 1. B 3. 2 c 4. 2. D Model coding (show all item of category_1 but want to show only item mathcing UID) : Category_2 = models.ForeignKey( Category_1, verbose_name=_('cat2'), related_name='cat2' ) -
Get Queryset Django based on another one
Have this model: class Review(models.Model): RATING_VALUES = [ ('1', 'Ужасно'), ('2', 'Плохо'), ('3', 'Сносно'), ('4', 'Хорошо'), ('5', 'Отлично'), ] spare_part = models.ForeignKey('SparePart', on_delete=models.PROTECT, verbose_name="Запчасть") mileage = models.SmallIntegerField(verbose_name="Пробег, тыс.км") car_brand = models.ForeignKey('CarBrand', on_delete=models.PROTECT, verbose_name="Марка авто") car_model = models.ForeignKey('CarModel', on_delete=models.PROTECT, verbose_name="Модель авто") owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Владелец") rating = models.CharField(max_length=1, choices=RATING_VALUES, verbose_name="Рейтинг", default=3) testimonial = models.TextField(max_length=1000, blank=True, verbose_name="Отзыв") likes = models.ManyToManyField(User, related_name='like', default=None, blank=True, verbose_name="Лайки") like_count = models.BigIntegerField(default='0', verbose_name="Кол-во лайков") date = models.DateTimeField(default=now, verbose_name='Дата') In views.py I get all User reviews like this: user_reviews = Review.objects.filter(owner_id=request.user.id).order_by('spare_part', 'spare_part__category_id') And now I need to get all the Review objects which current user liked. I do it this way, but get an error "Cannot use QuerySet for "Review": Use a QuerySet for "User"." user_liked = Review.objects.filter(likes__in=user_reviews) How to di it right? -
Am trying to create a date field where a user can select when to set an appointment with a worker. Am only getting a blank field with no Date picker
class Appointment(models.Model): CATEGORY = ( ('Plumbing', 'Plumbing'), ('Electrical', 'Electrical'), ('Cleaning', 'Cleaning'), ) STATUS = ( ('Pending', 'Pending'), ('Delivered', 'Delivered'), ) user = models.ForeignKey(Client, null=True, on_delete=models.SET_NULL) worker = models.ForeignKey(Worker, null=True, on_delete=models.SET_NULL) category = models.CharField(max_length=200, null=True, choices=CATEGORY) task_date = models.DateField(_("Task Date"), blank=True, null=True) task_location = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) task_description = models.CharField(max_length=1000, null=True) def __str__(self): return str(self.user) forms.py file class AppointmentForm(ModelForm): class Meta: model = Appointment fields = '__all__' exclude = ['user','worker','status'] widgets = {'task_date': forms.DateInput(format='%d/%m/%Y')} -
Django & React: Connecting multiple apps from one template
Good morning, I would like to ask, if it's possible to connect multiple apps in django, each using his own react frontend? For example: I have one main page that holds all the links to the different applications... Folder-Structure: |- project | |- app_main | | |- templates | | | |- app_main | | | | |- main.html | |- app_1 | | |- frontend_1 (react) | | | |- public | | | | |- index.html | |- app_2 | | |- frontend_2 (react) | | | |- public | | | | |- index.html As I understood - or at least I think so -, the folder holding the html-files have to be included inside the template in settings.py... settings.py REACT_ROUTE_APP_1 = os.path.join(BASE_DIR, 'app_1', 'frontend_1', 'public') REACT_ROUTE_APP_2 = os.path.join(BASE_DIR, 'app_2', 'frontend_2', 'public') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ REACT_ROUTE_APP_1, REACT_ROUTE_APP_2 ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Is this the right way or is there a much better solution? And if it's the right choice, how can I connect the url-route inside my ? main.html <div> <a href="?">Link to App 1</a> <a href="?">Link to App 2</a> </div> … -
I am creating a TodoApp using Django3.2 and React js and I got the error: cannot import views
I am creating a Todo App using Django 3.2 with python 3.6.8 and react js. I have installed the djangorestframework and Django-cors-headers. However, I cannot get the App views. I could not do the migration as well. I got the following error when I try to run the server: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen … -
How to update the content of a div after an AJAX call
I have a div (<div class="card-body">) and I want to put elements inside from the database (the elements are retrieved via AJAX call) But I need something dynamic since I will be adding content dynamically and apparently Django template tags are not enough. How can I do something like that from the ajax success function? index.html: {% extends 'base_generic.html' %} {% load static %} {% block content %} {% get_current_language as LANGUAGE_CODE %} <script type="text/javascript"> $(document).ready(function () { $.ajax({ url: '/todo_ajax/', type: 'get', success: function(data) { alert(data); }, failure: function(data) { console.log('Got an error dude'); } }); }); </script> <div class="wrapper"> <!-- Index Content --> <div id="content"> <div class="row row-cols-1 row-cols-md-3 g-4 mb-5"> <div class="col"> <div class="card h-100"> <div class="card-header" id="toDoHeader"> ... (truncated) </div> <div class="card-body"> {% for o in some_list %} <div class="cardItem cardItemIndex" class="mb-3"> <div class="row"> <div class="col"> <h6 class="card-title">{{ o.title }}</h6> </div> </div> <div class="row"> <div class="col"> <p class="card-text">{{ o.description }}</p> </div> </div> <p class="card-text to-do-footer">{{ o.start_date }} - {{ o.end_date }}</p> </div> {% endfor %} </div> </div> </div> </div> </div> </div> {% endblock %} views.py @login_required def todo_ajax(request): response = dict() if request.method == 'GET': to_do_list = ToDoList.objects.all().filter(user=request.user) data = serialize("json", to_do_list) return HttpResponse(data, content_type="application/json") return … -
django, python why timestamp changes after localize
CODE: import pytz from django.utils import timezone KST = pytz.timezone('Asia/Seoul') UTC = pytz.timezone('UTC') default_time = timezone.datetime(2021, 11, 29, 16, 44) current_manual_kst = KST.localize(default_time) current_manual_utc = default_time print(current_manual_kst.timestamp()) print(current_manual_utc.timestamp()) RESULT: >>> 1638171840.0 >>> 1638204240.0 So, I can see that results are different. I thought timestamps should be the same but results are not. Why this happened? And How to get the same timestamps (by default: UTC) from KST.localized datetime? -
SMTPSenderRefused getting this error while requesting the forget password
Getting the below error when I submit user's email address to get the password reset link the below pic is settings.py file -
How are all serializer errors returned in DRF at once?
I'm testing for multiple validation errors to be raised in(UserRegistrationSerializer). Yet DRF only returns the first error that is raised: {'username': [ErrorDetail(string='Choose a different username', code='invalid')]} I'm expecting: {'username': [ErrorDetail(string='Choose a different username', code='invalid')], 'password2': [ErrorDetail(string='Password confirmation failed', code='invalid')] How can multiple errors be accounted for once a serializer is validated as in the documentation example? https://www.django-rest-framework.org/api-guide/serializers/#validation class TestRegisterationSerializer__002(TestCase): '''Verify that the registeration process fails with respect to selecting an unavailable username and password confirmation''' @classmethod def setUpTestData(cls): User.objects.create_user(username="Python") cls.data = { 'username': "Python", 'password': "#secret#", 'password2': "Secret" } cls.error_messages = [ "Choose a different username", "Password confirmation failed" ] cls.serializer = UserRegisterationSerializer(data=cls.data) def test_user_registeration_invalid_confirmation(self): self.serializer.is_valid() print(self.serializer.errors) import re from django.contrib.auth.models import User from rest_framework import serializers class UsernameSerializer(serializers.ModelSerializer): username = serializers.SlugField(min_length=4, max_length=12) def validate_username(self, value): try: self.Meta.model.objects.get(username__iexact=value) except self.Meta.model.DoesNotExist: return value raise serializers.ValidationError("Choose a different username") class Meta: fields = ['username', ] model = User class LoginSerializer(UsernameSerializer): password = serializers.RegexField( r"[0-9A-Za-z]+", min_length=5, max_length=8 ) def validate(self, data): username, password = [ input.lower() for input in [data['username'], data['password']] ] if all(password[i] == password[i + 1] for i in range(len(password) - 1)) or username == password: raise serializers.ValidationError({ 'password': "Invalid password" }) return data class Meta: fields = ['username', 'password', ] …