Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
request to same server from index.html in app engine
I managed to deploy and serve index.html other related files from Angular after building in prod mode in static files and Django rest framework as backend. Locally I can access records from sqlite3 by appending endpoints to 'http:127.0.0.1:8000' eg http://127.0.0.1:8000/api/v1/questions/. On deployment I changed the root domain to 'http:127.0.0.1:8080' and append endpoints but I get no response from the server. In chrome console I get unknown error. I also tried 'http:localhost:8080' but I can access all records from admin panel in the dataase (postgresql in app engine). What did I miss here? Thanks -
Django-Rest-Framework system to check custom HTTP header (application - token)
I use Django and Django- rest-framework. I have to check a custom http header for a lot of my views. For each view I need to: Check if the http custom header is there (X-APP-TOKEN); Check if this token is correct; Serve the request or return an HTTP error (for example 403); Is there some approach that I can follow? For example something like permissions_class for rest-framework view. I tried to implement a custom permission like this: class IsAuthorizedApplication(BasePermission): def has_permission(self, request, view): app_id = request.META.get(app_settings.APPS_HEADER_AUTHORIZATION_APP_ID) secret_token = request.META.get(app_settings.APPS_HEADER_AUTHORIZATION_APP_TOKEN) if app_id and secret_token: try: selected_app = Application.objects.get(app_uuid=app_id, status=ApplicationStatusType.ACTIVE) // Check secret token return True except Application.DoesNotExist: return False return False But I think that this approach is based to the authentication system of djnago-rest-framework. Infact in case of 'false return' I receive: 401 - {"detail":"Authentication credentials were not provided."} Is there some different approach to check custom http headers like the permission-class or have I to write a base View to check the application-token before to serve the request? -
Django UpdateForm DateInput widget not showing date
I'm using the DateInput widget to provide a datepicker when a date field is input. However on my update form, the form pulls all the data for that recordd, except the date, which shows up as: dd/mm/yyy How do I get the already input date to show" models.py class Project(models.Model): ''' Main Project, serves the default Projects Portal window. ''' published = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) area = models.ForeignKey( Area, related_name="project", on_delete=models.PROTECT ) title = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=64) summary = models.CharField(max_length=256) others = models.CharField(max_length=128, blank=True) staff_trials = models.DateField(null=True, blank=True) deadline = models.DateField() slip = models.BooleanField(default=False) class Meta: ordering = ["-slip", "deadline"] def __str__(self): return self.title forms.py class DateInput(forms.DateInput): input_type = 'date' class ProjectModelForm(forms.ModelForm): """ Form used for creating and editing projects. Authenticated User required to be signed in. """ title = forms.CharField(widget=forms.Textarea) summary = forms.CharField(widget=forms.Textarea) class Meta: model = Project fields = ( 'title', 'summary', 'others', 'staff_trials', 'deadline', 'area', ) widgets = { 'staff_trials': DateInput(), 'deadline': DateInput(), } veiws.py class ProjectEditView(UpdateView): template_name = 'project_portal/project_detail.html' form_class = ProjectModelForm queryset = Project.objects.all() def form_valid(self, form): user = self.request.user form.instance.user = user print(form.cleaned_data) return super().form_valid(form) def get_object(self): slug_ = self.kwargs.get("slug") return get_object_or_404(Project, slug=slug_) -
How to get the data dynamically from database in the django application?
I am newbie to django and I am trying to get this web page to be dynamically render the data from the database to replicate this website https://www.modsy.com/project/furniture can you say how this can be achieved that slide bar itself. -
How to user Schedule Library to run function every minute
When i use Schedule library (library link) to run function every 1 minute. it works fine but my other URL not working. only scheduled function working. #import scheduler library import schedule import time #update every hour global table no of players and totol payouts def updateTotalPayoutsAndTotalPlayers(): try: querysetGlobal = Global.objects.filter().first() querysetUser = Players.objects.filter(is_active=1).count() querysetTotalPayouts = Game.objects.filter(gameStatusId=3).aggregate(Sum('pot')) totalPayouts = querysetTotalPayouts['pot__sum'] # print("total payouts : ",totalPayouts) querysetGlobal.totalPlayers = querysetUser querysetGlobal.totalPayouts = 0 if totalPayouts==None else totalPayouts querysetGlobal.save() # print("completed task......") except Exception as e: print("error updating payouts and no of players : ", e) #update globals table called ever one minute schedule.every(1).minutes.do(updateTotalPayoutsAndTotalPlayers) while True: schedule.run_pending() time.sleep(1) when i removed while other API's working. but my schedule won't run. to run server i used command : python manage.py runserver -
How to arrange data according to their creation time in Django?
I have to order data according to their creation time but views.py def email_template_list(request): # users = User.objects.all() if (request.user.role == 'ADMIN' or request.user.is_superuser): queryset = EmailTemplate.objects.all() else: queryset = EmailTemplate.objects.filter( created_by=request.user) users = User.objects.filter( id__in=queryset.values_list('created_by_id', flat=True)) if request.method == 'POST': if request.POST.get('template_name'): queryset = queryset.filter( title__icontains=request.POST.get('template_name')) if request.POST.get('created_by'): queryset = queryset.filter( created_by=request.POST.get('created_by')) data = {'email_templates': queryset, 'users': users} return render(request, 'marketing/email_template/index.html', data) Can i do it in Django template also?? -
crud operation without using serializers
This is the error: In line 7 and line 9; json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) This is my code: import requests BASE_URL = 'http://127.0.0.1:8000/' ENDPOINT = 'api/' def get_resource(id): resp = requests.get(f"{BASE_URL}{ENDPOINT}{id}/") print(resp.status_code) print(resp.json()) id = input("enter some id:") get_resource(id) -
How to do parallel processing in angular and django
I am new in django and Python. So I am using angular 7 in front-end and django for API's. So I want to achieve parallel processing. Scenario: I have some script name's that I will send to python for execution and python should execute those scripts(script may take different time to execute like some script will take 10 sec and some will take 20 sec). I want all the script should execute simultaneously and once anyone of those will finish it should send response back to angular. So that I don't need to wait for all the script to execute. As I know we can achieve this using sockets. but I want to know the best way of doing this. Note: I don't need any code here, just want some guideline how to achieve this. Thanks -
Django ImageFieldFile set to <ImageFieldFile: null>. How to change it to blank/empty, like other entries in the table?
I have a FileField in a Django Model. Some entries in this FileField are set to <ImageFieldFile: null>. The rest of the Model table are blank or actual images. I need to clean this table so that these erroraneous entries are also changed to blank, as this is not acceptable in my DRF API. -
Having issues generating token for a new user on sign up. TypeError at /api/users/ Token() got an unexpected keyword argument 'users'
During testing on POSTMAN, when I send a POST request to the server, the user gets registered but a token is not generated for the user. views.py authentication_classes = [TokenAuthentication, BasicAuthentication] permission_classes = (IsAuthenticated,) def get(self,request): users = User.objects.all() serializer = UserSerializer(users,many=True) return Response(serializer.data) def post(self,request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): users = serializer.save() if users: token = Token.objects.create(users=users) json = serializer.data json['token'] = token.key return Response(serializer.data, status= status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserSerializer(serializers.ModelSerializer): username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())] ) phone_number = serializers.CharField(min_length=11, required=True, validators=[UniqueValidator(queryset=User.objects.all())]) def create(self, validated_data): user = User.objects.create(username=validated_data['username'],phone_number=validated_data['phone_number']) return user class Meta: model = User fields = ('id', 'username', 'phone_number') -
django filter with two dates
I want to filter data from the database between the two dates that I enter into the HTML form. my Form.html <form action=""method="post"> {% csrf_token %} <input type="date" class="form-control" name="startDate" id="startDate" required><br> <input type="date" class="form-control" name="endDate" id="endDate" required><br> <button style="margin-left:150px;"type="submit" class="btn btn-success" name="date_filter">ok</button> </form> my models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class TimesheetDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="timesheet",null="True") username = models.CharField(max_length = 30) date = models.DateField(max_length = 10) day = models.CharField(max_length = 10) startTime = models.CharField(max_length =10) endTime = models.CharField(max_length =10) breakTime = models.CharField(max_length=3) normalTime = models.CharField(max_length=10) overTime = models.CharField(max_length = 10) holidayTime = models.CharField(max_length = 10) weekType = models.CharField( max_length = 10) attendance = models.CharField( max_length = 10) content = models.TextField( max_length = 300) my views.py def view_timesheet(request): if request.method == "POST": if('startDate' and 'endDate') in request.POST: startDate = request.POST.get('startDate') print(startDate) print (type(startDate)) endDate = request.POST.get('endDate') print(endDate) print (type(endDate)) user_row_count = TimesheetDetails.objects.filter(user=request.user) print(user_row_count) #dateRange = user_row_count.filter(date__range=['startDate','endDate']).count() #print(dateRange) #context = {'dateRange': dateRange} #print(context) return redirect('/total') This is the ouput i am getting right now. output 2019-12-06 2019-12-28 , , ]> but when I uncomment the following line and compare the dates I get the following error. any help will be highly appreciated. ValidationError … -
Django-Rest-Framework CreateAPIView does not show the form
I am trying to view the CreateAPIView. I am referring to the following tutorial. So as you can see in the image below I am able to get a similar page as is expected, but I cant see the form where we enter data. Now, I think it might be because I am not logged in. But I have been trying to login to the django-rest framework, it doesnt work even thought in the django-admin I am logged in. The image of the terminal shows the response I get when I try logging in to django-rest. image of api/booking/create webpage i.e. CreateAPIView image of the terminal response Thanks in advance. -
At present, which version of Django is good for use
Look at the title. Pymysql and mysqlclient -
What is the difference in sending data using json.dumps and by normal python dictionary?
i am using an api to do a post method and i used Requests library to perform the post. data_post = requests.post(url='https://proxy.vox-cpaas.in/api/user', data={'authtoken': '945e5f0f_ssss_408e_pppp_ellll234122', 'projectid': "pid_a44444fae2_454542_41d4_8630_6454545cdafff12", 'username': "username", 'password': "user.username"}) the above data post worked successfully. but data_post = requests.post(url='https://proxy.vox-cpaas.in/api/user', data=json.dumps({'authtoken': '945e5f0f_ssss_408e_pppp_ellll234122', 'projectid': "pid_a44444fae2_454542_41d4_8630_6454545cdafff12", 'username': "username", 'password': "user.username"})) the 2nd code didnt worked for me please someone explain me the difference. -
Django ERROR - The models is used as an intermediate models ... does not have a foreign key to 'Group' or 'Permission'
I started learning Django some days ago and for practice I decided to make a little project. After I did my model, I tried to map it to a relational model in sqlite3 using django.db. But after I run python manage.py makemigrations <app_name> I get the following errors: python manage.py makemigrations main SystemCheckError: System check identified some issues: ERRORS: auth.Group_permissions: (fields.E336) The models is used as an intermediate models by '<django.db.models.fields.related.ManyToManyField: permissions>', but it does not have a foreign key to 'Group' or 'Permission'. auth.User_groups: (fields.E336) The models is used as an intermediate models by '<django.db.models.fields.related.ManyToManyField: groups>', but it does not have a foreign key to 'User' or 'Group'. auth.User_user_permissions: (fields.E336) The models is used as an intermediate models by '<django.db.models.fields.related.ManyToManyField: user_permissions>', but it does not have a foreign key to 'User' or 'Permission'. contenttypes.ContentType: (models.E012) 'unique_together' refers to the nonexistent field 'models'. I'm really confused about what they mean (at least they seem similar). In my model there are actually no ManyToMany relations, and I've never modified any of the classes listed in the error message (User, Group). I don't know if my model's code is related to this. But I am suspicious about how I structured my project; … -
Downloading file using HttpResponse throwing error as "body size is too long" for large files (>5MB)
I am retrieving file from s3 bucket and returning content as a file as shown below: s3 = boto3.resource("s3") object = s3.Object(bucket-name,s3_key) text = object.get()['Body'] response = FileResponse(text) response['Content-Disposition'] = 'attachment;filename=sample.xls' return response But i am getting error as "body size is too long" while returning file. -
Is there a way to set Django admin to use a leaflet widget when selecting related objects with Geometry attributes in Django admin?
Is there a way, when using django-leaflet and the Django admin interface, to have the admin interface use a leaflet widget for a foreign key field to allow you to select a related object by that related object's GIS/geography features? To some extent, I know at least one answer is "yes, you can build it yourself". I first want to find out if I should do that or if there is something like this already. -
Django 3 Static files is not a registered tag library
I have updated Django 2 to Django 3. I am receiving below error. TemplateSyntaxError at /api/ 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log rest_framework static tz -
Django Send Mail function not working on patch request
In my viewset I have a method that as far as I can tell should be sending an email when I make a patch request but for some reason the email is not sending. Method: def patch(self, request, video_id): video = Video.objects.get(pk=request.data['video_id']) serializer = VideoSerializer( data=request.data, instance=video, partial=True) if serializer.is_valid(): serializer.save() send_mail('Subject', 'Message', 'from@email.com', ['to@gmail.com',], fail_silently=False) return Response(serializer.data) Here is the complete viewset: class AllCompletedViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = VideoSerializer def get_queryset(self): queryset = Video.objects.all().filter(Q(completed=True)) return queryset def patch(self, request, video_id): video = Video.objects.get(pk=request.data['video_id']) serializer = VideoSerializer( data=request.data, instance=video, partial=True) if serializer.is_valid(): serializer.save() send_mail('Subject', 'Message', 'from@email.com', ['to@gmail.com',], fail_silently=False) return Response(serializer.data) What am I doing wrong here? -
Deploying a django project with Apache, mod_wsgi
I am trying to deploy a django project but one among mod-wsgi and virtual environment probably seem to be causing an error. Error log: [Fri Dec 27 08:44:02.403611 2019] [wsgi:error] [pid 28373] [remote 192.168.1.104:52718] mod_wsgi (pid=28373): Target WSGI script '/home/ashish/Dev/we$ [Fri Dec 27 08:44:02.403655 2019] [wsgi:error] [pid 28373] [remote 192.168.1.104:52718] mod_wsgi (pid=28373): Exception occurred processing WSGI scri$ [Fri Dec 27 08:44:02.403804 2019] [wsgi:error] [pid 28373] [remote 192.168.1.104:52718] Traceback (most recent call last): [Fri Dec 27 08:44:02.403824 2019] [wsgi:error] [pid 28373] [remote 192.168.1.104:52718] File "/home/ashish/Dev/webDev/blog/blog/wsgi.py", line 12, $ [Fri Dec 27 08:44:02.403828 2019] [wsgi:error] [pid 28373] [remote 192.168.1.104:52718] from django.core.wsgi import get_wsgi_application [Fri Dec 27 08:44:02.403841 2019] [wsgi:error] [pid 28373] [remote 192.168.1.104:52718] ModuleNotFoundError: No module named 'django' apache2.conf WSGIScriptAlias / /home/ashish/Dev/webDev/blog/blog/wsgi.py WSGIDaemonProcess django_process python-path=/home/ashish/Dev/webDev/blog python-home=/home/ashish/.virtualenvs/djangoblog WSGIProcessGroup django_process <Directory /home/ashish/Dev/webDev/blog/assets> Require all granted </Directory> <Directory /home/ashish/Dev/webDev/blog/media> Require all granted </Directory> <Directory /home/ashish/Dev/webDev/blog/blog> <Files wsgi.py> Require all granted </Files> </Directory> I have made the virtual environment using the python3 -m venv command. It(djangoblog) has python3.7 installed. I have made www:data the owner of both /home/ashish/Dev/webDev/blog and /home/ashish/.virtualenvs/djangoblog, also given them permissions 755. Other useful information: OS: Ubuntu 18.04.3 Apache: 2.4.29 mod-wsgi: 4.5.17 Django : 2.2.5 While going through some of the test scripts … -
How does Apache handle a "script src=" that points to a Django url?
Using the Django development webserver, my app runs perfectly. But using Apache2, it chokes on a script tag, returning '404 Not Found'. Script tags that point to static files work fine in both Apache and Django's development server: <script src="{% static 'ideatree/client/scripts/misc.js' %}"></script> {# WORKS!! #} But the tag: <script src='initFirebaseCLIENT/'></script> That is routed by: urls.py re_path(r'^map/initFirebaseCLIENT/$', views.initFirebaseCLIENT), to: views.py def initFirebaseCLIENT(request): try: # EXCEPTION THROWN HERE, line 138 print("HERE", file=sys.stderr) # NEVER GETS HERE filename = 'ideatree/firebaseCredentials/client/initFirebaseCLIENT_DEVELOPMENT.js' fp = open(filename,'r') content = fp.read() fp.close() return HttpResponse(content, content_type="text/javascript") except Exception as err: return HttpResponse(str(err), status=406) ..throws an exception at the try: and the print statement never executes. Here's the traceback: > /var/www/mysite/ideatree/views.py(138)initFirebaseCLIENT() -> try: (Pdb) Internal Server Error: /ideatree/map/initFirebaseCLIENT/ Traceback (most recent call last): response = get_response(request) response = self.process_exception_by_middleware(e, request) return self.__object(*args, **kwargs) File "/var/www/mysite/wsgi/../ideatree/views.py", line 138, try: File "/var/www/mysite/wsgi/../ideatree/views.py", line 138, try: File "/usr/lib/python3.6/bdb.py", line 51, in trace_dispatch return self.dispatch_line(frame) File "/usr/lib/python3.6/bdb.py", line 70, in dispatch_line if self.quitting: raise BdbQuit bdb.BdbQuit To be safe, I a) opened up the file permissions with a chmod 777 to both the directory and file that I'm trying to fetch, and b) added the following to the Apache2 virtualHost config: <Directory /var/www/mysite/ideatree/firebaseCredentials> … -
how to pass parameter to ajax urls (DJANGO)
i want to pass parameter to url path , so it will know what user that i want to change the role , but it always return error NoReverseMatch at /manageuser/ Reverse for 'editrole' with keyword arguments '{'user_name': ''}' not found. 1 pattern(s) tried: ['editroleadmin/(?P[^/]+)$'] here's the html <div class="row mt"> <div class="col-md-12"> <div class="content-panel align-content-center"> <table class="table table-striped table-advance table-hover"> <thead> <tr> <th><i class="fa fa-bullhorn"></i> User</th> <th><i class="fa fa-bookmark"></i> Email</th> <th><i class="fa fa-bookmark"></i> Division</th> <th><i class="fa fa-bookmark"></i> Role</th> <!-- <th><i class=" fa fa-edit"></i> Status</th> --> <th></th> </tr> </thead> <tbody> {% for user in users %} <tr> <td class="user_name"> {{user.name}} </td> <td> {{user.email}} </td> <td> {{user.division}} </td> <td> <select id="userroles" class="roleselect"> <option selected="selected"> {{user.role}} </option> {% if user.role == "Business Analyst" %} <option>Admin</option> <option>Manager</option> <option>Segment Manager</option> {% elif user.role == "Admin" %} <option>Business Analyst</option> <option>Manager</option> <option>Segment Manager</option> {% elif user.role == "Manager" %} <option>Admin</option> <option>Business Analyst</option> <option>Segment Manager</option> {% else %} <option>Admin</option> <option>Manager</option> <option>Business Analyst</option> {% endif %} </select> </div> </td> <td> <button class="btn btn-danger btn-xs"><i class="fa fa-trash-o "></i></button> </td> </tr> {% endfor %} </tbody> </table> here's the script that i use . it always error in the var urls that i put in ajax <script> $(document).ready(function() { $(".roleselect").change(function () … -
Displaying PDF in Django application and need to select a word which is clicked and display the same word in alert box
In my django application, i need to display pdf file and allow to click any word and finally i want to show the meaning of clicked word?. how to do this? thanks in advance. -
Timeout occurs when serving deep learning models with django, gunicorn and Nginx
I was able to serve deep learning models on 4 2080TI GPUs based on django, gunicorn and Nginx. The majority of the latency is around 200ms, but several requests takes over than 2s to finish. It happens occasionally and is hard to reproduce under some specific setting. How to fix this problem? BTW, the QPS is just 1~2, so it's not result from busy GPU/CPU usage. Here is the Nginx log: -
Django query for multiple fields with list values
I have below Django model class Post(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) title = models.CharField(max_length=200,null=True) text = models.TextField() post_url = models.URLField(max_length = 200, blank = True) post_tier = models.ForeignKey(Tiers, on_delete=models.CASCADE, null= True) post_tier_value = models.IntegerField(default=0) slug = models.SlugField(unique=True, blank=True) I have author_list = [author1@gmail.com, author2@gmail.com] and tier_value_list = [2000,3000]. I want to query in the above model for (author = author1@gmail.com and post_tier_value <= 2000) or (author = author2@gmail.com and post_tier_value <= 3000). Can someone help me how to make query for this?