Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
SQL query is working directly but not when called from Python (django)
from django.db import connections with connections['DB'].cursor() as cursor: select_query = "select * from <table_name> where <condition_row> like '<PRODUCT_NAME>%' and creation_date like '" + today_date + "%';" cursor.execute(select_query) today_date = (datetime.date.today() - datetime.timedelta(1)).strftime("%d-%m-%y") The select query when executed directly from SQL developer gives output . But when called from the above script is giving null output . -
How to write a Query for getting a stock statement in django
I am just learning django for past few weeks.I wanna know how to write stock statement query in django? for example A=incoming products B= outgoing products stock = A-B I been creating a app for my warehouse business struck in here need help ! enter image description here so the image shows the models of the app ..what i want to accomplish is to add a query to views that brings stock statement -
Is it okay to use Postman to Profile Response Time of Django Endpoints?
I have been searching for ways to profile Django endpoints using Postman but I did not see any post about it. Is it okay to use Postman to Profile Response Time of Django Endpoints? (Currently, I have been profiling it by running the request five times then doing the average. Is this a good idea?) -
How to I automatically filter out is_deleted records in an associated table in Django?
I am using soft deletes on one of my models in Django, and I am overwriting the default manager to always return active records only, using something like: class ActiveRecordManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_deleted=False) class Tag(models.Model): is_deleted = models.BooleanField(default=False, db_index=True) objects = ActiveRecordManager() class Photo(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE, related_name="photos") objects = ActiveRecordManager() All works well. However, when I do: tag = Tag.objects.get(pk=100) And then I try to get the associated photos: photos = tag.photos.all() Then I get photos that are deleted. I only want to return objects that are not deleted (so my regular objects list. I was reading about _base_mangers in Django, which seems to control this, but the documentation recommends against filtering objects out: If you override the get_queryset() method and filter out any rows, Django will return incorrect results. Don’t do that. A manager that filters results in get_queryset() is not appropriate for use as a base manager. But what I am not clear about is how I am supposed to filter these results. Any thoughts? -
Has anyone tried django-friendship package? [closed]
I recently installed this package to my site to add a follower system but is not working or i miss to add something. The button to follow a user is not working. I have tried this to follow a user and then show my following list but is not working: 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'), ] Html <article class="featured-user"> <div class="row row-st-user"> {% for user in users %} <div class="col-auto user-col-feautered"> <div class="follow-user-span"><span>&nbsp;<img class="featured-user-img" src="{{ user.profile.image.url }}"><span class="user-feauter-st">{{ user.username }}</span></span> </div> {% if user in following %} <div class="div-user-follow"><a href="{% url 'blog:change_follower' operation='remove' pk=user.pk %}"><button class="btn btn-success btn-sm following-button-st-user" type="button">FOLLOWING</button></a></div> {% elif not user in following %} <div class="div-user-follow"><a href="{% url 'blog:change_follower' operation='add' pk=user.pk %}"><button class="btn btn-success btn-sm follow-button-st-user" type="button">FOLLOW</button></a></div> {% endif … -
django.db.utils.DataError: value too long for type character varying(10)
I am using Array Field in my django app but when I try to enter a value (for e.g. Andaman and Nicobar Island) in it it throws the following error: django.db.utils.DataError: value too long for type character varying(10) Here's my models.py states_dealtin = ArrayField( models.CharField(max_length=255, blank=True) ) The length is not exceeding 255 characters the why is it showing the error? -
Django database (Postgresql) sync for offline android
I have already have online website that converted to android app, i just want to know if it is possible to if the users(offline android) can add and update their local database. and when that users back to online what he has been add or update on their local database is synchronized back to the online server. django postgres android studio -
Django and Data Processing
I have a csv file uploaded to Django WebServer via POST method in Form on my page. This data are going to be converted to DataFrame, compared with some other data taken from DB Server and returned to the user as downloadable csv file. This All happens on my WebServer and it makes processor very busy for some time - I can't image what happens, when more users make same processing at the same time. I would like to distribute processing to the more cpu cores or if possible to more servers. I don't know why, but Django with Apache doing this processing on one core and is not willing to use more. Is there a way to multi-process this stuffs? Or even distribute to more servers to processing? I'm considering to use PySpark but I'm not sure if it is a good way to do it... (I have never used PySpark before) -
Django rest framework prefetch_related and select_related doesn't work
I'm try to decrease query counts for using prefetch_related and select_related. However, it seems doesn't work I can't find where I'm doing wrong. Models.py class Tournament(models.Model): name = models.TextField(blank=False, null=False) ... game = models.ForeignKey(Game, on_delete=models.SET_NULL, null=True) class Match(models.Model): name = models.TextField(blank=False, null=False) game = models.ForeignKey(Game, on_delete=models.SET_NULL, null=True) tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True, blank=True) .... serializers.py class TournamentSerializer(serializers.ModelSerializer): game = GameSerializer(many=False, read_only=True) ... match_name = TournamentMatchSerializer(many=True, source='match_set') class Meta: model = Tournament fields = '__all__' class TournamentMatchSerializer(serializers.ModelSerializer): class Meta: model = Match fields=['name'] views.py class TournamentDetailAPIView(RetrieveAPIView): queryset = Tournament.objects.all().prefetch_related(Prefetch('Match',queryset=Match.objects.select_related('tournament'))) serializer_class = TournamentSerializer -
Django/Python - Not able to display result in line by line and with filename
urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('VRFFILELIST/',views.sindex,name="Home-Page"), ] forms.py: ========== from django import forms class stringform(forms.Form): Enter_VRF_Name_To_Search = forms.CharField(max_length=20) views.py =========== from django.shortcuts import render from .forms import stringform import os def sindex(request): search_path = "C:/AUTOMATE/STRING/TESTFILE/" file_type = ".txt" Sstringform = stringform() Scontext = {'Sstringform' : Sstringform} if request.method == 'POST': SVRFTEXT = Scontext['Enter_VRF_Name_To_Search'] = request.POST['Enter_VRF_Name_To_Search'] #fname1 = [] ftext = [] Scontext['resultlist'] = ftext for fname in os.listdir(path=search_path): fo = open(search_path + fname) fread = fo.readline() line_no = 1 while fread != '': fread = fo.readline() if SVRFTEXT in fread: ftext.append(fread) line_no +=1 fo.close() return render(request, 'demoapp/VRFFILELIST.html', Scontext) VRFFILELIST.HTML =================== <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>VRF FILE LIST</title> </head> <body> <form method="POST"> {% csrf_token %} <table> {{Sstringform.as_table}} </table> <button type="submit">Send Command</button> </form> <table> <h3>VRF IN LIST OF FILES</h3> <textarea rows="20" cols="80" name="conf" form="conf" id="conf">{{resultlist}}</textarea> </table> </body> </body> </html> Output: [' ip vrf forwarding TEST:VRFA\n', ' ip vrf forwarding TEST:VRFA\n', ' address-family ipv4 vrf TEST:VRFA\n', ' neighbor 10.10.10.1 route-map TEST:VRFA-IN in\n', ' neighbor 10.10.10.1 route-map TEST:VRFA-OUT out\n', ' ip vrf forwarding TEST:VRFA\n', ' neighbor 192.168.10.2 route-map TEST:VRFA-IN in\n', ' neighbor 192.168.10.2 route-map TEST:VRFA-OUT out\n'] Required Output: TEST-FILE-A: ip … -
How do i deny access to admin page in Django 3.0?
I want it so that when a non staff/non admin/non superuser tries to access the django admin page, it raises a 404 error and when a user is staff/admin/superuser it directs to the login for the admin page. def nonstaffuser(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_superuser: return view_func(request, *args, **kwargs) else: raise Http404 return wrapper_func This is the decorator I made. urlpatterns = [ path('admin/', nonstaffuser(admin.site.urls)) ] I imported the decorator and it does raise a 404 when a user isn't staff but when a user is actually a staff/admin/superuser it raises a error: 'tuple' object is not callable. How do I fix this? Thank You -
when i input right information to login, it always return fail in django
I'm doing my project. Make my own model, and signup and signin. I successed signup. but when i signin, it always fail. what is wrong with my code? model.py from django.contrib.auth.models import(BaseUserManager, AbstractBaseUser, PermissionsMixin) from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, username, userid, company, companycode, password=None): if not username: raise ValueError(_('Users must have an name!')) user = self.model( username=username, userid = userid, company= company, companycode = companycode, ) user.save() return user def create_superuser(self, username, userid, company, companycode, password): user = self.create_user( username=username, userid = userid, company = company, companycode = companycode, password=password, ) user.set_password(password) user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=10, unique=True, verbose_name="이름") userid = models.CharField(max_length=100, unique=True, verbose_name="아이디") company = models.CharField(max_length=10, verbose_name="회사") companycode = models.CharField(max_length=100, verbose_name="회사코드") created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜") is_admin = models.BooleanField(default=False) #is_active = models.BooleanField(default=True) class Meta: db_table = 'user' objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['userid', 'company', 'companycode'] def __str__(self): return self.username def get_full_name(self): return self.username def get_short_name(self): return self.username @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All superusers are staff return self.is_superuser get_full_name.short_description = _('Full name') views.py from django.contrib.auth.models …