Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to programatically delete a group in django
I created a group in django using from django.contrib.auth.models import Group g1 = Group.objects.create(name='Name of the group') now I need syntax to delete the group -
SocketIO client not able to receive events
I've two services: Resource Manager(RM) & Training. RM is a websocket server while Training is the websocket client. I am using python-socketio for both client & server side. I get an HTTP request on RM based on which I've to trigger an event to Training service. I've written a python script for Training Service which accepts socket connections, does some computation and then triggers an event back to RM. This is the code for the Training service: import socketio client_socket = socketio.Client() @client_socket.event def connect(): print('connection established') client_socket.emit('register', 'training') @client_socket.on('train') def start(input_dict): print("Training triggered!") #do some computation client_socket.emit('training_completed', { 'status': False}) client_socket.connect('http://localhost:8000') client_socket.wait() RM is a django application which stores the socket id of the Training service and triggers the event: def start_training(request): # fetch socket id of training service sid = servicename_to_socketid_map.get('training', None) socket_server.emit('train', {'data': training_inp}, room=sid) return JsonResponse({ 'status': 1, 'msg': 'Training started!!' }) I am able to connect to Training service but I try to send an event particularly to Training, I am not able to receive that event. Can you tell me what am I doing incorrectly? P.S. : I've made the required chances to wsgi.py file for using python-socketio with django Thanks -
django allauth custom login with additional check apart from email and password
Here is my Custom login form from Allauth class CustomLoginForm(LoginForm): def __init__(self,*args,**kwargs): super(CustomLoginForm,self).__init__(*args,**kwargs) self.fields['login'].widget.attrs['class'] = 'form-control' self.fields['password'].widget.attrs['class'] = 'form-control' def login(self, *args, **kwargs): return super(CustomLoginForm, self).login(*args, **kwargs) The above works well when I use only Email and Password, and I would like to check another option, for example custom_field is true I saw this reference, https://django-allauth.readthedocs.io/en/latest/forms.html#login-allauth-account-forms-loginform and it says add your processing, but I struck with how to do it.. Any ideas? -
fabric3 : Intempestive Login for password when trying to run fab command
I am following the Obey the testing goat book and I try to automate some shell command server side using Fabric3 I have an issue concerning thefab deploy:host=yyy@xxx yyy being username xxx being folder name of my domain name Whenever I run this command, I get Login password for 'xxx': and it just never seem to work even though I enter the correct one Here is what I did so far: 1- did ssh-keygen locally and on the server 2- added on local side a file named authorized_keys which contains id_rsa.pub generated on server side 3- did the same operation on server side Basically, both sides have a file named authorized_keys Local side (resp. server side) have authorized_keys which is just a copy of id_rsa.pub generated by the ssh-keygen command on server side (resp. local side) Could anyone review what I did so far and tell me if I DID understand the problem (or not), and what should I do to resolve this issue Thank vm -
Django 2 Sendmail with gmail
I checked Django app in Ubuntu 18.04 without ufw When added to settings.py these: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' Run in the console python manage.py shell >>> from django.core.mail import send_mail >>> send_mail('ddd','fffffffffff', 'myemail@gmail.com',['test@gmail.com'],fail_silently=False) After 7 minutes I get this error. Less secure apps & your Google Account ON. Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/mikhail/Django/Chapter01/mysite/env/lib/python3.7/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/home/mikhail/Django/Chapter01/mysite/env/lib/python3.7/site-packages/django/core/mail/message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/mikhail/Django/Chapter01/mysite/env/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/home/mikhail/Django/Chapter01/mysite/env/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 63, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.7/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.7/smtplib.py", line 338, in connect (code, msg) = self.getreply() File "/usr/lib/python3.7/smtplib.py", line 394, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed What am I doing wrong? -
Unable to install django-import-export on Ubuntu 18.04
When I try to pip install django-import-export, I get this error: No metadata found in /home/ubuntu/Desktop/dev/venv/lib/python3.6/site-packages ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/home/ubuntu/Desktop/dev/venv/lib/python3.6/site-packages/sqlparse-0.3.0.dist-info/METADATA' Thank you for any help -
Iterate over a list in database cell in django template
The list is not in a view when multiple options are selected in CheckBoxSelectMultiple its creates a list in database cell like below //$("input[name='hobbies'][value='[&#39;Singing&#39;, &#39;Dance&#39;, &#39;Karate&#39;, &#39;Gym and Exercise&#39;, &#39;Gaming&#39;]']").prop("checked",true); the list looks like [&#39;Singing&#39;, &#39;Dance&#39;, &#39;Karate&#39;, &#39;Gym and Exercise&#39;, &#39;Gaming&#39;] I want to iterate over each element in this list and populate the respective value in edit form. Surfed around net for hours but didn't find any solution for it -
Deployment of Django Channels App in Google Cloud Platform
I am working on my first django channels app and I want to deploy my django channel app in GCP,its working fine in local server,but when I deployed it on GCP,it gives me errors: WebSocket connection to 'wss://sockets-263709.appspot.com/ws/chat/user2/' failed: Error during WebSocket handshake: Unexpected response code: 400 I have researched but can't figure out how to setup it,here's my below code: Entry point: from Frames.wsgi import application app = application wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Frames.settings') application = get_wsgi_application() Asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Frames.settings') django.setup() application = get_default_application() settings.py: WSGI_APPLICATION = 'Frames.wsgi.application' ASGI_APPLICATION = "Frames.routing.application" CHANNEL_LAYERS={ "default":{ "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("sockets-263709.appspot.com", 6379)], }, }, } client side: var wsStart='ws://'; // check if it is secured then assign wss:// if (loc.protocol==='https:'){ wsStart="wss://" } var chatSocket = new WebSocket(wsStart +window.location.host + '/ws/chat/' + roomName + '/'); Requirements.txt absl-py==0.8.1 aioredis==1.3.1 asgiref==3.2.3 astor==0.8.1 async-timeout==3.0.1 attrs==19.3.0 autobahn==19.11.1 Automat==0.8.0 certifi==2019.11.28 cffi==1.13.2 channels==2.3.1 channels-redis==2.4.1 chardet==3.0.4 constantly==15.1.0 daphne==2.4.0 Django==3.0.1 djangochannelsrestframework==0.0.3 djangorestframework==3.11.0 gast==0.3.2 google-pasta==0.1.8 grpcio==1.25.0 h5py==2.10.0 hiredis==1.0.1 hyperlink==19.0.0 idna==2.8 incremental==17.5.0 Markdown==3.1.1 msgpack==0.6.2 mysqlclient==1.4.6 protobuf==3.11.1 pyasn1==0.4.8 pyasn1-modules==0.2.7 pycparser==2.19 PyHamcrest==1.9.0 PyMySQL==0.9.3 pyOpenSSL==19.1.0 pytz==2019.3 PyYAML==5.2 requests==2.22.0 scipy==1.3.3 service-identity==18.1.0 six==1.13.0 sqlparse==0.3.0 termcolor==1.1.0 tqdm==4.40.2 Twisted==19.10.0 txaio==18.8.1 urllib3==1.25.7 I have a start point from … -
Jquery mobile table column toggle not working
I have tried to implement column toggle from jquery-mobile.js . I referred code from w3school. when i am integrating this to django, column toggle is not coming. Code not was working when i serve jquery, jquery-mobile files locally. If i provide external link its working. jQuery v3.3.1 , jquery.mobile-1.4.5 <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Project</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'bfslite/css/jquery.mobile-1.4.5.min.css' %}"> <script src="{% static 'bfslite/js/jquery.min.js"></script> <script src="{% static 'bfslite/js/jquery.mobile-1.4.5.min.js' %}"></script> <script src="{% static 'bfslite/js/sorttable.js' %}"></script> <script src="{% static 'bfslite/js/bootstrap.min.js' %}"></script> <script src="{% static 'bfslite/js/popper.min.js' %}"></script> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'bfslite/css/main.css' %}" /> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'bfslite/css/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'bfslite/chosen/docsupport/style.css' %}"> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'bfslite/chosen/docsupport/prism.css' %}"> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'bfslite/chosen/chosen.css' %}"> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'bfslite/css/jquery-ui.css' %}"> <script src="{% static 'bfslite/js/jquery-ui.js' %}"></script> </head> <body> <div class="container-fluid table-responsive"> <table class="sortable table table-striped table-hover table-sm" data-role="table" data-mode="columntoggle" id="my-table"> <thead> <tr> <th>Project Code</th> <th>Project Name</th> <th>Date Created</th> <th data-priority="1">Type</th> <th data-priority="2">Internal Status</th> <th data-priority="3">External Status</th> </tr> </thead> <tbody> {% for entry in entry %} <tr class="content"> <td>{{ entry.bfs_project_code }}</td> <td>{{ entry.bfs_project_name }}</td> <td>{{ entry.bfs_project_created_date }}</td> <td>{{ entry.bfs_project_type }}</td> … -
django static files with a different path
I'm trying to make the local development work with everything under a /abc. For example, instead of http://localhost:8080 I everything to be at something like http://localhost:8080/abcd I was able to achieve this by updating the url.py with the following: urlpatterns = patterns('', url(r'^abcd/admin/', include(admin.site.urls), name='admin'), url(r'^abcd/search/?$', views.search, name='search'), url(r'^abcd/$', views.index, name='root') ) # Force Django to serve static assets, if this is not the production if settings.PRODUCTION is False: urlpatterns += patterns('', ( r'^abcd/static/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.STATIC_ROOT } )) Now I can view the pages with http://localhost:8080/abcd but the rendering does not show up correctly because of the static files. I need the static files to be served at http://localhost:8080/abcd/static/. Is there a simple way to make it work? I tried doing the above and it doesn't seem to work. I'm super new to django so I don't fully understand how I can achieve what I'm trying to do. Any help from experts would be much appreciated. -
Push Notification with Django and FCM
get a issue, sending message shows that every thing went well but the receiver din't get the notification. from push_notifications.gcm import send_message # target is the user and device_id is the token received from the mobile send_message( target.device_id, {'Message': [f'User {request.user} send a friend request']}, 'FCM', ) # response {'multicast_id': 8075165042107727***, 'success': 1, 'failure': 0, 'canonical_ids': 0, 'results': [{'message_id': '0:1577698440016169%6afcf2daf9f***'}]} response with success but mobile din't get the message but if I send a bulk notification receivers get's their messages for ids in device_ids: send_bulk_message(ids.device_id, {'message': f'You where invited to {instance.name}'}, 'FCM') Any idea? -
Django Internationalization issue
I have a application in django 2.2 to translate just as below: LANGUAGES = ( ('pt', _('Portuguese')), ('en', _('English')), ('es', _('Spanish')), ) LANGUAGE_CODE = 'en' The translation itself is working on the templates and for the default language (LANGUAGE_CODE). The issue lies on the translation triggering. Since this is for a REST_API, I will not be using cookies or sessions, the translation needs to watch the Accept-Language header. Debuggins the Locale middleware, I can confirm that the correct language is being found, but the translated text are returned always for the default language (LANGUAGE_CODE), ignoring the language found by the middleware. If I replace the LANGUAGE_COD for pt or es, it works just fine. The django docs states that LANGUAGE_CODE was supposed to be the last fallback. Any hints? -
How to implement django tabular permission in custom admin panel
I'm creating web app using django. I want to implement django-tabular permission in custom user admin panel. I work fine in default django admin panel. My main goal is to implement permission in tabular form. forms.py from django.contrib.auth.models import Group class GroupForm(forms.ModelForm): class Meta: model = Group fields = '__all__' views.py class GroupCreateView(CreateView): form_class = GroupForm template_name = 'group_create.html' context_object_name = 'create_group' success_url = reverse_lazy('groups:group_list') urls.py from django.urls import path from .views import GroupCreateView, app_name = 'groups' urlpatterns = [ path('create/', GroupCreateView.as_view(), name='create_group'), ] create_group.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {% block body_content %} <div class="row"> <div class="col-12 m-2"> <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary">Create Group</button> </form> </div> </div> {% endblock body_content %} Is this approach is good, if then how can i implement django-tabular permission in custom admin panel or do i need to perform somethings else. Any suggestion would be appreciated. -
How do you execute a makefile to recompile django oscar assets?
I have a django oscar platform that I have amended. The amendments haven't been implemented yet and I think this is because assets need to be recompiled. I think to recompile the platform I need to execute this makefile How do I do this? -
reference error: module is not defined while running unit tests in django-jasmine
I am trying to run a jasmine unit test for my AngularJS function and getting an error which says 'module not defined'. I have tried changing the module to angular.mock.module and now it says 'angular not defined'. I am not able to figure out where exactly to make the change. the angularjs file to be tested var app = angular.module('postserviceApp', []); app.controller('postserviceCtrl', function ($scope, $http) { $scope.TimedRefresh = function(t) { setTimeout("location.reload(true);", t*60); return 'ok'; }; }); The jasmine Spec file describe('post service Ctrl', function() { beforeEach(module('postserviceApp')); var $controller, $rootScope; beforeEach( inject( function(_$controller_, _$rootScope_) { $controller = _$controller_; $rootScope = _$rootScope_; })); describe('$scope.refresh', function() { it('should return OK', function() { var $scope = $rootScope.$new(); var controller = $controller('postserviceCtrl', { $scope: $scope }); expect($scope.TimedRefresh(10)).toEqual('ok'); }); }); }); The error Screenshot of the error Any help will be appriciated -
fields not showing drf django
i am trying to register user from drf and create profile: models.py: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('user must have email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) if password: user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): USER_TYPE_CHOICES = ( (1, 'Freelance Photographer'), (2, 'photographer'), (3, 'client'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, null=True) email = models.EmailField(max_length = 100, unique = True) First_Name = models.CharField(max_length = 100, null = True, blank = True) Last_Name = models.CharField(max_length = 100, null = True, blank = True) is_client = models.BooleanField(default=False) is_photographer = models.BooleanField(default=False) is_staff = models.BooleanField(default = False) is_superuser = models.BooleanField(default = False) is_active = models.BooleanField(default = True) last_login = models.DateTimeField(null = True, blank = True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = "email" EMAIL_FIELD = "email" REQUIRED_FIELD = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class UserProfile(models.Model): user = models.OneToOneField(CustomUser,related_name='profile', on_delete=models.CASCADE, null=True) Image = models.ImageField(upload_to='profile',default='profile/demo.jpg') Mobile_Number = models.CharField(max_length=20, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) serializers.py: class UserProfileSerializer(serializers.ModelSerializer): class … -
How to separate data based in some id in jquery data-tables
Here I have two cities (Delhi and Mumbai), and I want to separate data based in city id on the data table. When I will click on Delhi it should render the Delhi data... I have Django models where the data will fetch by the table Could you please suggest some solutions? <section class="content"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <ul class="nav nav-tabs"> <li><a href="1">Delhi</a></li> <li><a href="2">Mumbai</a></li> </ul> </div> <div class="box-body"> <div class="pull-left"> <div class="pull-right"> <a href="/fleet/driver/{{city_id}}/add" class="btn btn-sm btn-primary"><span class="glyphicon glyphicon-plus-sign"></span> Add Driver</a> </div> </div><br><br> <table id="drivers" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Employee ID</th> <th>Employer</th> <th>Name</th> <th>Mobile</th> <th>City</th> <th>Edit</th> </tr> </thead> </table> </div> </div> </div> </section> <script> $(document).ready(function () { var table = $('#drivers').DataTable({ "pageLength": 100, "serverSide": true, "ajax": "/fleet/dt/drivers/?format=datatables&city_id={{city_id}}", "columns": [ {"data": "employee_id"}, {"data": "employer.name"}, {"data": "name"}, {"data": "mobile"}, {"data": "city.name"}, {"data": "driver.id", "bSortable": false, "mRender": function(data, type, full) {return '<a class="btn btn-info btn-sm" href="/fleet/driver/{{city_id}}/edit/{{ driver.id }}">' + 'Edit' + '</a>';} }] }); }); Thank you. -
how to send argument variable in python script when I call that script from inside another script
In case of django project we start the server from the terminal with command python manage.py runserver. Here we actually run the manage.py script and give an argument variable named runserver. If I want to run the server via any script then I have to call the manage.py script with argumen variable runserver. How to pass this argv from inside the script ? -
Absolutely positioned element not rendering correctly in child template
I have a form on my listing page (parent template) that consists of a text input field and a submit button. It happens to be styled with a CSS property of position: absolute. When I request the listing page of the app, the form is positioned correctly according to the offset properties (top, right) that have been defined in the style sheet. However, when I request a detail page (child template), the form doesn't render correctly. The text input field disappears and the submit button shifts over to the left edge of the form. That said, the offsets are still positioning the form correctly. I'm trying to understand what is causing the form to not render properly on the child template? # index.html <--- Parent Template {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'css/global.css' %}"> </head> <body> <form class="form_style"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor %} <button class="form_button" type="submit">Search</button> </form> {% block content %}{% endblock %} </body> </html> # detail.html <--- Child Template {% extends 'index.html' %} {% block content %} {% for key, value in mineral.items %} {% if key == 'name' %} … -
How to do type ahead search in SQL server database
I am writing back-end API in Django for an Angular front-end application. I am using an SQL-server database and a linked server. In the front-end I want to use type-ahead search for employees. For ex. In front-end if I want to search for employees having names 'Lisha' then while typing the name itself data is fetched from database (linked server). Currently I am using a query like: select * from openquery([LinkedServer], 'select employeeName from "DB"."View" where "employeeName" LIKE "%Lisha%"') The query will search for all the name like 'Lisha' and then return the result set which I am sending to the front-end. But what I want is as soon as user type 'L' the result should start coming and I can send the result to frontend without waiting for the all the name having 'L' query getting completed. The query I am using is very slow as it waits for all the names having 'Lisha' to get finished and then the result set I can send to the front-end. How can I make it faster and how can I use type ahead search? -
How do I properly install virtualenvwrapper on Mac?
I've gone through so many questions and Google Searches, and my command prompt still continues to say that no command "mkvirtualenv" is found. I am trying to create a virtual environment to use Django on, but I can't with this problem in the way. -
Django order_by randomizes queryset twice?
I am trying to randomize a query set for a program i'm working on. full_quiz = Quiz.objects.get(name=quiz_name).questions.all() form = TheForm(full_quiz) if request.method == "POST": form = QuestionForm(request.GET, full_quiz) From my testing, it appears like the query set is getting randomized with the second form variable. Any fix for this? Thanks -
How to get file name for uploading image into s3 bucket?
Hello I am facing an issue while adding a file in to s3 bucket.... I am sharing my model class UserProfile(SoftDeletionModel, BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=True) contact_number = models.CharField(max_length=20, blank=True) profile_pic=models.TextField(blank=True, null=True) Here is my serializer class class UserprofileSerializer(ModelSerializer): class Meta: model = UserProfile exclude = ['deleted_at','created_date','modified_date'] extra_kwargs = {'user': {'required': False}} Here is my view class UserProfileUpdateView(UpdateAPIView): def get_queryset(self, *args, **kwargs): queryset_list = UserProfile.objects.filter( user=self.request.user) return queryset_list serializer_class = UserprofileSerializer The issue I am facing is..... THe profile pic uploaded as a image.... But in my model it created as a textfield , for saving the s3 bucket proxy url..... I need to get the file name for creating a path in s3 bucket ...... So how can I do that ? -
request.user.is_authenticated(AS user from group):
I am creating an authentication system for my Django web-app. This is my model: class Student(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) total_earnings = models.IntegerField(default="0") month_earnings = models.IntegerField(default="0") def __str__(self): return self.name class Clase(models.Model): name = models.CharField(max_length=300) counter = models.IntegerField(default="6") language = models.CharField(max_length=10,choices=LANGUAGE_CHOICES, default='english') students = models.ManyToManyField(Student) teachers = models.ManyToManyField(Teacher) def __str__(self): return self.name I want to give different permissions and features to teachers and students, but I have no clue on how. Any ideas? Thanks! -
Why does the Django-Summernote prevents prepopulated_fields from working?
I noticed Django-Summernote that I was willing to use in Django Admin prevents PostAdmin from working properly. As soon as I try to replace the default content field with the Summernote one, Auto-Slug stops working and most of the posted contents' texts are not shown. I did a quick search and unfortunately, I could not figure out a way to solve this issue. Therefore, I would be glad if you guys tell me what's wrong. This is my admin.py: from django.contrib import admin from .models import Post from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'status','created_on') list_filter = ("status",) search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} class PostAdmin(SummernoteModelAdmin): summernote_fields = ('content',) admin.site.register(Post, PostAdmin)