Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Catch the value returning from Django in HTML/JavaScript
I have created a django API, which is returning a json object. And then I have a separate web application from which I am calling the django API. Now I want to store/catch the returned Json object in my HTML/Javascript. Here's the code I am using HTML Code <div > <form acton="http://xx.xxx.xx.xxx:xxxx/export" method="POST"> <label class="optinLabel">Project Name</label> <input type="text" placeholder="confirm your project name"/> <label class="optionLabel">Downlaod</label> <input type="submit" value="Json" style="color:red" /> </form> </div> Django views.py def export(request): if request.method == "POST": projectname = request.POST.get('projectname') folderpath = "/home/data" finalpath = os.path.join(folderpath,projectname) json_result = ann_json(finalpath) return JsonResponse({"response":json_result}) Here the view.py returning the Json, how will catch that in my HTML Code? Any help will be appreciated. -
Change profile picture in django
im trying to make a edit profile module , but it needs to change profile picture too.. i already try some code , but the picture isnt change when i press the submit button Here's the views.py for update_profile def update_profile(request): if request.method == 'POST': user_form = UserInfoForm(request.POST, instance=request.user ) profile_form = UserProfileInfoForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() return redirect('/profile/') else: messages.error(request, ('Please correct the error below.')) else: user_form = UserInfoForm(instance=request.user) profile_form = UserProfileInfoForm(instance=request.user.profile) return render(request, 'profile.html', { 'user_form': user_form, 'profile_form': profile_form }) here's the form <form role="form" class="form-horizontal" method="post"> {% load staticfiles %} {% block body_block %} {% if registered %} <h1>Update Profile Success!</h1> {% else %} <form class="cmxform form-horizontal style-form" id="commentForm" enctype="multipart/form-data" method="POST" action=""> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit" name="" value="Update"> </form> {% endif %} {% endblock %} </form> urls.py (already add +static[]) from someone suggestion and still not working app_name = 'polls' urlpatterns = [ path('', views.login_view, name='login'), path('home/', views.index_view, name='indexing'), path('profile/', views.update_profile, name='profile'), path('definesegment/', views.list_all_table, name='definesegment'), path('script/', views.script, name='script'), path('load-data/', views.list_all_tabledependent, name='load-data'), path('load-column/', views.list_all_column, name='load-column'), path('manageuser/', views.manageuser, name='manageuser'), path('approvallist/', views.approvallist, name='approvallist'), path('approvalhistory/', … -
django reverse nginx reverse proxy works but cannot debug running app
I am a newbie debugging a django 1.11 app, The reverse proxy in nginx is set to running this command python common/fastcgi.py :25410 --work-dir /data/backup --wsgi etmn_api.wsgi:application --max-conns 4096 --num-workers 8 --buffer-size 10 48576 --daemon fastcgi/etmn_api.pid --stdout /etmn_api/daemon.log and it has this url mapping url(r'^api/ip/get_info', general_api.get_ip_info) the reverse proxy works find when I access url it returns string http://34.343.43.34/api/ip/get_info but I cannot run it via the above python command, I was expecting this curl http://127.0.0.1:25410/api/ip/get_info to return a output, but it just hangs there, this is the fastcgi.py, which I have no idea from where it is taken. https://gist.github.com/swissonelabs/068839412b9acf5983c887e8ec0e1f19 Any help is appreciated, I have been stuck on this for two days straight. Thanks in advance. -
Django CRUD template not showing up
Im making a CRUD application using class instances. My app is a very simple accounting app: Django: 3.03 Python: 3.8.0 accounts/models.py class Project(models.Model): ## normal fields accounts/views.py class ProjectCreate(CreateView): model = Project fields = '__all__' class ProjectUpdate(UpdateView): model = Project fields = '__all__' class ProjectDelete(DeleteView): model = Project success_url = reverse_lazy('project') accounts/urls.py: urlpatterns = [ path('project/create/', project_views.ProjectCreate.as_view(), name='project_create'), path('project/<int:pk>/update/', project_views.ProjectUpdate.as_view(), name='project_update'), path('project/<int:pk>/delete/', project_views.ProjectDelete.as_view(), name='project_delete'), ] I have 2 template files under the following directory: accounts templates project project_form.html project_confirm_delete.html models.py urls.py views.py forms.py When i call the view: http://localhost:8000/accounts/project/create/ I get the following error: 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: accounts/project_form.html I cant figure out why this is not working. Can you please help. Any help would be much appreciated. Thanks. -
How to create optional tuple return or unpack
I want to send tuple back if function returns error message and the data if success: Example function: def test(args): if (some success here): return data return None, error_message Call: data, error_msg = test(args) if error_msg: return somehttpresponse(error_msg, 400) return somehttpresponse(data, 200) How can I achieve this in python? Or is there any other clean way to return error message without compromising the return data on success? -
Get fields from through table in Django
I have two models, organization and vendor, which are connected by a 'relational' or 'through' table, VendorOrganization. There is a field description in my through table, which I am trying to access, but do not know. How should I configure my view, query and serializer to be able to access fields from the through table? Thanks for any help! // models.py class Organization(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20, unique=True, validators=[alphanumeric_plus_underscore, MinLengthValidator(4)]) vendors = models.ManyToManyField("thirdparty.Vendor", through="thirdparty.VendorOrganization") class Vendor(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60, blank=False, null=False) class VendorOrganization(models.Model): vendor = models.ForeignKey(Vendor, blank=False, null=False, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, blank=True, null=False, on_delete=models.DO_NOTHING) created_at = models.DateTimeField(_('created at'), auto_now_add=True, null=True) created_by_user = models.ForeignKey(User, blank=False, null=False, on_delete=models.DO_NOTHING) description = models.CharField(max_length=300, blank=True, null=False) // serializers.py (this does not work to get the 'description' field) class VendorSerializer(serializers.ModelSerializer): class Meta: model = Vendor fields = ('id', 'name', 'created_at', 'created_by_user', 'description') extra_kwargs = { 'id': {'read_only': True}, 'created_at': {'read_only': True}, } // views.py class VendorView(mixins.DestroyModelMixin, ListAPIView): authentication_classes = (TokenAuthentication,) def get(self, request): pagination_class = None current_org = Organization.objects.get(id=request.user.organization.id) queryset = current_org.vendors.select_related() vendors = VendorSerializer(queryset, many=True) return Response(vendors.data) -
apscheduler's BackgroundScheduler runs twice in django project
I am trying to use apscheduler in existing django project. I have scheduled the job (print current time) to run every 1 minute. But for every 1 minute it prints the current time twice. My code snippet: class DailyMailerController: def sendMailToCustomer(): print (Utils.getHourMinuteSec(datetime.datetime.now())) def start(): scheduler = BackgroundScheduler() scheduler.add_job(dailymailercontroller.DailyMailerController.sendMailToCustomer, 'interval', minutes=1) try: scheduler.start() except(KeyboardInterrupt): print("Exiting by Ctrl+C") Output: 10:53:04 10:53:06 10:54:04 10:54:06 10:55:04 10:55:06 How to run the job only once for every 1 minute? -
how to update the json data in python Django?
I got below this error when I am trying to update the data """get() got an unexpected keyword argument 'emp_id'""" class employeeList(APIView): def put(self,request,emp_id): employeeid = employees.objects.get(id=emp_id) serializer = employeeSerializer(employeeid,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors,status=status.HTTP_404_NOT_FOUND) this is url for update path('update/<int:emp_id>',views.employeeList.as_view()) Now I want to update the employee data by taking id value.please can anyone solve this problem -
How to extend Django User Model to accept multiple images? I am trying to register a user who has to upload multiple images. Any help is appreciated
This is my first question here😅. I want to create a user registration form that can upload multiple images provided by the user. I am following this video https://youtu.be/q4jPR-M0TAQ from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) -
Can't login through Django's Admin page
I have already created a custom user model for profiling and Authentication, however it doesn't seem to authenticate the password. I tried numerous times on changing it and even confirmed it on shell but it still doesn't go through on Django Admin. Here is my models.py: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password=None, user_type=None, is_superuser=False, is_pqa=False, is_staff=False, is_admin=False, is_test_lead=False, is_test_manager=False, is_active=True): if not email: raise ValueError("User must have an email address!") if not password: raise ValueError("User must have a password!") user_obj = self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.user_type = user_type user_obj.ad = is_admin user_obj.superuser = is_superuser user_obj.tm = is_test_manager user_obj.pqa = is_pqa user_obj.tl = is_test_lead user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_pqa(self, email, password=None): user = self.create_user( email, password=password, is_pqa=True, is_staff=True, user_type=1 ) return user def create_staff(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, user_type=2 ) return user def create_test_lead(self, email, password=None): user = self.create_user( email, password=password, is_test_lead=True, is_staff=True, user_type=3 ) return user def create_test_manager(self, email, password=None): user = self.create_user( email, password=password, is_test_manager=True, is_staff=True, user_type=4 ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_admin=True, is_superuser=True, is_staff=True, user_type=5 ) return user … -
^media/(?P<path>.*)$ Error Showing in Django
I am trying to access the product created by user in my website, but it is showing that path does not found. I am not able to understand why it is showing this, even though i have added the path. Please resolve my issue. error that it is showing settings.py file i have added the media stuff urls.py file product which i want to access ,products/urls.py -
Django foreignkey to foreignkey distinct()
I hope my title is enough what my problem is, this is my views.py teacher = SubjectSectionTeacher.objects.filter(Employee_Users__id = m.id) studentenrolledsubject= StudentsEnrolledSubject.objects.filter(Subject_Section_Teacher__in = teacher.values_list('Employee_Users')).distinct().order_by('id') this is my models.py class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True) class SubjectSectionTeacher(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) I have 4 records data with same Students_Enrollment_Records ,Subject_Section_Teacher , in StudentsEnrolledSubject, i use distinct method in my views to eliminate the same record, -
How to write Filter for Slug fields using DjangoFilterBackend
I am struggling to write a filter for the slug field. Any help would be really appreciated. class ModelA(models.Model): id = models.IntegerField(db_column='Farms_ID', primary_key=True) class Main(models.Model): id = models.IntegerField(db_column='Farms_ID', primary_key=True) class ModelMainA(models.Model): id = models.IntegerField(db_column='Farms_ID', primary_key=True) a= models.ForeignKey(ModelA, on_delete=models.CASCADE, null=False, related_name='related_a') main= models.ForeignKey(Main, on_delete=models.CASCADE, null=False, related_name='related_main') How do I write the filter for Main model from django_filters.rest_framework import DjangoFilterBackend class MainFilter(django_filters.FilterSet): a = django_filters.CharFilter(field_name='WHAT SHOULD BE THE FIELD' , lookup_expr='contains') class Meta: model = Deal fields = ['a'] Thanks in Advance. -
Django Rest Framework set Token TTL?
I've been browsing the documentation but can't find it anywhere. Is it possible to set the TTL for the access and refresh tokens in Django Rest Framework? -
Connect user model with custom mysql table
I was trying to implement django authentication from this tutorial. This is the content of my models.py: import jwt from datetime import datetime, timedelta from django.conf import settings from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) from django.db import models # Create your models here. class UserManager(BaseUserManager): def create_user(self, username, email, password=None): if username is None: raise TypeError('Users must have a username.') if email is None: raise TypeError('Users must have an email address.') user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password): if password is None: raise TypeError('Superusers must have a password.') user = self.create_user(username, email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(db_index=True, max_length=255, unique=True) email = models.EmailField(db_index=True, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.username @property def token(self): return self._generate_jwt_token() def get_full_name(self): return self.username def get_short_name(self): return self.username def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') The authentication system is working, but the problem is now I want to change the user model backend with existing mysql … -
Error: that port is already in use (Ubuntu 18.04 server, not local development)
I ran ufw allow 8000 from the root account and am now trying to python manage.py runserver and it is saying error port already in use. When I run (env) justin@ubuntu-s-1vcpu-1gb-nyc3-01:~/project$ ps -ef | grep python I see the following: root 832 1 0 Feb11 ? 00:00:00 /usr/bin/python3 /usr/bin/networkd-dispatcher --run-startup-triggers root 884 1 0 Feb11 ? 00:00:00 /usr/bin/python3 /usr/share/unattended-upgrades/unattended-upgrade-shutdown --wait-for-signal justin 4225 1 0 Feb16 ? 00:00:49 /home/justin/project/env/bin/python /home/justin/project/env/bin/gunicorn --bind 0.0.0.0:8000 jobzumo.wsgi justin 12497 12369 0 03:41 pts/1 00:00:00 grep --color=auto python justin 15455 4225 0 Feb18 ? 00:00:02 /home/justin/project/env/bin/python /home/justin/project/env/bin/gunicorn --bind 0.0.0.0:8000 jobzumo.wsgi Do I need to kill any of these processes? I have been hesitant as I don't want to screw anything up. Or could the issue be coming from elsewhere? Note: I am trying to run the project from a user I created, but that is only because the project is in the justin/ directory. Don't know if this has any effect. Thanks. Also If I tagged this question wrong I apologize, feel free to move it. -
Django + Postgres: Combining JSONField key lookup with unaccent or lower
I have a Django Model that represents data about Countries that looks something like this: class Country(Model): name = TextField(unique=True) code = TextField(...) latitude = DecimalField(...) longitude = DecimalField(...) data_sources = JSONField(null=True) alternative_values = JSONField(null=True) I'm trying to maintain attribution for where I source data for the various fields here, hence the existence of data_sources. I also want to store alternative values when data sources conflict (e.g. if a country has two possible names as is the case for Czechia vs Czech Republic). The alternative_values dict looks roughly like this: { "name": [{ "value": "Czech Republic", "data_source": "Somewhere", }] } When querying the database for a Country by name, I'd like to search both the name of a country and any potential alternative names in the alternative_values object. Typically when searching for a name, I want queries to be case insensitive, and to properly account for differences in accenting (e.g. if a user searches for "Medellin", it should still match "Medellín" even if they didn't know to place the accent there). I've discovered the Postgres extensions, so I'm using __unaccent and __lower, which work like charms against the top-level name attribute. I've also discovered the ability to traverse the structure … -
django-tables2 get count of manytomany field
I'm having some difficulty getting the count of a related many to many field. I have a Project and Employee class, and the Project has a FK on Employee. Thus any employee can have 0 or more associated Projects. On the employee page, I'd like to display the total number of projects associated with the employee. Before using tables2, in my html template I had this in my view: def get_queryset(self): employees = ( Employee.objects.all() .prefetch_related('projects') .annotate(Count('projects')) ) return employees and this in my HTML {% for employee in employees %} <tr> <td><a href="{% url 'employee' employee.id %}">{{ employee.name }}</a></td> <td class="text-center">{{ employee.projects__count}}</td> </tr> {% endfor %} After moving to tables2, how can I get a count of all the projects associated with an employee? I have something that displays all the projects associated with the employee, but I only want the total count. What I have is: projects = tables.ManyToManyColumn( verbose_name="Projects", transform=lambda record: record.name, linkify_item=('project', [A('pk')]), default="(none)", ) -
UnboundLocalError at /memberships/payment ocal variable 'course' referenced before assignment
from django.shortcuts import render from django.views.generic import ListView, DetailView,View from memberships.models import UserMembership from .models import Course, Lesson # Create your views here. class CourseListView(ListView): model = Course class CourseDetailView(DetailView): model = Course class LessonDetailView(View): def get(self,request,course_slug,lesson_slug, *args,**kwargs): course_qs = Course.objects.filter(slug=course_slug) if course_qs.exists(): course = course_qs.first() lesson_qs = course.lessons.filter(slug=lesson_slug) if lesson_qs.exists(): lesson = lesson_qs.first() user_membership = UserMembership.objects.filter(user=request.user).first() user_membership_type = user_membership.membership.membership_type course_allowed_mem_types = course.allowed_memberships.all() context = { 'object' : None } if course_allowed_mem_types.filter(membership_type=user_membership_type).exists(): context = {'object': lesson} return render(request, "courses/lesson_detail.html",context) *Internal Server Error: /memberships/payment Traceback (most recent call last): File "C:\Users\ASUS\Envs\web\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ASUS\Envs\web\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ASUS\Envs\web\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ASUS\Envs\web\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\ASUS\Envs\web\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\ASUS\myproject\cpx\courses\views.py", line 20, in get lesson_qs = course.objects.filter(slug=lesson_slug) UnboundLocalError: local variable 'course' referenced before assignment* -
Docusign Create Envelope ENVELOPE_IS_INCOMPLETE using templateId
I am trying to create an envelope using the REST Api from docusign and got this error. This was working a few weeks ago and now, I suddenly got this error. Below is my json body for the request. { "status": "sent", "emailSubject": "Company Contract: Signature Required", "templateId": "310439de-819e-404b-90d6-a468bc0e4e12", "templateRoles": [ { "email": "sample1@gmail.com", "name": "Buyer Buy", "roleName": "BUYER_PROFILE" }, { "email": "sample@gmail.com", "name": "First Floor", "roleName": "SELLER_PROFILE" } ] } I also tried this request via postman and I still have the same error. I hope anyone can help. Thanks -
Django / ProgrammingError : not enough arguments for format string when using raw query
Django 2.2 Python 3.6 Mariadb Models.py made by "inspectdb" from existing database. I'm using 'raw ()' for a query that is hard to solve with django ORM. This query working good in the MYSQL workbanch. However in "Consult.objects.raw()", rasing this error. ProgrammingError not enough arguments for format string Below is the query what I wrote. monthly_consult_by_dr_2 = Consult.objects.raw( ''' SELECT CASE WHEN M.dr_id IS NULL THEN 'total' ELSE MAX(dr_id) END AS D_ID , CASE WHEN M.dr_id IS NULL THEN 'total' ELSE MAX(dr_name) END AS D_NAME , SUM(M.CNT) AS CNT , SUM(CASE WHEN M.C_TYPE = 'consulting' THEN M.CNT ELSE 0 END) AS total_consult_total , SUM(CASE WHEN M.C_TYPE = 'consulting' AND M.CONSULT_TYPE = 2 THEN M.CNT ELSE 0 END) AS total_consult_now , SUM(CASE WHEN M.C_TYPE = 'consulting' AND M.CONSULT_TYPE = 1 THEN M.CNT ELSE 0 END) AS total_consult_reserv , SUM(CASE WHEN M.C_TYPE = 'noteconsulting' THEN M.CNT ELSE 0 END) AS total_note , SUM(CASE WHEN M.BASE_TM = '201910' THEN M.CNT ELSE 0 END) AS cnt_201910 , SUM(CASE WHEN M.BASE_TM = '201910' AND M.C_TYPE = 'consulting' THEN M.CNT ELSE 0 END) AS consult_total_cnt__201910 , SUM(CASE WHEN M.BASE_TM = '201910' AND M.C_TYPE = 'consulting' AND M.CONSULT_TYPE = 2 THEN M.CNT ELSE 0 END) AS consult_now_cnt__201910 … -
How to make django reload server without change any code after few hours?
I have develop a django apps, and i start the server by using python manage.py runserver. without stop the server and without edit any code I wish it reload the server after 24 hoursy, any ideas on this? -
How to create the Tables2 class dynamically
In the tables.py in the example dir there is: class Bootstrap4Table(tables.Table): country = tables.Column(linkify=True) continent = tables.Column(accessor="country__continent", linkify=True) class Meta: model = Person template_name = "django_tables2/bootstrap4.html" attrs = {"class": "table table-hover"} exclude = ("friendly",) I am trying to create a table class dynamically, so I did: Override the get_table method like so: def get_table(self, **kwargs): """ Return a table object to use. The table has automatic support for sorting and pagination. """ table_class, table_data = type('QueryTable', (tables.Table), myTableCol), mylist table_class = table_class print(table_class, table_data) table = table_class(data=table_data, **kwargs) return RequestConfig(self.request, paginate=self.get_table_pagination(table)).configure(table) Where the table_class, table_data is where I am creating the class. myTableCol provides the columns and mylist provides the data for each column. My problem is I dont know how to include the template_name = "django_tables2/bootstrap4.html" when I am dynamically creating the table class. Also, when i do it this way, the tables dont show any borders. I am pulling data from a rdf graph and I don't know the name or number of columns, so I want to dynamically create the columns along with having the Meta class with template_name = "django_tables2/bootstrap4.html. -
User table is empty in admin and sqlite
I'm new in django and I have created a new user model and I have some issues in getting it started. I have already created a super user however it shows that the admin page and DB Browser that it's null. In my home, I got it up and running but at the office it's showing NULL. I tried creating another superuser but it's still showing as NULL. Here is the code in question: from django.db import models from django.contrib.auth.models import ( BaseUserManager,AbstractBaseUser ) # Create your models here. class UserManager(BaseUserManager): def create_user(self,email,password=None,user_type=None,is_pqa=False,is_staff=False,is_admin=False,is_test_lead=False,is_test_manager=False,is_active=True): if not email: raise ValueError("User must have an email address!") if not password: raise ValueError("User must have a password!") user_obj=self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.user_type=user_type user_obj.ad=is_admin user_obj.tm=is_test_manager user_obj.pqa=is_pqa user_obj.ts=is_tester user_obj.tl=is_test_lead user_obj.active=is_active user_obj.save(using=self._db) return user_obj def create_pqa(self,email,password=None): user=self.create_user( email, password=password, is_pqa=True, user_type=1 ) return user def create_tester(self,email,password=None): user=self.create_user( email, password=password, is_staff=True, user_type=2 ) return user def create_test_lead(self,email,password=None): user=self.create_user( email, password=password, is_test_lead=True, user_type=3 ) return user def create_test_manager(self,email,password=None): user=self.create_user( email, password=password, is_test_manager=True, user_type=4 ) return user def create_superuser(self,email,password=None): user=self.create_user( email, password=password, is_admin=True, is_staff=True, user_type=5 ) class User(AbstractBaseUser): USER_TYPE_CHOICES= ( (1, 'pqa'), (2, 'tester'), (3, 'test_lead'), (4, 'test_manager'), (5, 'admin'), ) email=models.EmailField(max_length=255, unique=True) full_name=models.CharField(max_length=255,blank=True,null=True) active= models.BooleanField(default=True) birth_date=models.DateField(null=True,blank=True) hire_date=models.DateField(null=True,blank=True) user_type=models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) ad=models.BooleanField(default=False) #superuser/admin … -
Redis backend in online using django
I have create chat app, in offline it works fine, but when i deploy it online i receive this error note: i have already install the redis without issue, this is my settings.py this is production.py which is my another settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, # "symmetric_encryption_keys": [SECRET_KEY], }, } and this my settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } note my site is live this is my referrence https://github.com/codingforentrepreneurs/ChatXChannels