Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to switch local and deployment environment in django setting
I know I can set Config Var in Heroku that I can save my secret key and other credential(etc. db information). So I have this setting, # settings.py from os.path import abspath, dirname, join import psycopg2 import dj_database_url BASE_DIR = dirname(dirname(abspath(__file__))) SECRET_KEY = ['ENV_SECRET_KEY'] DEBUG = True DATABASES['default'] = df_database_url.config(conn_max_age=600, ssl_require=True) I want to switch base on the environment. For example, # local_setting.py django_secrety_key = 'foo' django_db = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'example_db', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' } } # settings.py from os.path import abspath, dirname, join import psycopg2 import dj_database_url from local_setting import * BASE_DIR = dirname(dirname(abspath(__file__))) SECRET_KEY = if local django_secret_key, else ['ENV_SECRET_KEY'] DEBUG = if local True else False DATABASES['default'] = if local django_db else df_database_url.config(conn_max_age=600, ssl_require=True) How can I set local so that I can check it uses local_setting?? -
how to insert primary key value in another table in django
i have created model code is blow here from django.db import models Create your models here. class EmployeeDetail(models.Model): emp_fname = models.CharField(max_length=50, default="") emp_lname = models.CharField(max_length=50, default="") emp_uname = models.CharField(max_length=100, default="") emp_email = models.EmailField(max_length=254, default="") emp_password = models.CharField(max_length=100, default="") emp_dob = models.DateField(max_length=50, default="") emp_doj = models.DateField(max_length=50, default="") emp_designation = models.CharField(max_length=100, default="") emp_salary = models.IntegerField() emp_leaves = models.IntegerField() emp_contact = models.CharField(max_length=12, default="") emp_photo = models.ImageField(upload_to="employee/images", default="") def __str__(self): return self.emp_fname class Post(models.Model): emp_id = models.ForeignKey('EmployeeDetail', on_delete=models.CASCADE) title = models.CharField(max_length=255) content = models.TextField() author = models.CharField(max_length=15) timeStamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + ' by ' + self.author and i have view.py file is blow here from django.shortcuts import render, redirect from .models import EmployeeDetail, Post from django.http import HttpResponse from django.contrib import messages # Create your views here. def login(request): # messages.success(request, 'Welcome to Login Form') if request.method == "POST": uname = request.POST['uname'] password = request.POST['password'] employee = EmployeeDetail.objects.filter(emp_uname=uname, emp_password=password) # print(employee) if employee: uname = request.POST['uname'] request.session['emp_uname'] = uname return redirect('employee/home') # return redirect('employee/home') else: messages.error(request, 'Wrong Details') return render(request, 'login.html', {}) return render(request, 'login.html', {}) def create_post(request): if request.session.has_key('emp_uname'): name = request.session['emp_uname'] query = EmployeeDetail.objects.filter(emp_uname=name) if request.method == "POST": title = request.POST.get('title') eid = request.POST.get('eid') euname = request.POST.get('ename') content … -
Django ORM: Equivalent of SQL `NOT IN`? `exclude` and `Q` objects do not work
The Problem I'm trying to use the Django ORM to do the equivalent of a SQL NOT IN clause, providing a list of IDs in a subselect to bring back a set of records from the logging table. I can't figure out if this is possible. The Model class JobLog(models.Model): job_number = models.BigIntegerField(blank=True, null=True) name = models.TextField(blank=True, null=True) username = models.TextField(blank=True, null=True) time = models.DateTimeField(blank=True, null=True) What I've Tried My first attempt was to use exclude, but this does NOT to negate the entire Subquery, rather than the desired NOT IN: query = ( JobLog.objects.values( "username", "job_number", "name", "time", ) .filter(time__gte=start, time__lte=end, event="delivered") .exclude( job_number__in=models.Subquery( JobLog.objects.values_list("job_number", flat=True).filter( time__gte=start, time__lte=end, event="finished", ) ) ) ) Unfortunately, this yields this SQL: SELECT "view_job_log"."username", "view_job_log"."group", "view_job_log"."job_number", "view_job_log"."name", "view_job_log"."time" FROM "view_job_log" WHERE ( "view_job_log"."event" = 'delivered' AND "view_job_log"."time" >= '2020-03-12T11:22:28.300590+00:00'::timestamptz AND "view_job_log"."time" <= '2020-03-13T11:22:28.300600+00:00'::timestamptz AND NOT ( "view_job_log"."job_number" IN ( SELECT U0."job_number" FROM "view_job_log" U0 WHERE ( U0."event" = 'finished' AND U0."time" >= '2020-03-12T11:22:28.300590+00:00'::timestamptz AND U0."time" <= '2020-03-13T11:22:28.300600+00:00'::timestamptz ) ) AND "view_job_log"."job_number" IS NOT NULL ) ) What I need is for the third AND clause to be AND "view_job_log"."job_number" NOT IN instead of the AND NOT (. I've also tried doing the sub-select … -
How can I combine DetailView with a custom form?
I have a detail view in which I display post's title, date, content underneath that I have a button to add a comment which takes to me an other page which has a form to create a comment, what I want to do is have that form on detail view page instead of redirecting to another page. My Post: My comment form: My PostDetailView and CreateCommentView class PostDetailView(DetailView): template_name = 'blog/detail_post.html' context_object_name = 'post' model = Post def CommentCreateForm(request,pk): if request.method == 'POST': post = get_object_or_404(Post,pk=pk) form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail',pk=post.pk) else: form = CommentForm() return render(request,'blog/create_comment.html',{'form':form}) My urls.py: urlpatterns= [ path('new/',views.PostCreateForm.as_view(),name='post_create'), path('',views.PostList.as_view(),name='post_list'), path ('post/<int:pk>/',views.PostDetailView.as_view(),name='post_detail'), path('comment/new/<int:pk>',views.CommentCreateForm,name='add_comment'), ] my detail_post.html: {% extends 'blog/base.html' %} {% block content %} <div class="post-title"> <a href="{% url 'post_detail' pk=post.pk %}"><h1>{{ post.title }}</h1></a> </div> <div class="post-date"> <p><b>Published on: </b>{{ post.create_date|date:"d, F Y" }}</p> </div> <div class="post-content"> <p>{{ post.content|safe|linebreaksbr }}</p> </div> <div class="add-comment"> <a class="btn btn-primary" href="{% url 'add_comment' pk=post.pk %}">Add comment</a> </div> <div class="post-comments"> {% for comment in post.comments.all %} {% if comment.approved %} <p><b>Posted By:</b>{{ comment.author }}</p> <p>{{ comment.content|safe|linebreaksbr }}</p> {% endif %} {% endfor %} </div> {% endblock %} my create_comment.html: {% extends 'blog/base.html' %} … -
Displaying multiple images to same Post
MODELS: class Activitati(models.Model): data_publicarii = models.DateField(default = "AAAA-LL-ZZ") titlu = models.TextField(max_length = 50, blank = False) text = models.TextField(blank = False) def get_absolute_url(self): return reverse('activitati', kwargs={'pk':self.pk}) class Images(models.Model): post = models.ForeignKey(Activitati, on_delete = models.CASCADE, default = None) image = models.ImageField(upload_to ='images/', blank = True, null = True) def __str__ (self): return self.post.titlu + 'Image' VIEWS: def activitati_list(request): activitati = Activitati.objects.all() post = Images.objects.all() ordering = ['-data_publicarii'] return render(request, 'activitati_list.html', {'activitati':activitati,'post':post}) TEMPLATE: {%for p in post.images_set.all%} <div class="zoom"> <img src="{{p.image.url}}" class=photo> </div> {%endfor%} Why doesnt it display anything ? i dont know what i am missing ? In the template, if i write 'post.all' instead post.images_set.all it displays all images for each post, but this is not what i want. Where can I find more documentation about that '_set' ? -
Django ManyToManyField Validate Unique Set
models.py class MyProduct(models.Model): name = models.CharField() codes = models.ManayToManyField(Code) Hi, I'm trying to validate the ManyToManyField for the unique set. it shoud validate that similar set should not repeat again on another record, In the django docs , it mentioned clearly that ManyToManyField cannot be unique=True or unique_together. So how can I handle this validation, I am not able to find the solution for this. I request please guide me for some suggestion for this, it will be helpfull for me. Thanks in advance. -
How to fetch the ID of the request user in Django?
I am creating a profile page, and need to fetch the id of the requesting user, so I can then loop it's information. I am using this view: def profile(request, id): cl = Clients.objects.get(id=request.user.id) ... But when I try access the page I get the following error: profile() missing 1 required positional argument: 'id'. Isn't the id=request.user.id passing the ID? -
Why Does not work Class_Name(Products.objects) in Django?
Class_Name(Products.objects)does not working Here says no attribute objects in Products Any one Can See in Here : https://github.com/kazisohag/django.git Please solve my problem as soon as possible And help me. -
ImportError: cannot import name 'views' from 'textutils' in Django
urls.py file from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), ] views.py file from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello") Error Occur ImportError: cannot import name 'views' from 'textutils' I Am New Here So Don't Know The Proper Method Of Posting Questions. I Hope You Understand, Please Help Me To Get Out Of This Problem ! -
Need _id from mongodb in django [closed]
I am using MongoDB in Django. i need to return _id (the object field). how can i do that? I am not using any kind of template just JSON response. data1=Filter_data.objects.get(user_id=raw_data["user_id"],post_id=raw_data["post_id"]) -
Need to set current.username in author comment section
I've created Comment section. The main goal is that only registered users can post comments and only from their usernames. For now, I have a problem from who (username) the post is posting. On screenshot, you can see, that I can choose to post comment from user:JOHUA, but I'm currently logged in from user:JOHN I need to set permission for user to post comment only from his username (maybe I should remove username variable in models.py, forms.py and admin.py and to set it by default like user:username, or maybe you know how to remove other usernames from Username column, so register user can only choose his username. I have been puzzling over this problem for a long time, so definitely need community help! HERE IS SOME CODE: models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') username = models.ForeignKey(User, on_delete=models.CASCADE) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.username) forms.py from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['username', 'email', 'body'] admin.py from django.contrib import admin from .models import Post, Category, Comment class CategoryAdmin(admin.ModelAdmin): pass @admin.register(Comment) … -
Auth0 save 'sub' instead of 'username'
I finished implementing auth0 to my django and react app. But ever since I signup with a new user, the 'sub' is saved as the username instead of the real 'name'. Is there a way to fix this? django admin user page -
Directed graphs: sons that a mother had with a given father
I am using queries of the form "all descendants of node X with an ascendant called Y". It turns out that Django returns different results depending on which of the parents of the target node one specifies as Y. Illustration: Consider the simple model class Person(models.Model): name = models.CharField(max_length=200, unique=True, blank=False) descendants = models.ManyToManyField("self", symmetrical=False, related_name='ascendants') def __str__(self): return self.name Create a graph with 3 nodes: mother = Person(name="Mother") mother.save() son = mother.descendants.create(name="Son") father = son.ascendants.create(name="Father") Thus, "Father" and "Mother" are the ascendants of "Son". This is the puzzling part. I want to retrieve the sons that "Mother" had with "Father". However, the code q1 = mother.descendants.filter(ascendants__name="Father") print("mother descendants with an ascendant called Father = ", q1) produces an empty QuerySet, which seems incorrect. In contrast q2 = mother.descendants.filter(ascendants__name="Mother") print("mother descendants with an ascendant called Mother = ", q2) correctly produces <QuerySet [<Person: Son>]>. Is this a bug of Django? Thanks! -
What can be the best way for automatic deployment of my application on AWS?
I have an app created in Django and React, but there are few problems that I am facing mainly :- As I will have a large database(postgres) exclusily for a single user, I am creating different AWS instance(t2.micro) for every user. (we are a startup so economical to use t2.micro) Whenever there is a new user then I have to go and manually install postgres, setup nginx and other important things and this is just for Django in EC2, I am not even talking about React in S3. Solutions I am looking for :- If there is a way to automatically create an AWS EC2 instance and deploy backend also same thing for AWS S3 and deploy frontend, whenever there is a new user. There are a lot of things that I will be running when the backend starts namely Huey, Installing Postgres and Creating User for it, installing Redis, making migrations and other trivial stuff. Is there a way to automate every single thing? Things to consider :- We are a startup and can not depend on paid services really much. Please do not ask me to use a single server for every user as we are using 3rd … -
How to find out which data is tenants data in postgres uisng django
so i have 10 tenants, i am using Django with django-tenants with postgresql, every tenants have users, which user data is which tenant data -
Django View Error: Local variable referenced before assignment -> Flaw in if-statement?
In my Django view I have the following if-loop: for i in queryset: if i['mnemonic'] == '#0602###95EUR00': cash_ps_totbank_eur = i['value'] cash_ps_totbank_eur_sub1 = i['value'] if i['mnemonic'] == '#0602###90EUR00': cash_ps_totbank_eur += i['value'] # Working cash_ps_totbank_eur_sub2 = i['value'] if i['mnemonic'] == '#0602###95USD00': cash_ps_totbank_usd = i['value'] cash_ps_totbank_usd_sub1 = i['value'] if i['mnemonic'] == '#0602###2095900': cash_ps_totbank_usd += i['value'] # NOT working & throwing error cash_ps_totbank_usd_sub2 = i['value'] When loading the template, Django throws me an error saying local variable 'cash_ps_totbank_usd' referenced before assignment. I do the same thing here as eight lines above, namely adding a value to a varible that was initiated in the if-loop before and hence should have already a value assigned to it. With the variables ending on _sub1 and _sub2 i tried to check, if there is maybe an error with the equality-check between the queryset and the string. But this is not the case. The variables with _sub1 and _sub2 work perfectly fine and get the correct values assigned to. Any idea what I am missing here? -
Django make query dynamically for filter
this code works well from django.db.models import Q filtered = Article.objects.filter(Q(authers__id=2) | Q(issues__id=1) | Q(issues__id=3) ) However now I have list like this below, and want to make filter dynamically. ids = [1,2,3] for id in ids: eachQ = Q(authers__id=isId) #then...... how can I make query ??? -
Djanng filter for many to many by multiple
Auther has the manytomany entity Article I can use filter for manytomany like this a = Author.objects.get(id=1) Article.objects.filter(authors=a) However I want to filter auther a and auther b like Article.objects.filter(authors=a and authors=b) How can I make it?? -
In Django, how to set value in request object in decorator function and access it from request object in decorated function
I have implemented backend api using django. Environment details are as- Environment : platform : Linux (ubuntu) framework : Django 1.11.28 programming language : python 2.7.12 (will planning to migrate 3.8 in future) Database : Mongodb 3.4 Description : I have developed web services using django. These are plain web services not Restful( earlier there wasn't full support for mongodb for Django rest framework) hence most of the things are customised not as per django standard. Issue details : For authentication I am using Azure AD. I have written simple decorator which receives access token from request sent by front web app/mobile then this decorator validates token and return to view.For authentication I am using django-auth-adfs package decorator authorisation.py def is_authorized(function): @wraps(function) def authorize(request, *args, **kwargs): # access token validation logic if validated(token): # get user details from access token first_name, last_name etc user_info = {"first_name":"foo","last_name":"bar"} return function(request, *args, **kwargs) else: return HttpResponse('Unauthorized', status=401) return authorize View.py @is_authorized def home_view(request): # calling function which decodes access token and return user details. # This function contains same code as in decorator except function it returns user_info **first_name, last_name = get_userinfo_from_access_token(request)** return JsonResponse({"data":{"fname":first_name,"lname":last_name}}) As you can see code got messy, and repetitive … -
Django Dynamic Forms with scratch
I have to make a google form or microsoft form like application in django. kindly give some ideas or example to implement it. -
Django Rest Framework Star Rating System
I have the following structure in my Django models. ratings.models.py class Rating(models.Model): class Meta: verbose_name = 'Rating' verbose_name_plural = 'Ratings' unique_together = [ 'user', 'product'] user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user') product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='product') rating = models.PositiveIntegerField( null=False, blank=False) Product has nothing special to show here. Just a simple Django model. I will omit it. In ProductDetailView in serializers i need the count per rating. A product can be rated from 1 to 5. Example: ... "ratings": { "rating1_star": 6, "rating2_star": 5, "rating3_star": 4, "rating4_star": 3, "rating5_star": 3 } I have achieved this with the following code. class ProductDetailSerializer(serializer.ModelSerializer): ratings = serializers.SerializerMethodField('get_ratings_detail') class Meta: model = Product fields = [...,'ratings',] def get_ratings_detail(self, obj): ratings = Rating.objects.filter( product=obj) r_details = ratings.aggregate( rating1=Count( 'product', filter=Q(rating__iexact=1)), rating2=Count( 'product', filter=Q(rating__iexact=2)), rating3=Count( 'product', filter=Q(rating__iexact=3)), rating4=Count( 'product', filter=Q(rating__iexact=4)), rating5=Count( 'product', filter=Q(rating__iexact=5)), ) return r_details My question is if can i achieve the same result using a better method? I quite do not like how get_ratings_detail looks like, and also i am not sure if this is the best way to do it. Thank you. -
When I save the page as a draft, I get a many-to-many relationship error
class Article(models.Model): """ Article """ nid = models.BigAutoField(primary_key=True) article_title = models.CharField(verbose_name=_('Article title'), max_length=150) summary = models.TextField(verbose_name=_('Article summary'), max_length=255) content = models.TextField(verbose_name=_('Article content'), author = models.ForeignKey(verbose_name=_('Article author'), to=settings.AUTH_USER_MODEL, on_delete=models.PROTECT) category = models.ForeignKey( ArticleCategory, verbose_name=_('Article category'), null=False, blank=False, on_delete=models.PROTECT ) tags = models.ManyToManyField( verbose_name=_('Article tags'), to="Tag", through='Article2Tag', through_fields=('article', 'tag'), blank=True, ) class ArticlePage(Page, Article): content_panels = Page.content_panels + [ FieldPanel('article_title'), FieldPanel('summary', classname="full"), FieldPanel('content', classname="full"), FieldPanel('author'), FieldPanel('category'), FieldPanel('tags'), ] base_form_class = NoTitleForm forms.py class NoTitleForm(WagtailAdminPageForm): title = forms.CharField(required=False, label=_('自带标题'), help_text=_('Title is auto-generated.')) slug = forms.SlugField(required=False, label=_('自带路径'), help_text=_('Slug is auto-generated.')) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.initial['title']: self.initial['title'] = _('auto-generated-title') if not self.initial['slug']: self.initial['slug'] = _('auto-generated-slug') def save(self, commit=True): page = super().save(commit=False) page.title = strip_tags(self.cleaned_data['article_title']) page.slug = slugify(page.title) if commit: page.save() return page When I wrote an article and saved it as a draft, an error occurred:"" needs to have a value for field "nid" before this many-to-many relationship can be used. I guess, when saving as a draft, it may be that many-to-many this table is not saved, but after the first release, you can continue to edit it, and when you save it as a draft again, you will get an error. I don't know how to save this many-to-many … -
My admin panel gives 500 error when DEBUG=False
"Error:-1" is show when my DEBUG=False and "Error:-2" is show when my DEBUG=True. my setting.py file is:- DEBUG = False ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '***************' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '*************************' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # #for uploaded image MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #end of uploded image STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), # '/static/', ] This is "Error:1" .... [ When DEBUG=False ] [13/Mar/2020 16:45:33] "GET /admin/ HTTP/1.1" 500 4712 [13/Mar/2020 16:45:33] "GET /admin/js/main2.js HTTP/1.1" 404 21440 [13/Mar/2020 16:45:33] "GET /admin/js/main.js HTTP/1.1" 404 21440 … -
Set different foreign key value in django inline formset initially
I am trying to make a result management system using django. And for storing the subjects marks, I am using the django inline formset. The problem is that the user have to select a subject manually from dropdown which is Select Field in django and I think this will not be a good choice to do. So I decided to set the SelectField initially to those foreign field. But the initial value is always set to the last object of the Subject model. def subject_mark_create(request, grade_pk, exam_pk): subjects = Subject.objects.get_by_grade(grade_pk).order_by('name') SubjectMarkFormset = inlineformset_factory(Exam, SubjectMark, extra=subjects.count(), max_num=subjects.count(), fk_name='exam', form=SubjectMarkForm, can_delete=False) exam = get_object_or_404(Exam, pk=exam_pk) if request.method == "GET": formset = SubjectMarkFormset(instance=exam) for form in formset: for subject in subjects: form['subject'].initial = subject My Current inlineformset What I desired my formset should look like -
Object of type 'ManyRelatedManager' is not JSON serializable
i am working on an dummy app,here i want to select multiple user_name from MuUser model and return that to the Sessions Model. while doing this i am getting this error here is my code my MyUser model class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) date_of_birth=models.DateField(null=True,blank=True) mobile_number=models.CharField(max_length=20,blank=True,null=True) address=models.CharField(max_length=100,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) joining_date=models.DateField(null=True,blank=True) Rating_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) Rating=models.IntegerField(choices=Rating_CHOICES,default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return str(self.user_name) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin my Sessionmodel class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) SPORT=( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) Sports_category=models.CharField(max_length=10,choices=SPORT) SESSIONS=( ('General','General'), ('Business','Business'), ) Session_category=models.CharField(max_length=15,choices=SESSIONS) TYPE=( ('Paid','Paid'), ('Free','Free'), ) Session_type=models.CharField(max_length=10,choices=TYPE) Created=models.DateField(null=True,blank=True) Session_Date=models.DateField(null=True,blank=True) Location=models.ForeignKey(MyUser,related_name='street',on_delete=models.CASCADE) Player=models.CharField(max_length=100,blank=False) Start_time=models.TimeField(auto_now=False, auto_now_add=False) End_time=models.TimeField(auto_now=False, auto_now_add=False) Duration=models.CharField(max_length=30,blank=False) status=( ('1','Active'), ('2','UnActive'), ) Status=models.CharField(max_length=20,choices=status) Equipment=models.TextField() Duration=models.CharField(max_length=20,blank=False) #Level=models.ForeignKey(IntrestedIn,blank=True,on_delete=models.CASCADE) GENDER=( ('Male','Male'), ('Female','Female'), ('Male and Female','Male and Female'), ('Other','Other'), ) Gender=models.CharField(max_length=20,choices=GENDER ,blank=True) Fee=models.CharField(max_length=50,blank=True,default='0') Players_Participating=models.ManyToManyField(MyUser,blank=True) def __str__(self): return str(self.Host) class SessionViewSet(viewsets.ViewSet): def create(self, request): try: Host= request.data.get('Host') Sport = request.data.get('Sport') Sports_category = request.data.get('sports_category') #Location = request.data.get('Location') Session_category = data.get('session_category') Session_type=data.get('session_type ') Created=data.get('Created') Session_Date=data.get('Session_Date') Location=request.data.get('Location') Start_time=request.data.get('Start_time') End_time=request.data.get('End_time') Duration=request.data.get('Duration') Level=request.data.get('Level') Player=request.data.get('Player') Gender=request.data.get('Gender') Fee=request.data.get('Fee') …