Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the checked objects immediately in django view with ajax?
I am very new to ajax. Here I have a django form and inside the form there is a form group of checkbox. What I want here is, from the checkbox if the user check some user object I want to get it in the django view immediately before the form submit. And if the the user uncheck this It should be removed from django view also. How can I do this ? After form submit it works fine but I want to get the checked user before the form submits.So I think in this case ajax will be required. But I am very beginner in ajax so I got stuck here. template <div class="form-group"> <div class="checkbox"> <input class="checkbox1" name="users" type="checkbox" value="{{user.pk}}" id="user{{user.pk}}"/> <label for="user{{user.pk}}"></label> </div> </div> jquery <script> $(function(){ var checked_lists = []; $(".checkbox1:checked").each(function() { checked_list.push(this.value); }); }); </script> views print('us',self.request.POST.getlist('checked_lists')) -
Django redirect to specific URL after Registration
Good day. I'm trying to redirect a user to specific url which in my case is rootPath/dashboard/ But when the user registers i get redirected to /user/register/dashboard/ I have searched other stackoverflow topics on same problem but they didn't resolve my problem. I have defined these settings in settings.py LOGIN_URL = 'user/login/' LOGOUT_URL = 'user/logout/' LOGIN_REDIRECT_URL = 'dashboard/' views.py def register(request): form = RegisterForm(request.POST or None) if request.POST: if form.is_valid(): data = form.cleaned_data email = data['email'] pwd = data['password'] user = User(email=email, password=pwd) user.save() return redirect(settings.LOGIN_REDIRECT_URL) return render(request, 'registration/register.html', context={'form': form}) @login_required def dashboard(request): return render(request, 'user/dashboard.html') urls.py urlpatterns = [ path('user/login/', CustomLoginView.as_view(), name='login'), path('user/logout/', auth_logout, name='logout'), path('user/register/', register, name='register'), path('dashboard/', dashboard, name='dashboard') ] register.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container text-center"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <h1 class="h3 mb-3 font-weight-normal">Register</h1> <form class="form-signin" action="." method="post"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Register" class="btn btn-primary"></p> {# <a href="{% … -
Exporting data from mysql workbench into excel
i'm creating a tool using django in which i'm using data from the database.I need an export option from which i can export data from the mysql database into a csv file. can anyone please guide me thorugh it ? -
Resources for learning testing django channels?
I am writing tests for project that uses channels + DRF. I have to test huge user use-case scenarios. I read official docs and searched a lot but it wasn't enough. Can you recommend articles or smth like that? -
MultiValueDictKeyError at /add, Request method : GET
this is my views.py file from django.shortcuts import render def home(request): return render(request, 'home.html',{'name':'irtiza'}) def add(request): val1 = int(request.GET['num1']) val2 = int(request.GET['num2']) res = val1 + val2 return render(request, "result.html",{'result': res}) when i run this code i am getting this error, error then i tried this code: def add(request): val1 = int(request.GET.get(['num1'])) val2 = int(request.GET.get(['num2'])) res = val1 + val2 return render(request, "result.html",{'result': res}) this error occur. enter image description here what should i do now to resolve this error. This is just a simple function to ADD two numbers.Kindly help me. -
Django WSGI cannot be loaded
I am trying to start my first django app with Apache2 (2.4.18). Unfortunately, I got a bit stuck. This is the error code i get in my log file: [Wed Mar 11 06:31:32.668937 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] mod_wsgi (pid=14849): Target WSGI script '/home/nigsdtm/srv/portal/mysite/wsgi.py' cannot be loaded as Python module. [Wed Mar 11 06:31:32.669026 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] mod_wsgi (pid=14849): Exception occurred processing WSGI script '/home/nigsdtm/srv/portal/mysite/wsgi.py'. [Wed Mar 11 06:31:32.669734 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] Traceback (most recent call last): [Wed Mar 11 06:31:32.669779 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] File "/home/nigsdtm/srv/portal/mysite/wsgi.py", line 16, in <module> [Wed Mar 11 06:31:32.669783 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] application = get_wsgi_application() [Wed Mar 11 06:31:32.669789 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Wed Mar 11 06:31:32.669792 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] django.setup(set_prefix=False) [Wed Mar 11 06:31:32.669809 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 24, in setup [Wed Mar 11 06:31:32.669812 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] apps.populate(settings.INSTALLED_APPS) [Wed Mar 11 06:31:32.669817 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 112, in populate [Wed Mar 11 06:31:32.669820 2020] [wsgi:error] [pid … -
how to fetch data from two different models in single api call in django rest frame work? is it possibel if yes then how?
How I can add and fetch two different models in a single API call. urlpatterns = [ path('users/<int:id>/', GenericAPIView.as_view()), path('users/', GenericAPIView.as_view()), ] # User Serializer class userSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' # usersdata serializer class userdataSerializer(serializers.ModelSerializer): class Meta: model = UserData fields = '__all__' this is my views.py this is views.py code. class GenericAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin): serializer_class = userdataSerializer, userSerializer queryset = UserData.objects.all() lookup_field = 'id' def get(self, request, id=None): if id: return self.retrieve(request) else: return self.list(request) def post(self, request): return self.create(request) def put(self, request, id=None): return self.update(request, id) How I can add and fetch two different models in a single API call. How I can add and fetch two different models in a single API call. How I can add and fetch two different models in a single API call. How I can add and fetch two different models in a single API call. How I can add and fetch two different models in a single API call. -
updating multiple rows in django database
I have 5 records in the database and want to update all the values of a particular field called "ret_name". For that, I have written the following code in views: def retap_list(request, date_selected): obj = ret_tbl.objects.filter(curr_date = date_selected) obj[1].update(ret_name = "change") print(obj[1].ret_name) But it is showing me the following AttributeError: "'ret_tbl' object has no attribute 'update'" How should I update each row one at a time? -
how to create filtering by argument inside the model and not through id
need to blow filtering by post field here is my code enter code here class Comment(models.Model): post = models.ForeignKey('AnimalInfo', related_name='comments',on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) class CommentView(viewsets.ViewSet): permission_classes = [IsAuthenticated] serializer_class = CommentSerializer queryset = AnimalInfo.objects.all() def retrieve(self,request,pk=None): user = CommentSerializer(self.queryset) return Response(user.data) class CommentSerializer (serializers.ModelSerializer): class Meta: model =Comment fields='all' thank you in advance -
How request_id is being called at django tutorial 03
I am new to Django. I am learning it from Django's official website (making voting app). I am not stuck process wise but want to understand why in polls/view.py request_id call is working(we have not imported any class then how does it know about this particular id). https://docs.djangoproject.com/en/3.0/intro/tutorial03/#writing-more-views the only packages installed are from django.shortcuts import render from django.http import HttpResponse Please help me understand this logic. Thanks -
How to upload file in Xhtml?
I wish to upload file and perform some task on that file using django upload api, i uploaded a file or more than a file from postman ,that is working properly . i did same process using xhtml file but that is not working . Please help me anyone. index.xhtml <form id="submit_form" action="http://xx.xxx.xx.xxx:xxxx/upload" method="POST"> <label for="ubutton">Upload</label> <input type="file" id="file" name="file" multiple="multiple" /> <label for="utext">Project Name</label> <input id="utext" type="text" name="projectname" placeholder="enter project name"/> <label for="utextarea">Entity Names</label> <input id="utextarea" type="textarea" name="entitynames" placeholder="Enter camma separated values"/> <input type="submit" value="Submit" id="submit" onclick = "return myfunction(this)"/> <span id="error_message" class="text-danger"></span> <span id="success_message" class="text-success"></span> </form> views.py @csrf_exempt def upload(request): if request.method == 'POST': print("Inside post request") projectname = request.POST.get('projectname') entitystr = request.POST.get('entitynames') uploaded_file=request.FILES files=uploaded_file.getlist('file') fs=FileSystemStorage() filepaths=[] for file in files: filename = fs.save(file.name, file) file_path = os.path.abspath("media/"+filename) filepaths.append(file_path) extract_text(filepaths,fs) textfilepath=r'/home/sharmila/test/brat-v1.3_Crunchy_Frog/prediann/text_files'+"/" preprocessing(textfilepath,projectname) write_config(entitystr,projectname) return redirect("http://xx.xxx.xx.xxx:xxxx/index.xhtml#/") I got projectname and entitysrt values from xhtml , but files variable is empty dictionary . How can i upload file ? -
How can I use dropdowns and according to the dropdown I provide further details
I used ng-if using radio buttons for yes or no selection and according to that provided the details but how can I use dropdowns and according to each deopdown selection I show the details like if I select Near Metro from the dropdown and I show the available places and when I select the place again from the dropdown I show the post office pincode -
question about switching from heroku to a public host
my site is in Heroku is what if I launch it in public hosting the images work or it is necessary to open an Amazon account. image and video in the locale they work and all my files are put in a media document in the root I use whitenoise in production -
Django model has several booleanfields and I want to put them into the same checkbox
As title This is my model.py A = models.BooleanField(_('A'), default=True) B = models.BooleanField(_('B'), default=False) C = models.BooleanField(_('C'), default=False) How to put them in the same checkbox by forms.py? thx -
Problem with upload FileField and ImageField in new django 3.0.4
I'm with a big issue about django 3.0.4. I'm using virtualenv with python3.6.9 and django==3.0.4, In my models at upload process the picture be saved in correct folder, but return error 500 on server and the data field (title, category, file_attach) aren't saved in database. If I change django to version==2.2 in virtualenv the picture be stored and save in database without errors. Some bug or hack in django==3.0.4? The project was created in django 3 but work fine in 2.2. Some solution? -
Check if user is in the manager column in order to create a post/task
I'm learning in DJango and I have learned alot of stuff from the documentation and also in StackOverflow. Right now, I'm kinda stuck and I just want to know who can I check in a class based view, if the user is in the manager column in job model/ It can also be in the manager model that's fine too. I tried using UserPassesTestMixinin order to check if user is part of it but I'm getting an error of Generic detail view createjob must be called with either an object pk or a slug in the URLconf. I just need someone to point me to the right direction or give me a hint.I also tried, this: class createjob (LoginRequiredMixin,CreateView): model = Job fields = ['member','title', 'description', 'file'] def form_valid(self,form): form.instance.manager=self.request.user return super().form_valid(form) But it's giving me an error of Cannot assign "<SimpleLazyObject: <User: edlabra>>": "Job.manager" must be a "Manager" instance. Here's my views.py: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView, CreateView from .models import Job, Member from profiles.models import User from django.contrib.auth.decorators import login_required # Create your views here. class jobs(LoginRequiredMixin,ListView): model = Job template_name = 'users/user_jobs.html' context_object_name = 'jobs' def get_queryset(self): return Job.objects.filter(member__member=self.request.user) … -
Override Bootstrap 4 Colors in PyCharm Django Project - Error: Can't find stylesheet to import
I am trying to import Bootstrap 4's bootstrap.scss file as described in Bootstrap's theming documentation. My IDE is PyCharm. My ultimate goal is to override Bootstrap 4's colors by importing bootstrap and overriding certain aspects that I want. The problem is, I can't seem to import bootstrap.scss into my custom.scss file relative to the node_modules directory in my project. Here is the structure of my project: learnsass - learnsass <-- main Django project files (ex: settings.py) - myapp - static - myapp - css - custom.scss <-- file I'm trying to import bootstrap from - custom.css <-- automatically generated from file watcher - custom.css.map <-- automatically generated from file watcher - ... - node_modules - bootstrap - dist - js - scss - bootstrap.scss <-- the bootstrap scss I'm trying to import in custom.scss - ... - jquery - popper.js - static - templates - venv - db.sqlite3 - manage.py - package.json - package-lock.json custom.scss My custom.scss file looks like this. $theme-colors: ( "primary": #cccccc, "danger": #840383, ); @import "~bootstrap/scss/bootstrap"; A terminal with the output message shows "Error: Can't find stylesheet to import." cmd.exe /D /C call C:\Users\Jarad\AppData\Roaming\npm\sass.cmd custom.scss:custom.css Error: Can't find stylesheet to import. ╷ 5 │ @import "~bootstrap/scss/bootstrap"; … -
Use of MinIO in Django rest framework
I am new to Django Rest environment. Now what I want to do is posting multiple images in Minio container using Django rest API s. Can please someone guide me how to achieve that. -
How to keep everything retained in memory while learning Django?
What is the best way to learn Django so that it retains in memory everytime we start to build something? I have tried learning Login and Registration processes and stuffs like these in Django via video lectures but I forget them after some time. I also try to retain the working logic behind it but still I forget those logics after some time. Is this problem caused to every newbie or it's happening with me only? Please help me on how to become pro in this, so that every time I use Django after a break I don't need to watch the whole video lectures!! -
How to execute the content based on dictionary data using if and else condition in django template?
Here the code snippet that working fine if "Triglycerides" is not in value2.test_name but providing me the output content twice (executing both if condition and the other when "Triglycerides" is in value2.test_name). <tr class="info"> <td>1</td> <td>Triglycerides</td> <td> {% for key, value in data.items %} {% for key2,value2 in value.items %} {% if value2.test_name == "Triglycerides" %} <div class="form-group"> <input type="text" class="form-control" name="triglycerides_result" value="{{ value2.results }}"> </div> </td> <td><div class="form-group"> <input type="text" class="form-control" name="triglycerides_uom" value="{{ value2.units }}"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="10.00" name="triglycerides_lr"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="190.00" name="triglycerides_hr"> </div></td> {% endif %} {% endfor %} {% endfor %} <td> <div class="form-group"> <input type="text" class="form-control" name="triglycerides_result" value=""> </div> </td> <td><div class="form-group"> <input type="text" class="form-control" name="triglycerides_uom" value=""> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="10.00" name="triglycerides_lr"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="190.00" name="triglycerides_hr"> </div></td> </tr> I'm sure it's not a proper way to apply conditions to get the data. please let me know how will I make the above code works. Thanks. -
Inline formsets with django viewflow frontend
I can get an inline formset to work fine with django, but when trying to use viewflow and the built-in workflow frontend, I can't seem to get the inline form to work during the workflow. What is the proper way to reference the formset? Since the workflow models inherit from the viewflow.models.Process object, I can't seem to understand how to create the inline related model. Use case: I have a workflow with about 50 various fields and I can run the workflow just fine using the Flow and breaking up the process in logical parts in about 10 steps. However, After the process is started and the first 3 or 4 fields are entered, I want step 2 to be an inline form where various roles are assigned to users for this particular workflow event. I already have a separate table where they are manually assigned to roles and I can have the Flow assign the next task to whomever is assigned to that "steps" role and it works fine, but I want the action of assigning the roles to be part of the actual workflow itself. I suspect I should add the inlineformset as a field of the parent … -
sending the image to server through post request django
I am trying to send an image from python client to django server. But i failed to upload the file. The django code is models.py from django.db import models class File(models.Model): file = models.FileField() def __str__(self): return self.file.name Serializers.py from rest_framework import serializers from .models import File class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = "__all__" urls.py from django.urls import path from .views import * urlpatterns = [ path('', FileUploadView.as_view()) ] views.py class FileUploadView(APIView): parser_class = (FileUploadParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.FILES) print(type(file_serializer)) if file_serializer.is_valid(): print('abc') file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) python client code is import requests as req name = {'name': open('im.jpeg', 'rb')} resp = req.post('http://127.0.0.1:8000/upload', name) print(resp) print(resp.text) the output is {"file":["No file was submitted."]} Kindly help me on this -
crispy error |as_crispy_field got passed an invalid or inexistent field
I want to customize the django Model field according to my needs and submit the data into database. I did all the things accordingly. But after running the app i getting the crispy error. I can't able to find my errors. Please help me friends. Models.py is as follows from django.db import models from datetime import date from configration.models import AddSite, AddDepartment, AddCategory, AddDesignation, Rate # Create your models here. class EmployeeRegistration(models.Model): #Departmental Details EmpId = models.IntegerField(verbose_name='EmpId') Site = models.ForeignKey(AddSite,on_delete=models.CASCADE,max_length=150,verbose_name='Site') Department = models.ForeignKey(AddDepartment,on_delete=models.CASCADE,max_length=150,verbose_name='Department') Category = models.ForeignKey(AddCategory,on_delete=models.CASCADE,max_length=150,verbose_name='Category') Designation = models.ForeignKey(AddDesignation,on_delete=models.CASCADE,max_length=150,verbose_name='Designation') PfAllowance = models.BooleanField(default = True) EsiAllowance = models.BooleanField(default = True) Uan = models.PositiveIntegerField(null = False,verbose_name='Uan') Pf = models.PositiveIntegerField(null = True,verbose_name='Pf') AttendenceAward = models.BooleanField(default = True) AttendenceAllowance = models.BooleanField(default = True) ProfesionalTax = models.BooleanField(default = False) Rate = models.PositiveIntegerField(null = True) # Personal Details Name = models.CharField(max_length=150,verbose_name='Name') Father = models.CharField(max_length=150,verbose_name='Father') Dob = models.DateField() Gender = models.BooleanField(default = True) #Female = models.BooleanField(default = False) MaritalStatus = models.BooleanField(default = True) Address = models.CharField(max_length=200,verbose_name='Address') Aadhar = models.PositiveIntegerField(null=True) pan = models.CharField(max_length=10) choices = [('Working','WORKING'),('NotWorking','NOT WORKING')] Status = models.CharField(choices=choices,blank = False,max_length=10,verbose_name='Status') Doj = models.DateField(default = date.today) Doe = models.DateField(blank = True,verbose_name = 'Doe',null = True) def __str__(self): return '{name}'.format(name=self.Name) views.py is as follows from django.shortcuts import render … -
How to create a weekly summary of dated records in model django
I have a model that has entries for each day. I want to create a queryset with a subtotals (annotates) for a selection of fields in the model. This is what i have so far. Here is the model (or some of it!) class Shiftlog(models.Model): date = models.DateField(default=timezone.now) onlinetime = models.DurationField() trips = models.IntegerField(default=0) km = models.IntegerField(default=0) def weekcom(self): weekcom = self.date - timedelta(days=self.date.weekday()) return weekcom Here is the view code that represents what I am trying to achieve. report = Shiftlog.objects.values('weekcom').annotate(Sum('km')) Now this does not work. I see from other posts that the annotate functionality only works with model fields. I appreciate I can create a dictionary of weekcom (weekcommencing rows) and iterate through the model to populate some k,v buckets for each row (weekcom). However, this does not feel right. I also appreciate that this can be done in SQL directly (I have not gone to this option yet so i don't have the code), but I am trying to avoid this option too. Any guidance, much appreciated. Thanks! -
Django ORM: Filtering by array contains OuterRef within a subquery yields zero results
Here's an isolated ORM query: Purpose.objects.annotate( conversation_count=SubqueryCount( Conversation.objects.filter(goal_slugs__contains=[OuterRef("slug")]).values("id") ) ) Where SubqueryCount is: from django.db.models import IntegerField from django.db.models.expressions import Subquery class SubqueryCount(Subquery): template = "(SELECT count(*) FROM (%(subquery)s) _count)" output_field = IntegerField() When that query is run, the following sql is used (via djdt explain): SELECT "taxonomy_purpose"."id", "taxonomy_purpose"."slug", ( SELECT count(*) FROM ( SELECT U0."id" FROM "conversations_conversation" U0 WHERE U0."goal_slugs" @> ARRAY['ResolvedOuterRef(slug)']::varchar(100)[] ) _count ) AS "conversation_count" FROM "taxonomy_purpose" Note the ResolvedOuterRef(slug) injected into the ARRAY lookup as a string. Am I doing something wrong, or should I report this as a bug? If this is a bug, is there a known workaround (maybe creating a custom OuterRef class)?