Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When using django.test.client.post I get Bad Request
I use pytest-django to do unit test on my django project. The view is def news(request): """ Interface for newslist """ page = 1 if request.method == 'POST': content = request.body try: content = json.loads(content) except ValueError as error: return err_response("Value Error of post: {}".format(error)) if 'page' in content: page = content['page'] articlelist = Article.objects.all().order_by('-time') paginator = Paginator(articlelist, 10) try: current_list = paginator.page(page) except InvalidPage as error: return err_response(error) # coping with the paginator ... newsnum = len(Article.objects.all()) return JsonResponse({ 'newsnum': newsnum, 'pagelist': list(pagelist), 'data': [{ 'title': newsitem.title, 'source': newsitem.source, 'time': newsitem.time.strftime("%Y-%m-%d %H:%M:%S"), 'content': newsitem.content, 'href': newsitem.href, 'image': newsitem.image, } for newsitem in current_list] }, status=200) When I use pytest-django to test it @pytest.mark.django_db def test_view_news(client): """ Test view news """ url = reverse("news") data = { 'page': 1 } response = client.post(url, data=data) assert response.status_code == 200 It gives Bad Request and code 400. But when I use client.get(), the response is normal (code 200).In the settings, I already set DEBUG = True ALLOWED_HOSTS = ['*'] Can anyone tells me what happened? -
How to Django reverse to pages created in Wagtail?
I have a Wagtail model for an object. class ObjectPage(Page): # fields, not really important I want to make the object editable by front-end users, so I have also created a generic update view to accomplish this. My question is how I can use Django's reverse() function to point to the edited object in my get_success_url() method: class EditObjectPage(LoginRequiredMixin, UpdateView): # model, template_name, and fields defined; not really important def get_success_url(self): return("ObjectPage", kwargs={"slug" : self.object.slug}) # doesn't work return("object_page_slug", kwargs={"slug" : self.object.slug}) # also doesn't work I know how to do this when I'm explicitly defining the URL name in my urls.py file, but in this case, the URL is created as a Wagtail page and is handled by this line of my urls.py: url(r"", include(wagtail_urls)), I've been searching the documentation for whether Wagtail pages are assigned names that can be reversed to, but I'm finding nothing in the official documentation or here on StackOverflow. -
Django How to add data to database from javascript
I am have created a page in django, on this page I have create a button that calls a JavaScript function which in turn gets data from a API. This part of my code works as expected as it writes the response data to the console. However I cannot seem to get that data to be inserted into the model I have created in django. I am not sure how python/javascript/models are meant to all link together. models.py from django.db import models class Set(models.Model): scry_id = models.CharField(max_length=255) code = models.CharField(max_length=255) name = models.CharField(max_length=255) set_type = models.CharField(max_length=255) release_date = models.DateField() card_count = models.IntegerField() block_code = models.CharField(max_length=255, null=True) block_name = models.CharField(max_length=255, null=True) parent_set_code = models.CharField(max_length=255, null=True) digital_only = models.BooleanField(default=False) foil_only = models.BooleanField(default=False) nonfoil_only = models.BooleanField(default=False) icon = models.CharField(max_length=255) status = models.BooleanField(default=False) def __str__(self): return self.name sets.html {% extends "main/index.html "%} {% block content %} <div class="background card"> <div class="card-body"> <button class="btn" id="setRefresh" style="border: 1px solid" onclick="setRefresh()"><i class="fas fa-sync"></i></button> </div> </div> {% endblock%} custom.js function setRefresh() { const Url="https://api.scryfall.com/sets"; fetch(Url) .then(res => res.json()) .then(data => obj = data.data) .then(() => obj.sort(function(a,b){return a.released_at.localeCompare(b.released_at);})) .then(() => { for (var i = 0; i < obj.length; i++) { //console.log(obj[i].name); } }) } -
django normalize() argument 2 must be str, not None when adding a user's bio of a custom user model
when i try to add a user's bio from the admin panel in my custom user model when i hit save the following error appears normalize() argument 2 must be str, not None here are the models in my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email,bio, full_name, password=None): if not email: raise ValueError('Users must have an email address') if not full_name: raise ValueError('Users must have a name') user = self.model( email=self.normalize_email(email), bio=bio, full_name=full_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, full_name, password): user = self.create_user( email=self.normalize_email(email), full_name=full_name, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name="Email",max_length=250, unique=True) username = models.CharField(max_length=30, unique=True, null=True) date_joined = models.DateTimeField(verbose_name='Date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='Last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) bio = models.TextField(null=True, blank=True) full_name = models.CharField(verbose_name="Full name", max_length=150, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = MyAccountManager() def __str__(self): return self.full_name # For checking permissions. def has_perm(self, perm, obj=None): return self.is_admin # For which users are able to view the app (everyone is) def has_module_perms(self, app_label): return True every other field is addable normally and works fine except this … -
Apply DRY to a dict where data is coming from different vars
I have two functions where I pass the dict event_data = {[...]} to the Google API. The only difference is that for update_calendar_event the data is coming from a dict. For create_calendar_event it is an obj. Do you have any idea how to apply DRY here while considering that it's these two different types? class GoogleCalendarAPI: def __init__(self) -> None: # cache_discovery=False to avoid ImportError self.service = build( "calendar", "v3", credentials=credentials, cache_discovery=False ) def _event_link(self, event_slug: str) -> str: return "https://example.com/events/" + event_slug def update_calendar_event( self, calendar_event_id: str, validated_data: Dict[str, Any], event_slug: str ) -> None: event_data = { "summary": validated_data.get("name"), "description": validated_data.get("description") + "\n\nEvent link: " + self._event_link(event_slug), "start": { "dateTime": validated_data.get("start_date").isoformat(), "timeZone": validated_data.get("timezone"), }, "end": { "dateTime": validated_data.get("end_date").isoformat(), "timeZone": validated_data.get("timezone"), }, } self.service.events().patch( calendarId=CALENDAR_ID, eventId=calendar_event_id, body=event_data ).execute() def create_calendar_event(self, event_instance) -> str: event_data = { "summary": event_instance.name, "description": event_instance.description + "\n\nEvent link: " + self._event_link(event_instance.slug), "start": { "dateTime": event_instance.start_date.isoformat(), "timeZone": event_instance.timezone, }, "end": { "dateTime": event_instance.end_date.isoformat(), "timeZone": event_instance.timezone, }, } event = ( self.service.events() .insert(calendarId=CALENDAR_ID, body=event_data) .execute() ) return event.get("id") -
Override label offset in Fieldset for Crispy Forms
I have a Fieldset in my layout, which contains a checkbox on the first line. For the main form I've set: self.helper.layout_class = "create-label col-md-2" which aligns my labels and fields and creates an "even" form. The problem is, this gets applied within a fieldset and a checkbox gets shuffled to the right, description on the right, and it looks like it's just hanging in the middle of the screen: This is because the generated html is applying the offset generated for labels, and ends up looking like this: <div class="form-group row"> <div class="offset-md-2 col-md-10"> <div id="div_id_allow_invitees_to_add_others" class="custom-control custom-checkbox"> <input type="checkbox" name="allow_invitees_to_add_others" class="checkboxinput custom-control-input" id="id_allow_invitees_to_add_others"> <label for="id_allow_invitees_to_add_others" class="custom-control-label"> Allow invitees to add others </label> If I manually remove the offset-md-2 in the browser inspector, it displays exactly as I want - over on the left ... I just moved the Fieldset to it's own Div in the hope I could override this, but no joy. That bit of the layout is fairly simple: Div( Fieldset( _("Invitees"), Field("allow_invitees_to_add_others"), Formset("invitees"), ), css_class="", ), Can anybody advise me on how to get this checkbox over on the left! -
Django, how to convert Python dict to Javascript
In a Django app I have a dict created in a view and I want to use it in Javascript, but I get a syntax error views.py MY_TYPES = { 'use_random': 0, 'use_stages': 1, 'use_import': 2, 0: 'use_random', 1: 'use_stages', 2: 'use_import', } class Duo(View): url = 'duo/test_dict.html' def get(self, request, partner_pk): context = { 'my_types': json.dumps(MY_TYPES), } return render(request, self.url, context) test_dict.html {% load static %} <head> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> </head>` {% block content %} <h1> Test dict</h1> <script> my_types = {{ my_types|safe }}; </script> <script type="text/javascript" src="{% static 'js/test_dict.js' %}"></script> {% endblock content %} test_dict.js $(document).ready(function () { console.log(my_types) console.log(JSON.parse(my_types)) }); Line 2 gives the output {0: "use_random", 1: "use_stages", 2: "use_import", use_random: 0, use_stages: 1, use_import: 2} but throws the error in line 3 SyntaxError: Unexpected token o in JSON at position 1 What am I doing wrong? -
How do I implement five star rating in Django DetailView?
I'm currently working on a restaurant review site and I'm struggling with displaying a five star rating comment form in a class based DetailView page. How do I implement a five star rating system for my class based RestarurantDetail page? I would like to change the appearence on my Integerfield "rate" to a five star rating field. I would still like to display all other fields in the comment form as normal, perhaps with crispy forms (but it's perhaps not possible if I want to customize the rate field?) If you need aditional information, just let me know! Code Restaurant Model (parts of it) in Models.py class Restaurant(models.Model): name = models.CharField(max_length = 100) country = models.CharField(max_length = 75) city = models.CharField(max_length = 75) address = models.CharField(max_length = 100) categori = models.ManyToManyField(Kategori) description = models.CharField(max_length = 300, blank=True) approved = models.BooleanField(default=False) geom = PointField(null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: unique_together = ('country', 'city', 'adress') Comment Model in Models.py class Comment(models.Model): ALTERNATIVES_1 = ( ('Alt 1', 'Alt 1'), ('Alt 2', 'Alt 2'), ('Alt 3', 'Alt 3'), ) restaurant = models.ForeignKey(Restaurant, on_delete = models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 50, blank = … -
Django static folder with css and javascript wont load
Hey I have a problem with the static files directory in Django, Inside the html template I already used the {% load static %} above the link tag and in the link tag I used href="{% static 'style.css' %}" (keep in mind the style.css is in the static folder which is located in the projects root folder (after several times "still not working" I even created the same static folder with the same css file in the respective app folder... and still not working). In the settings.py I used all of the following lines one at a time and even all together STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/static") STATIC_DIRS = ( '/static', ) the html renders perfectly fine and is showing in the browser without any errors but for whatever reason the styling just wont apply (internal and inline sytling works, but I want to use external css). There seems to be a problem in the settings.py file but since I gave the path to the static folder in any way possible, I really don't know what to do. I didnt try with .js files yet but it'll be the same problem I guess. I'm thankfull for any answer. -
ImproperlyConfigured at /posts/new-comment/12/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
How can i fix this error. When i write comment and click on 'add comment' button than it shows me the error which i mentioned in the title. I don't get it how can i fix it. Please help me to fix this error. I shall be very thankful to you. I just want that after commenting he should redirect to the post detail view on which post a person leave a comment. model.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post,related_name='comments', on_delete=models.CASCADE) body = models.TextField() create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.author.username def get_absolute_url(self): return reverse("posts:post_detail", kwargs={"pk": self.post_id,"slug":self.post_slug}) urls.py app_name = 'posts' urlpatterns = [ path('int:pk/str:slug/',views.PostDetailView.as_view(),name ='post_detail'), path('new-comment/int:pk/',views.CommentCreateView.as_view(),name= 'comment_create'), ] view.py class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm template_name = "posts/snippets/comment_form.html" def form_valid(self, form,*args, **kwargs): form.instance.post_id = self.kwargs['pk'] # form.instance.post_slug = kwargs['slug'] form.instance.author = self.request.user return super().form_valid(form) template(postdetail.html) {% if not post.comments.all %} No comments <a href="{% url 'posts:comment_create' pk=post.pk%}">Add one</a> {% else %} <a href="{% url 'posts:comment_create' pk=post.pk%}">Add one</a> if more details are require than tell me in the comment session. i will update my question with that detail. -
'int' object is not iterable?(Django template)
Here is Django template code. I tried to put out images to template. amount of image put out to template is depending on {{object.image_amount}} {% for i in object.image_amount %} <td><img src="{% static 'rulings_img/' %}{{object.item_hs6}}/{{object.id}}-{{object.image_amount}}.jpg" width="100" height="100"></td> <td>{{object.image_amount}}</td> {% endfor %} When I tried this code error message appeared. 'int' object is not iterable How can I solve this error? -
How to create the dummy the redis in Django test?
I am trying to create the dummy redis in Django test. My tests.py looks as below class TestInitiatePositive(SimpleTestCase): databases = '__all__' def setUp(self): pass @responses.activate def test_initiate_payment(self): self.credentials = { 'username': '*****', 'password': '*****' } User.objects.create_user(**self.credentials) self.client.login(username='*****',password='*****') abc.objects.create(user_id_id ='1',nick_name = 'KONTO', access_token ='eyJ0eXAiOiJ') response = self.client.post('/hello/initiate/', data={"from": "*****", "to": "*****"}) self.assertContains(response, 'dummyUrl', status_code=200) self.assertTemplateUsed(response, 'hello/redirecting.html') The model signal will be triggered once the data is inserted into the abc table and celery will pick up the task from the model signal and insert it into redis @receiver(post_save, sender=access_tokens) def access_token_added(sender, instance, created, **kwargs): if created: accessToken.delay(x) I am getting the following error Error 60 connecting to ****:6379. Operation timed out. I need to create the dummy redis to complete this test case. -
How can i run Django with Vue and Webpack Loader using Nginx?
I'm trying to deploy a very simple Django app that uses VueJS with Webpack-Loader using Django-Webpack-Loader. I can run my app in local without any problem using manage.py runserver and npm run serve. Now i'm trying to deploy this simple app to DigitalOcean using Gunicorn and Nginx. The problem is that while i can see the standard templates being rendered by django, my Vue files are not loading and i only get a lot of errors: GET http://URL/static/vue/js/index.js net::ERR_ABORTED 404 (Not Found) The full code of the application is HERE, it's not mine, i'm just running a simple example to get started. Can anyone help me on this? I made sure to build my frontend for production using npm run build and i collected my static files using manage.py collectstatic, but i still get the error. Any kind of advice is appreciated. -
React: sending component as html + css to server?
I want to send react component with styles, as it looks on dev server, to another server (django in my case), and there create a PDF with exact look. So I want to pass identical component (as html with styles?) via POST to server. I've found ReactDOMServer.renderToString and it works, but it cant provide styles. Any solutions? Thanks. -
How to override django-allauth templates in django 3.0.7 and django-allauth 0.43.0
I want to override django-allauth templates. I have done it before in django==3.0.2 and django-allauth==0.41.0. Now I am using django==3.0.7 and django-allauth==0.43.0. Lasttime I configured my settings like that in the code sample. I have tried this it doesn't work. I have also tried other solutions like placing the templates inside another app's templates directory but still no luck. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),os.path.join(BASE_DIR, 'templates', 'allauth')], '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', ], }, }, ] And the templates folder structure is like this. templates allauth account openid socialaccount tests What am I doing wrong here? -
Celery task - cancel previous calls with same parameters (re-calls)
I need to have a celery task which is called every time I change a field on a model. Imagine having a name field on a Book model, and every time it's changed, I need to start a complicated celery task which does some long-running things for the book, like re-ordering it in the library. The thing is, that the name is an input field so a user can type slowly in the name field, and a celery task will be called every letter. The important thing is here that I don't care about previous calls, and I want to execute the task only when it's relevant i.e it's the last call. I thought about throttling or maybe somehow revoking all previous task calls with the same name that takes care of this book, but from what I've seen here, terminating tasks under perfectly normal circumstances isn't something I should be doing. Throttling may also be an option. The solution also has to support both SQS and Redis for local & production environments. Any help would be appreciated, thanks so much in advance! -
Django - why user.is_authenticated asserting true after logout
I am trying to write a test for logging out a user in Django. Here is the code: urls.py from django.conf.urls import url from django.contrib import admin from accounts.views import LoginView, LogoutView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', LoginView.as_view(), name='login'), url(r'^logout/', LogoutView.as_view(), name='logout'), ] views.py from django.http import HttpResponseRedirect from django.contrib.auth import login, logout from django.views.generic import View class LogoutView(View): def get(self, request): logout(request) return HttpResponseRedirect('/') tests.py from django.test import TestCase, Client from django.contrib.auth.models import User class LogoutTest(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user( username='user1', email='user1_123@gmail.com', password='top_secret123' ) def test_user_logs_out(self): self.client.login(email=self.user.email, password=self.user.password) self.assertTrue(self.user.is_authenticated) response = self.client.get('/logout/') self.assertFalse(self.user.is_authenticated) self.assertRedirects(response, '/', 302) The assertion self.assertFalse(self.user.is_authenticated) is failing. Testing through the browser seems to work fine. It seems like the user would not be authenticated after called logout(). Am I missing something? -
DRF displaying default image even if user uploaded an image
I wonder which method in which part of my Django backend I should use to change the representation of the user's profile picture/ the path of the user's profile picture. Because I have an default image '/media/default_l.png' which is used in my model like so: class User(AbstractBaseUser,PermissionsMixin): id = models.AutoField(primary_key=True) # custom User models must have an integer avatar = models.ImageField(upload_to=avatar_upload, blank=True, default='default_l.png', validators=[validators.FileExtensionValidator(['jpg','jpeg', 'gif', 'png',])]) ... This default image is used to display an image as long as the user didn't upload an profile image of his choice. When the user uploads an image, he uploads the image to upload_to=avatar_upload like so: def avatar_upload(instance, filename): #https://c14l.com/blog/django-image-upload-to-dynamic-path.html #return os.path.join('images/user_avatar/', 'user_{0}', '{1}').format(instance.user.id, filename) new_filename = '{}_{}.{}'.format('user',instance.pk, 'png') return "user_avatar/{}".format(new_filename) So the default image is /media/default_l.png and the uploaded image is /media/user_avatar/user_3.png (= user_pk.png) The serializer for uploading an image is # Upload User Profile Picture class AvatarSerializer(serializers.ModelSerializer): avatar = serializers.ImageField(max_length=None, use_url=True) class Meta: model = User fields = ['avatar'] def save(self, *args, **kwargs): if self.instance.avatar: #delete if not default if "/media/default_l.png" not in self.instance.avatar.url: self.instance.avatar.delete() return super().save(*args, **kwargs) The uploading works fine with the view class UserUploadImage(RetrieveUpdateAPIView): #permission_classes = (IsLoggedInUser, ) parser_class = [MultiPartParser, FormParser] serializer_class = AvatarSerializer queryset = User.objects.all() … -
Django Invalid block tag: 'urls' error on loading tag
I'm trying a tutorial to load a ML script into Django. I've completed the tutorial but right now i'm getting an error TemplateSyntaxError at / Invalid block tag on line 9: 'urls'. Did you forget to register or load this tag? HTML <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Home page</title> </head> <body> <h1>Titanic survival prediction</h1> <form action="{% urls 'result' %}"> {% csrf_token %} extra code with form items </form> URLS file in python: from django.contrib import admin from django.urls import path from djangoweek import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('result/', views.result, name='result'), ] I've looked at other questions at stack but I don't got the answer. -
Django how to include URLs from different apps into the same single extended template html using namespace
I have created a 2nd app in my django project and I am trying to create a HTML files that contains links to both the main app and the 2nd app. I am getting this error: Reverse for 'deploy' not found. 'deploy' is not a valid view function or pattern name. My code is: urls.py from django.conf.urls import url from django.contrib import admin from django.urls import path, include from applications.atoll_queue_manager_fe_project.fe import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('create/', views.createtodo, name='createtodo'), # App2 - Deploy Side Branch path('deploy-side-branch/', include('fe2.urls')), ] 2nd app fe2/urls.py from django.urls import path from applications.fe2 import views app_name = 'fe2' urlpatterns = [ path('', views.deploy_side_branch, name='deploy'), ] navbar section in base.html (extended by new.html) <ul class="navbar-nav mr-auto"> <li class="nav-item {{ deploy }}"> <a class="nav-link" href="{% url 'deploy' %}">Deploy</a> </li> <li class="nav-item {{ current }}"> <a class="nav-link" href="{% url 'currenttodos' %}">Current</a> </li> <li class="nav-item {{ completed }}"> <a class="nav-link" href="{% url 'completedtodos' %}">Completed</a> </li> <li class="nav-item {{ create }}"> <a class="nav-link" href="{% url 'createtodo' %}">Create</a> </li> </ul> -
Django keeps saying field is required even if the fields are already provided
My View: code = 111 score = 3 test = models.Test.objects.filter(code__iexact=code)[0] first_name = data['first_name'] last_name = data['last_name'] password = data['password'] form = forms.EntryForm(data=data) if form.is_valid(): form.instance.test = test form.instance.first_name = first_name form.instance.last_name = last_name form.instance.password = password form.instance.score = score form.save(commit=True) Running this however will give me this warning saying test and score fields are required: <ul class="errorlist"><li>test<ul class="errorlist"><li>This field is required.</li></ul></li><li>score<ul class="errorlist"><li>This field is required.</li></ul></li></ul> But as you can see, all the fields are already provided. It doesn't also give an error for first_name, last_name and password so I guess Django have read that one. Here is my Entry model: class Entry(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=200, default=None) score = models.CharField(max_length=100, default=None) def __str__(self): return "Test: {t} | By: {f} {l}".format(t=self.test, f=self.first_name, l=self.last_name) And the form: class EntryForm(forms.ModelForm): class Meta: model = models.Entry fields = '__all__' Any ideas? Thanks a lot! -
Custom pagination in Django is not working properly
I created a pagination in django using a dropdown which lists the pages for the user to select from. When any value is selected a javascript function is called which calls the django backend to fetch the data. The response object from django includes the page number which was selected so that the same page can be kept selected in HTML (since the page reloads to render the template). <div> Pages : <select name="pagination" id="pagination_id" onchange="pageChange()"> {% for i in pages %} <option value={{i}} {% if page_selected == i %} selected="selected" {% endif %}> {{i}} </option> {% endfor %} </select> </div> However, the dropdown selection is always the first item even though the data in HTML table changes. The value in page_selected is appropriate but the dropdown does not select on the correct page. What am I doing wrong ? -
Accepting localized Date input on Django REST framework
I have a form with date field for submitting date in russian, typical input will be like: "1 апреля 2020" Also have a serializer: class CartSerializer(serializers.Serializer): ... delivery_date = serializers.DateTimeField(input_formats=['%d %B %Y',]) At settings.py have: LANGUAGE_CODE = 'ru' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True When sending delivery_date to rest API it returns an error: {"delivery_date":["Datetime has wrong format. Use one of these formats instead: DD [January-December] YYYY."]} Is possible in DRF to accept non-english Date value? -
spacy nlp is taking long time to answer (django backend)
I have django backend and I'm using spacy for text processing Here is a sample of my code nlp = spacy.load('en_core_web_sm') def process_data(jd): # print(jd) print('process_data start', time.time()) #doc = nlp(jd) doc = nlp.pipe([jd]) print('process_data pipe', time.time()) for each in doc: print('process_data inside loop', time.time()) doc = each print('process_data done loop', time.time()) print('process_data nlp', time.time()) Here is the output of the same process_data start 1603023551.9794967 process_data pipe 1603023551.979678 process_data inside loop 1603023564.9438393 process_data done loop 1603023565.172661 process_data nlp 1603023565.2528574 process_data skills 1603023570.6167505 spacy.load occurs when the application is initialised itself... but if you see to get inside the for loop is taking a lot of time (1603023564.9438393 - 1603023551.979678) Could anyone suggest how to make it faster -
creating a bubble chart using chartjs from three lists of data
I am trying to build a bubble chart using chartjs having 3 lists of data I collected. Using below code for html var ctx = document.getElementById('chart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'bubble', // The data for our dataset data: { datasets: [{ label: 'list1-list2-list3', backgroundColor: 'rgb(255, 99, 132)', pointStyle:'circle' borderColor: 'rgb(255, 99, 132)', data: { x: {{list1|safe}}, y: {{list2|safe}}, r: {{list3|safe}} } }] }, // Configuration options go here options: {} }); I have tried converting these lists to array and then using it but no success. I am getting this enter image description here I want to achieve something like this enter image description here. please guide, much appreciated.