Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Scheduling my crawler with celery not working
Here I want to run my crawler with celery every 1 minute. I write the tasks as below and called the task in the view with delay but I am not getting the result. I run celery -A mysite worker -l info celery , rabbitmq broker , scrapy and django server in different terminals. The CrawlerHomeView redirects to the task list successfully by creating the task object.But the celery is not working It is throwing this error in the celery console ValueError: not enough values to unpack (expected 3, got 0) [2020-06-08 15:36:06,732: INFO/MainProcess] Received task: crawler.tasks.schedule_task[3b537143-caa8-4445-b3d6-c0bc8d301b89] [2020-06-08 15:36:06,735: ERROR/MainProcess] Task handler raised error: ValueError('not enough values to unpack (expected 3, got 0)') Traceback (most recent call last): File "....\venv\lib\site-packages\billiard\pool.py", line 362, in workloop result = (True, prepare_result(fun(*args, **kwargs))) File "....\venv\lib\site-packages\celery\app\trace.py", line 600, in _fast_trace_task tasks, accept, hostname = _loc ValueError: not enough values to unpack (expected 3, got 0) views class CrawlerHomeView(LoginRequiredMixin, View): login_url = 'users:login' def get(self, request, *args, **kwargs): frequency = Task() categories = Category.objects.all() targets = TargetSite.objects.all() keywords = Keyword.objects.all() form = CreateTaskForm() context = { 'targets': targets, 'keywords': keywords, 'frequency': frequency, 'form':form, 'categories': categories, } return render(request, 'index.html', context) def post(self, request, *args, **kwargs): form … -
How to efficiently reverse a QuerySet to iterate and save all objects in Django?
I have two models Book and Chapters with a foreign key relation. I'm trying to INSERT a Chapter in between an already existing chapters QuerySet that is ordered by order field. Example: Say I already have chapters 1 to 10. Now I need to add a new chapter between 1 and 2. So the new chapter should take the place of the current chapter 2 in the database. So all the chapters after 2 and including itself should have an order of order + 1 to make room for the new chapter. I think I am halfway to achieve this, but I am stuck when trying to slice the QuerySet (Negative indexing is not supported.). Documentation reference. My code: models.py class Book(PubDateUpdDateMixin, models.Model): title = models.CharField(max_length=80) slug = models.SlugField(unique=True, blank=True) description = models.CharField(max_length=3000) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='authors') class chapter(PubDateUpdDateMixin, models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='chapters') title = models.CharField(max_length=40) content = models.TextField(max_length=30000) slug = models.SlugField(unique=True, blank=True) order = models.IntegerField(null=True) views.py class ChapterCreate(LoginRequiredMixin, CreateView): login_url = reverse_lazy('login') model = Chapter slug_url_kwarg = 'book_slug' form_class = ChapterForm template_name_suffix = '-create' def get_object(self): return Book.objects.get(slug=self.kwargs['book_slug']) def get_context_data(self, **kwargs): context = super(ChapterCreate, self).get_context_data(**kwargs) context['book'] = Book.objects.get(slug=self.kwargs['book_slug']) return context def form_valid(self, form): book = self.get_object() … -
Retrieving Form data (from an A HTML page) in a python function pointing to a 'B' HTML page
I have an 'A' HTML page (URL: AppName/A) with an A_Form. After submitting the A_form, the user shall go to the 'B' HTML page (URL:AppName/A/B) where other forms should pop up depending on the data of the A_Form submitted earlier. After submitting the A_Form data, i want to get these data in the python parameter function pointing to the 'B' HTML page (URL:AppName/A/B). In, 'A' HTML code, i have directed the data form to the 'B' HTML URL: {% csrf_token %} {{ A_Form.as_p}} <input type="submit" value="Submit"/> </form> In views.py, A HTLM python function code: def Afunction_view(request): AForm = A_Form() if request.method == 'POST': A_form_result = A_Form(request.POST) BForm = B_Form() CForm = C_Form() return render(request, 'AppName/B.html'{'BForm':BForm,'CForm':CForm}) else: AForm = A_Form() return render(request, 'AppName/A.html'{'AForm':AForm}) In views.py, 'B' HTML python function code:: def Bfunction_view(request): BForm = B_Form() CForm = C_Form() if request.method == 'POST': else: BForm = B_Form() CForm = F_Form() return render(request, 'AppName/B.html'{'BForm':BForm,'CForm':CForm}) The problem with this approach is that after the form in the 'A' HTML page is submitted the user is directed to the 'B' HTML page and the B function is exectued with values on the request parameter... so is it more convenient to put all forms in the … -
How Can I split datetime field field django rest frameworks [closed]
I've used datetime field in my dajngo model. but it was throwing invalid datetime error. so i want to split datetime in two field date field and time field with out changing model. some things like this https://gist.github.com/toshism/1571984 It was working perfectly in django template, But i didn't know to accomplish this features in django rest frameworks. -
Django download fiile
I'm quite new to using Django and I am trying to develop a website where the user is able to download a report file, these files are then stored in a folder static/doc/location.txt. I have in management/commands from django.core.management.base import BaseCommand, CommandError import json import os Print the report def service_area_by_region_top_category_count(self, services_in_service_area_by_region, region_name, limit): print('#### ' + region_name + ':') data_folder = "static\\location\\" file_to_open = data_folder + "location.txt" with open(file_to_open, "a") as file_prime: file_prime.write(str('#### ' + region_name + ':')+ '\n') region_queryset = services_in_service_area_by_region[region_name] data_folder = "static\\location\\" file_to_open = data_folder + "location.txt" with open(file_to_open, "a") as file_prime: for category in Category.objects.all().annotate( service_count=Count(Case( When(services__in=region_queryset, then=1), output_field=IntegerField(), )) ).order_by('-service_count')[:limit]: print(" - " + category.name + ": " + str(category.service_count)) file_prime.write(str(" - " + category.name + ": " + str(category.service_count))+ '\n') Everything working well but the file instead to be saved on the path static/doc/location.txt is saved on the root of the site with the name (static\location\location.txt). txt file created -
Running mysql and django inside docker-compose fails. Why is it unable connect to database?
version: "3.0" services: backend: build: ./backend ports: - "3600:8000" depends_on: - mysql redis: image: redis mysql: image: mysql:5.6 environment: - MYSQL_DATABASE=django-app - MYSQL_ROOT_PASSWORD=password This is my docker-compose.yml #!/bin/sh cd src rm *.sqlite3 python manage.py makemigrations python manage.py migrate daphne -b 0.0.0.0 -p 8000 literature.asgi:application This is my docker entrypoint for the backend. But whenever I do docker-compose up. It fails to migrate the database succesfully and I get the error saying "Can't connect to mysql". But if I restart just the django-app container then it works fine. All migrations are finished and django-admin works. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django-app', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'mysql', 'PORT': '3306', } } It works fine if I use SQLite instead. -
Insert comment form on Post detail page. django- blog app
I have trying this from 2-3 days. I want to insert my comment form on post detail page. My form is not showing on that page. I have followed this tutorial for the comment model. I have another app for account which is used for signup purpose. model.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.title def publish(self): self.published_date = timezone.now() self.save() def approved_comments(self): return self.comments.filter(approved_comment=True) class Comment(models.Model): post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(verbose_name ='Username',max_length=200) text = models.TextField(verbose_name ='Comment') email = models.EmailField(default='') created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text view.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': form}) @login_required def comment_approve(request, pk): comment = get_object_or_404(Comment, pk=pk) comment.approve() return redirect('post_detail', pk=comment.post.pk) @login_required def comment_remove(request, pk): comment = get_object_or_404(Comment, pk=pk) comment.delete() return redirect('post_detail', pk=comment.post.pk) urls.py path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'), path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'), path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'), path('post/<int:pk>/', views.post_detail, name='post_detail'), … -
download a dynamic image with content in django
this will be the output of my work as of done as shown in the above image, the picture and the content on the image is **Purely dynamic**. this is what I used to write to make it happen here my question is that, how can we download the image including the content on it. waiting for the best response from the community. pls, help with this issue. -
How to update table with jquery in django?
I have created in my django app a table in which in the last two columns I have insert an edit and delete button. To do that I have created a partial_book_list.html that contains the body of my table with all data. In other words: base <table class="table table-sm" id="myTable" style="width:100%"> <tbody> {% include 'commesse/includes/partial_book_list.html' %} </tbody> partial_book_list.html {% for commessa in commesse %} <tr> <td>{{commessa.codice_commessa}}</td> <button type="button" class="btn btn-warning btn-sm js-update-book" data-url="{% url 'book_update' commessa.id %}"> </button> <button type="button" class="btn btn-danger btn-sm js-delete-book" data-url="{% url 'book_delete' commessa.id %}"> </button> </td> </tr> {% endfor %} After that I have created a modal form with the following jQuery save function: var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#myTable tbody").html(data.html_book_list); $("#modal-book").modal("hide"); } else { $("#modal-book .modal-content").html(data.html_form); } } }); return false; }; data.html_book_listi is given my the following views: def save_book_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True commessa = Informazioni_Generali.objects.all() data['html_book_list'] = render_to_string('commesse/includes/partial_book_list.html', { 'commessa': commessa }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) In other … -
Has anyone tried django-friendship package? Problem following an user
I recently installed this package to my site to add a follower system but is not working. This is my views.py i defined the context 'users' who takes all the site users and exclude current login user and then i defined the context 'following' who takes all the following users. views.py from django.contrib.auth.models import User from friendship.models import Friend, Follow, Block class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name='posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['users'] = User.objects.exclude(id=self.request.user.id) context['following'] = Follow.objects.following(self.request.user) def change_follower(request, operation, pk): follow = User.objects.get(pk=pk) if operation == 'add': Follow.objects.add_follower(request.user, other_user, follow) elif operation == 'remove': Follow.objects.remove_follower(request.user, other_user, follow) return redirect(request.META['HTTP_REFERER']) urls.py from django.urls import path, re_path from .views import PostListView from . import views app_name='blog' urlpatterns = [ re_path(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.change_follower, name='change_follower'), ] The button to follow a user is not working. I have tried this to follow a user and then show the following list but is not working: Html <h2>Users list</h2> {% for user in users %} {% if user in following %} {{ user.username }} <a href="{% url 'blog:change_follower' operation='remove' pk=user.pk %}"><button type="button">Following</button></a> {% elif not user in following %} <a href="{% url 'blog:change_follower' operation='add' pk=user.pk … -
How to serialize user permissions in Django Rest Framework?
I'm building an application with a Django rest backend and a React frontend and working on authorization and authentication. Authentication works well, but I'm a bit stuck when it comes to telling the frontend what the user is authorized to do in terms of add/edit/view/delete for a model. For example, if a user cannot edit a story, I don't want to display the 'Edit Story' button. When working through the Django documents, I consider it easiest to send the user's permissions from Django backend to the React frontend. Therefore I want to serialize the user permissions. This is my View: class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_permissions(request): logged_in_user = request.user return Response(data=logged_in_user.get_all_permissions()) def get_object(self): return self.request.user This is my Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'user_permissions') When i call the UserAPI the field user_permissions is empty. "user": { "id": 35, "username": "HII", "user_permissions": [ ] } I wonder how i can not access the user_permission via my API. I'm happy for any hint and clarification. -
Problem with Periodic tasks in django with Celery
My periodic tasks with celery is not working. I wish to update my database every night depending on the date. here is my ptasks.py file in the application directiory: ''' import datetime import celery from celery.task.schedules import crontab from celery.decorators import periodic_task from django.utils import timezone @periodic_task(run_every=crontab(hour=0, minute=0)) def every_night(): tasks=Task.objects.all() form=TaskForm() if form.deadline<timezone.now() and form.staus=="ONGOING": form.status="PENDING" form.save() ''' I am using ampq in settings.py: ''' CELERY_BROKER_URL = 'amqp://guest:guest@localhost' CELERYBEAT_SCHEDULER='djcelery.schedulers.DatabaseScheduler' ''' Here is my models.py: ''' from django.db import models import datetime import pytz from django.utils import timezone # Create your models here. class Task(models.Model): title=models.CharField(max_length=30) complete=models.BooleanField(default=False) created=models.DateTimeField(default=timezone.now()) comment=models.CharField(max_length=500, default="") Tag1=models.CharField(max_length=10, default="Tag1") deadline=models.DateTimeField(default=timezone.now()) status=models.CharField(max_length=15,default="ONGOING") def __str__(self): return self.title ''' Here is my forms.py: ''' from django import forms from django.forms import ModelForm from .models import * class TaskForm(forms.ModelForm): class Meta: model=Task fields='__all__' ''' -
Django Template Statement
How can I write the underneath statements inside a django template? # input from a form n = int(input()) for i in range n: if i%2 == 0: print('i') elif i == 9: print('biggest number') break -
How can I order a queryset in Django by custom values?
I want to order result of a query (done by .filter) based on a list of values I provide. I have a importance column in my database and the values are none, not important, important, very important. But when I make a query, Django returns whichever row is the first. I want to specify to put "very important" first, "important" second, "not important" third and the last would be none. Curent Query Result 1, word, not important 2, word2, none 3, word3, very important 4, word4, important Query result I want to achieve 3, word3, very important 4, word4, important 1, word, not important 2, word2, none How can I make this order? -
error when writing an app from a tutorial
Good day! I create an application on django based on the tutorial from the official documentation, but I get the following error: Traceback (most recent call last): File "c:\python372\Lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\python372\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\virtualenv\hello\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\virtualenv\hello\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\virtualenv\hello\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\virtualenv\hello\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\virtualenv\hello\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\virtualenv\hello\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\virtualenv\hello\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\virtualenv\hello\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\virtualenv\hello\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\virtualenv\hello\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\virtualenv\hello\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\virtualenv\hello\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\virtualenv\hello\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
Django Rest Framework FormData array in array
must accept object across FormData appropriate: { "name": "name", "description": "description", "skills": [ { "id": 1, "technologies": [ "technology1", "technology2" ] }, { "id": 2 } ] } skills[0]id - sends id. How to send technologies? skills[0]technologies - sends only one skills[0]technologies[0] - does not work -
Django: Using jquery ajax call to run function when a button is clicked
I am trying to run a function without refreshing the page by using the jQuery ajax() Method, but it's not working. I have very limited experience with jQuery and ajax, so would appreciate any help. My template: <a id="button add-word" href="#" class="btn btn-warning btn-sm" >Add</a> My view: def custom_create_word(request, object): if request.method == 'POST': pass if request.method =="GET": from .forms import WordForm from .models import Word word = Word.objects.get(pk=object) user = request.user target_word = word.target_word source_word = word.source_word deck_name = "My Words" fluency = 0 Word.objects.create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:dict')) My url: path("<int:object>/",views.custom_create_word,name="add-custom"), My js: $(document).ready(function(){ $("#add-word").click(function() { $.ajax({ url: '/vocab/add-custom/', success: function (result) { $("#add-word").html(result); }}); }); }); I don't get any errors, but the function isn't run. Everything works when I do it without jquery and ajax (i.e. the function is run but the page is refreshed every time). Any ideas on how to fix this? -
What is the advantage of using a frontend framework like react with django [closed]
Django can render the template and get the data from database to the users. Bootstrap can be used for styling. Then What is the advantage of using a front end framework like react. If react is used with django, can they not work together without django rest api?. I'm new to web development can anybody help me understand these concepts -
Dynamic queryset filtering with multiple query parameters
I have the following view I have implemented to filter transactions depending on a certain query provided. Is there a way I could filter dynamically depending on what query is provided, for example one would want to only query year and month only or even filter using one query. The rest of the query values will end up having a None value an should not be included in the filter. class ReportTransactionsFilterAPIView(APIView): def get(self, request, format=None): year = self.request.GET.get('year') month = self.request.GET.get('month') subcounty = self.request.GET.get('subcounty') ward = self.request.GET.get('ward') fromDate = self.request.GET.get('fromDate') toDate = self.request.GET.get('toDate') qs = LiquorReceiptTrack.objects.all() qs = LiquorReceiptTrack.objects.filter( Q(date_recieved__range=[fromDate,toDate])| Q(date_recieved__year=year)| Q(date_recieved__month=month)| Q(sub_county__iexact=subcounty)| Q(ward__iexact=ward) ) -
Override Class in Widget Attributes in a Django Form
I wrote the code as follows: forms.py class Select(forms.SelectMultiple): template_name = "entity/choices/choices.html" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.attrs = {"class": "no-autoinit"} class Media: css = {"all": ("css/base.min.css", "css/choices.min.css",)} js = ("js/choices.min.js",) class EntityForm(forms.ModelForm): class Meta: model = Entity fields = ["main_tag", "tags"] widgets = { "tags": Select(), } It works but I have a question if I want to override the class in attrs, what should I do? such as class Select(forms.SelectMultiple): template_name = "entity/choices/choices.html" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.attrs = {"class": "no-autoinit"} class Media: css = {"all": ("css/base.min.css", "css/choices.min.css",)} js = ("js/choices.min.js",) class EntityForm(forms.ModelForm): class Meta: model = Entity fields = ["main_tag", "tags"] widgets = { "tags": Select(attrs={"class": "important"}), #I add class important } I want to add other classes to override the no-autoinit classes that I have defined. But if I don't add other classes, the no-autoinit class will work. Please recommend me. Thanks -
Subsequent Carousel Slides draw blank
{% extends 'accounts/main.html' %} {% block content %} <div id="myCarousel" class="carousel slide" data-ride="carousel"> <ul class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> {% for i in range %} <li data-target="#myCarousel" data-slide-to="{{i}}"></li> {% endfor %} </ul> <div class="carousel-inner"> <div class="carousel-item active"> <div class="card-deck"> <div class="card"> <img class="card-img-top" src="{{ post.img.all.0.img }}"> </div> {% for i in post.img.all|slice:"1:" %} <div class="card"> <img class="card-img-top" src="{{ i.img }}"> </div> {% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %} </div><div class="carousel-item"> {% endif %} {% endfor %} </div> </div> <a class="carousel-control-prev" href="#myCarousel" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#myCarousel" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> Carousel-slide ''' I am doing Django website and coding on Bootstrap Carousel slides containing multi items in each slide. The first Active Slide is in order... but clicking next button for subsequent slides draw blank. Glad if someone can help... many thanks ''' class Post(models.Model): title = models.CharField(…) image = models.ManyToManyField(Image) class Image(models.Model): img = models.ImageField(max_length=200) views.py def post_detail(request, id): post=Post.objects.get(id=id) img_count = post.image.count() nslides = img_count//4 + ceil(img_count/4) –(img_count //4) params = {‘no_of_slides’:slide, ‘range”: range(1, nslides), ‘post’:post} return render(request, ‘post_detail.html, params) -
ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'six' from 'django.utils'
Currently I am using Django version 3.0.7 Earlier i was working on 3.0.5 and getting error of : Trying to load rest_framework.templatetags.rest_framework Error: No module named 'django.core.urlresolvers' Then i changed it to "from django.urls import reverse" this error got fixed but below written error generated, so i upgraded Django version to 3.0.7 but still there is same error. C:\Users\Lenovo\Desktop\QuickChat\project>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\backends\django.py", line 120, in get_package_libraries module = import_module(entry[1]) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python38\lib\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 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\templatetags\rest_framework.py", line 8, in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (C:\Users\Lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, … -
<audio> tag not allowing to skip some part of file. bootstrap
I want to play audio in browser and I am using bootstrap 4.0 <audio> tag. But Whenever I click on track to skip some part of audio it starts over. This is the html I am using <audio preload="auto" controls autoplay> <source src="{{MEDIA_URL}}{{currentSong.songFile.url}}"> </audio> Any help would be appreciated. Thanks! -
Dynamic form from JSON in Django and save the data in JSON
The issue I am facing is I want different fields for different networks so users can fill the fields for different Networks on my website. There are 4 Models Custom User Model Network Model (Have Network Information like name, slug) NetworkField Model (Has one column as fields which is a JSONField() which is used for different fields the network can have) NetworkProfile Model (The user profile that is specific for every network and has 3 fields one for network(which network profile), user (the user profile), field_value (JSONField, value for the JSON field in NetworkField model)) The issue I am facing is to create Dynamic Form from JSONField in NetworkField and show the form to user and when filled must save that data into field_value in NetworkProfile. views.py def dform(request, network_slug): current_network = get_object_or_404(Network, network_slug=network_slug) json_form_fields = current_network.field_id.fields form_class = get_form(json_form_fields) data = {} if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): data = form.cleaned_data NetworkProfile.objects.update(network_id=Network.objects.get(network_slug=network_slug), user_id=request.user, fields_value=data) else: form = form_class() context = { 'form': form, 'data': data, } return render(request, "networks/dform.html", context) urls.py path('<slug:network_slug>/profile', views.dform, name='network-profile'), forms.py import django.forms import json from django import forms from django.contrib.auth import get_user_model class FieldHandler(): formfields = {} def __init__(self, fields): for … -
Handling multiple calls to an API django
I'm hosting an API that will be subjected to multiple users to call it at the same time. Each call will take around 10 seconds to return as I will be running some GPU computations and returning the request. 1) How do I test how many GPU cores a require to return X number of requests? 2) I tried calling 2 calls simultaneously and it is able to compute both requests, how do I test how many requests it can handle at one go. Do I need a request manager to queue thee jobs? (currently my machine only has one GPU core) 3) How does API handle multiple requests in general? Thanks for helping!