Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django support for asynchronous database engines
I can't find information about django support for asynchronous database engines. For example for postgresql django supports only psycopg2 library, that is completely synchronous and nothing more is supported, for sqlite django supports only sqlite3 library that is synchronous as well. So I'm not well orientiered in django and of course I can be mistaken, but what's the sense of django asgi if it doesn't support asynchronous database engines(I mean, then all the asynchronous code becomes synchronous) ? And the second question, is there any way to use asynchronous engines in django ? -
Django Rest Framework: TypeError - Direct assignment to the forward side of a many-to-many set is prohibited
I have a custom User model and a Group model that are linked by a UserGroup through model (Many to Many relationship): models.py class User(models.Model): username = models.CharField(primary_key=True, max_length=32, unique=True) user_email = models.EmailField(max_length=32, unique=False) # Validates an email through predefined regex which checks ‘@’ and a ‘.’ user_password = models.CharField(max_length=32) user_avatar_path = models.CharField(max_length=64) class Group(models.Model): group_id = models.AutoField(primary_key=True) group_name = models.CharField(max_length=32, unique=False) group_admin = models.ForeignKey( User, on_delete=models.CASCADE, related_name='my_groups' ) members = models.ManyToManyField( User, related_name='groups', # The name to use for the relation from the related object back to this one. through='UserGroup' # Attaches a Junction table to the Many to Many relationship. ) class UserGroup(models.Model): # Manually specified Junction table for User and Group user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='user_groups' ) group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name='user_groups' ) I'm trying to associate multiple users with a group, using a PATCH request to update the members attribute of a group. Using the following GroupSerializer, I'm able to associate a user as a member of the group when the group is created, by overriding the create function of the serializer: serializers.py class GroupSerializer(serializers.ModelSerializer): members = MemberSerializer(many=True, required=False) group_admin = serializers.SlugRelatedField(slug_field='username', queryset=User.objects.all()) # A Group object is related to a User object by … -
Reuse webdriver sersions?
I was following this Re-using existing browser session in selenium But when I used the following code I am not able to create new sessions (driver = webdriver.Chrome(chromedriverPath)) anymore because the seision_id always the same from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver # Save the original function, so we can revert our patch org_command_execute = RemoteWebDriver.execute def new_command_execute(self, command, params=None): if command == "newSession": # Mock the response return {'success': 0, 'value': None, 'sessionId': session_id} else: return org_command_execute(self, command, params) # Patch the function before creating the driver object RemoteWebDriver.execute = new_command_execute Goals in my website I have too many users, so I want to prevent using too many requests as much as possible. Hence, I am trying to lunch 3 or 4 seasons then I use one of them. Now, I have too many other things I may need to explain. For example to prevent the possibility of two users clicking the same button the same time I created a data_base where it has the driver session_id and a field called is_used and a toggle it False/True. Also, when I user need data from the website I filter the database that I have then like this DriverSesions.objects.filter(is_used=False) question How can … -
CSS doesn't connect to HTML (Django)
None of my static css files connect to html. However, all static pictures work correctly. settings.py DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main' ] import os STATIC_DIR = os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] base.html (parent) <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" type="image/png" href="{% static 'img/favico.png' %}"> <title>{% block title %}{% endblock %}</title> <link rel = 'stylesheet' href = 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css'> <link rel = 'stylesheey' href = "https://use.fontawesome.com/releases/v5.8.2/css/all.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <link href="/docs/5.1/dist/css/bootstrap.min.css?v=513" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel = 'stylesheet' href = "{% static 'css/main.css' %}"> </head> index.html {% extends 'main/base.html' %} {% load static %} <head> {% block title %} {{title}} {% endblock %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> </head> {% block content %} <main> <h1>GHBDTN</h1> <body> <div class="grid-wrapper"> <header class="grid-header"> <img class="circles" src="{% static "main/img/main8.jpg" %}" alt="main pic"> <p>Предоставим качественное образование, <br> поможем понять школьную программу, <br> улучшить оценки и <br> подготовиться к экзаменам</p> </header> </div> </body> </main> {% endblock %} style.css (relate to index.html) .grid-wrapper { display: grid; grid-template-columns: 1 fr; grid-template-rows: 1 fr; grid-template-areas: 'header … -
django table onlineshop_product has no column named name
I work on an online shopping website project with the help of Django. and I'm a beginner in Django The following code provides a table of my database. It helps to add a product ``` class Product(models.Model): category = models.ForeignKey(Category,related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200,db_index=True) slug = models.SlugField(max_length=200,db_index=True) image = models.ImageField(upload_to='products/%y/%m/%d',blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) ``` Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs. OperationalError at /admin/onlineshop/product/add/ table onlineshop_product has no column named name when i did migration using the command ``` python manage.py migrate ``` it will appear Operations to perform: Apply all migrations: admin, auth, contenttypes, onlineshop, sessions Running migrations: No migrations to apply. Your models in app(s): 'onlineshop' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. ``` python manage.py makemigrations ``` It is impossible to add the field 'created' with 'auto_now_add=True' to product without providing a … -
after creating single_product using product models ,i am not able to fetch data in detail page
enter image description heredef product_detail(request,category_slug,product_slug): try: single_product = Product.objects.get(category__slug=category_slug, slug=product_slug,) except Product.DoesNotExist: single_product=None context={ 'single_product':single_product} return render(request,'store/product_detail.html',context) -
Django - how to use filter to check if a string field contains a word?
my model order has a text field as: order.remark. how to filter orders with the remark field containing certain word? e.g. a reference number, a telephone number. in the order remark field the user can input anything, how to filter orders with remark containing the words "SZFPS/LCB-D2232", for instance. Please be noted that user might type in a lot of information without enter space, i.e. the words are not seperated by space or tab or any sort of delimeters. how to effectively filter the orders? -
Showing top 5 post in django
in my project i want to show top 5 post in home section by categories.i fetch all post in home sections and if category is same i showed the post.but forloop.counter is not suitable in this situation.i need counter to break the loop or if condition.but i cant. please help me. views.py def home(request): category = Category.objects.all().filter(parent=None) post_by_category = Post.objects.filter(published=True).order_by('-category') slider = Post.objects.filter(slider=True).order_by('-created_on') context = { 'category':category, 'post_by_category':post_by_category, 'slider':slider, } return render(request,'home.html',context) home.html <div class="col-md-9"> {% for post in post_by_category %} {% if post.category.category_name == category.category_name %} <div class="d-lg-flex post-entry-2"> <a href="{{post.get_url}}" class="me-4 thumbnail mb-4 mb-lg-0 d-inline-block"> <img src="{{post.heder_image.url}}" alt="" class="img-fluid"> </a> <div> <div class="post-meta"><span class="date"><a href="{{category.get_url }}">{{category.category_name }}</a> </span> <span class="mx-1">&bullet;</span> <span>Jul 5th '22</span></div> <h3><a href="{{post.get_url}}">{{post.title}}</a></h3> <p>{{post.meta_description}}</p> <div class="d-flex align-items-center author"> <div class="photo"><img style="width:50px;height:50px;border-radius:50%" src="{{user.profile.profile_picture.url}}" alt="" class="img-fluid"></div> <div class="name"> <h3 class="m-0 p-0">{{post.author.first_name}} {{post.author.last_name}}</h3> </div> </div> </div> </div> {% endif %} {% endfor %} </div> -
How to give a query a list of objects or items?
my Question is that how can i give a list of objects or items to a query : for example i have an objects which has 4 user id like this : list_of_user_id = [1 , 2 ,3 ,6] and now i want to set the CreatorUserID equal to list_of_user_id to check how many of the users in list_of_user_id exist in the TblAnswerQuestionRequest table . this is my Model.py : class TblAnswerQuestionRequest(models.Model): text = TextField(verbose_name='محتویات درخواست',max_length=4000, blank=True, null=True) CreatorUserID = models.ForeignKey(Members, on_delete=models.PROTECT, null=True, blank=True) knowledge_request = models.ForeignKey(TblQuestionRequest, on_delete=models.PROTECT, null=True, blank=True) CreateDate = IntegerField('تاریخ ثبت', default=LibAPADateTime.get_persian_date_normalized(), null=True, blank=True) create_hour = models.TimeField(default=datetime.datetime.now(), null=True, blank=True) Status = IntegerField('وضعیت', default=1,choices=StatusChoices, null=True, blank=True) def __str__(self): return str(self.id) and what i want is like this : Question_Users = TblAnswerQuestionRequest.objects.filter(CreatorUserID = list_of_user_id) -
no such table using ( django-treebeard)
I am trying to view my table in the django-admin panel but i keep reciving no such table (table name) when i am sure it exists. models.py : from django.db import models from vessels.models import Vessel from treebeard.mp_tree import MP_Node # Create your models here. class Component(MP_Node): name = models.CharField(max_length=200, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') def __str__(self): return self.name admin.py : from django.contrib import admin from .models import Component # Register your models here. admin.site.register(Component) -
SMTPConnectError: (421, b'Server busy, too many connections')
I have watched videos and practice the same thing yet I keep getting smtp connect error EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'captainleon04@gmail.com' EMAIL_HOST_PASSWORD ='ppbdhcdnj' EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Django ninja api in AWS app runner deterministic=True requires SQlite 3.8.3 or higher error
I'm trying to deploy a django ninja API in aws App Runner, it works properly in local but when I do it in aws it says: "django.db.utils.NotSupportedError: deterministic=True requires SQLite 3.8.3 or higher". My requirements file is: Already tried adding pysqlite3 and pysqlite3-binary as it says here but has issues installing it in local because says that there are not versions that meet requirements. I'll appreciate your help, Thanks beforehand. -
how can I fix a 'IntegrityError at /admin/orders/order/add/' when FOREIGN KEY constraint failed?
I created the order model for Django rest API, and when I tried to add an order I got an error: django.db.utils.IntegrityError: FOREIGN KEY constraint failed That's the content of models.py : from django.contrib.auth import get_user_model User= get_user_model() class Order(models.Model): SIZES= (('SMALL','small'), ('MEDIUM','medium'), ('LARGE','large')) ORDER_STATUS= (('PENDING','pending'),('IN TRANSIT','in transit'),('DELIVERED','delivered')) customer= models.ForeignKey(User, on_delete = models.CASCADE, null = True, db_constraint=False) size= models.CharField(max_length=20, choices=SIZES, default=SIZES[0][0]) order_status= models.CharField(max_length=20, choices=ORDER_STATUS, default=ORDER_STATUS[0][0]) quantity=models.IntegerField(default=1) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return f"<Order {self.size} by {self.customer.id}" and admin.py : from django.contrib import admin from .models import Order @admin.register(Order) #admin.site.register(Order) class OrderAdmin(admin.ModelAdmin): list_display=['size','order_status','quantity','created_at'] how can I fix it ?? -
django table onlineshop_product has no column named name
I work on my online shopping website with the help of Django. and I'm a beginner in Django The following code provides a table of my database. It helps to add a product class Product(models.Model): category = models.ForeignKey(Category,related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200,db_index=True) slug = models.SlugField(max_length=200,db_index=True) image = models.ImageField(upload_to='products/%y/%m/%d',blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Shows me an error in the browser. This error shows me when I add a product inside the admin panel. when I add the product the following error occurs. OperationalError at /admin/onlineshop/product/add/ table onlineshop_product has no column named name Exception Value: table onlineshop_product has no column named name -
How to solve pre-commit asserttion error on ubuntu 22.04
I am using ubuntu 22.04 and the python version is 3.10.4. I have installed a Django project with the cookie-cutter. and now I have got an error when I want to commit my changes. here is the error: (blog) ➜ blog git:(main) ✗ pre-commit run [INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: AssertionError: BUG: expected environment for python to be healthy() immediately after install, please open an issue describing your environment Check the log at /home/mahdi/.cache/pre-commit/pre-commit.log Content of pre-commit.log: ### version information ``` pre-commit version: 2.18.1 git --version: git version 2.34.1 sys.version: 3.10.4 (main, Apr 2 2022, 09:04:19) [GCC 11.2.0] sys.executable: /home/mahdi/.local/share/virtualenvs/blog-qatotdDy/bin/python os.name: posix sys.platform: linux ``` ### error information ``` An unexpected error has occurred: AssertionError: BUG: expected environment for python to be healthy() immediately after install, please open an issue describing your environment ``` ``` Traceback (most recent call last): File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/error_handler.py", line 73, in error_handler yield File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/main.py", line 371, in main return run(args.config, store, args) File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/commands/run.py", line 414, in run install_hook_envs(to_install, store) File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/repository.py", line 221, in install_hook_envs _hook_install(hook) File "/home/mahdi/.local/share/virtualenvs/blog-qatotdDy/lib/python3.10/site-packages/pre_commit/repository.py", line 83, in _hook_install raise AssertionError( … -
make infinite scroll works with externals cdn call in the head
my infinite scroll is working but i notice some bugs.when the page loads before the infinite scroll calls everything is working fine but after the infinite scrolls call the fotorama is not working.the first solution i tried is to put the fotorama links to the event onAfterPageLoad but it is not working. html <head> .... <link href="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.js"></script> .... </head> <div class="infinite-container"> {% for post in posts %} ................. <div class="infinite-item"> <div class="fotorama" data-allowfullscreen="native" data-nav="false"> <img src="{{ post.image.url }}" loading="lazy"> </div> </div> ........................... {% endfor %} </div> {% if posts.has_next %} <a class="infinite-more-link" href="?page={{ posts.next_page_number }}"></a> {% endif %} <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> How can i achieve this ? -
I have created Multiple User Type Registration using Django rest-auth by using below article .Now how can i generate login logout for the user?
I follow this article Thanks In advance -
How to save user profile model with image field and user field as OneToOneField variable in django rest framework
User model is as follow. class User(AbstractUser): username = None email = models.EmailField('email address', unique=True) first_name = models.CharField('First Name', max_length=255, blank=True, null=False) last_name = models.CharField('Last Name', max_length=255, blank=True, null=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] User Profile model is as follow. class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) avatar = models.ImageField(upload_to=avatar_image, blank=True, null=True) -
django-rest-framework - How to create seperate profiles for users based on is_staff
I am working on a job portal project. I am using custom user model class UserManager(BaseUserManager): def create_user(self, email, name, password=None, **extra_fields): if not email: raise ValueError('Users must have an email address') if not name: raise ValueError('Users must have a name') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.name = name user.save(using=self._db) return user def create_staffuser(self, email, password, name): user = self.create_user( email, name, password=password ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, name, email, password): user = self.create_user(email, name, password=password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] And I have 2 separate models one for job seekers and other for employers. class SeekerProfile(models.Model): """Seeker profile for job seekers""" MALE = 'M' FEMALE = 'F' OTHERS = 'O' GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHERS, 'Others'), ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_birth = models.DateField() gender = models.CharField( max_length=1, choices=GENDER_CHOICES ) address = models.TextField() city = models.CharField(max_length=100) pincode = models.CharField(max_length=50) phone_number = models.CharField( max_length=50, null=False, blank=False, unique=True) disabled = models.BooleanField(default=False) user = models.OneToOneField( settings.AUTH_USER_MODEL, limit_choices_to={'is_staff': False}, on_delete=models.CASCADE ) def __str__(self): return self.first_name+" … -
Date based email notification in django
I am building a simple web application in Django and I wanted to add a reminder functionality to it. I decided to do with emails but the period of notifications must be specified by the user, not the admin. Are there any ways to do this? I checked celery but I am not sure that this can be implemented with it. Thanks in advance. -
Deploy Django site on netlify
I'm trying to upload my full-stack website, done with Django and React on Netlify. I have tried various ways and searched for different tutorials, but unfortunately I did not find them useful ... Many recommend using cactus to launch their own applications consisting of python, but I don't think it can work with Django, does anyone know how to do it or give me some advice? Thanks note: netlify is only for "static" websites, so how can I make my Django application "static"? -
Count number of replies on a particular post in Django
I want to count number of replies on a particular post in Django View.py **POST CODE** def forum(request): profile = Profile.objects.all() if request.method=="POST": user = request.user image = request.user.profile.image content = request.POST.get('content','') post = Post(user1=user, post_content=content, image=image) post.save() messages.success(request, f'Your Question has been posted successfully!!') return redirect('/forum') posts = Post.objects.filter().order_by('-timestamp') return render(request, "forum.html", {'posts':posts}) REPLY CODE def discussion(request, myid): post = Post.objects.filter(id=myid).first() replies = Replie.objects.filter(post=post) if request.method=="POST": user = request.user image = request.user.profile.image desc = request.POST.get('desc','') post_id =request.POST.get('post_id','') reply = Replie(user = user, reply_content = desc, post=post, image=image) reply.save() messages.success(request, f'Your Reply has been posted successfully!!') return redirect('/forum') return render(request, "discussion.html", {'post':post, 'replies':replies}) model.py class Post(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post_id = models.AutoField post_content = models.CharField(max_length=5000) timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' class Replie(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) reply_id = models.AutoField reply_content = models.CharField(max_length=5000) post = models.ForeignKey(Post, on_delete=models.CASCADE, default='') timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' I want to do like where on the place of Number of reply, I want to display the number of replies of the particular post please help me to figure it out -
Need help loading staticfiles with nginx and django to a container
I am having trouble loading the static files from my django project. Here is a picture of my directories: direcctories I have ran docker-compose up and I get the following errors: ERRORS Here is what my nginx (default.conf) file looks like: default.conf http { server { listen 8080; access_log /var/log/nginx/access.log location / { root /frontend/templates/frontend # proxy_pass http://pathfinder_gunicorn; # include /etc/nginx/mime.types; } location /static/ { alias /static/; } location ~ \.(css)$ { root /frontend/static/css; } } } Here is my Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /pathfinder COPY requirements.txt . RUN pip install -r requirements.txt COPY . . COPY ./entrypoint.sh / ENTRYPOINT ["sh", "entrypoint.sh"] RUN apk update RUN apk add RUN apk add npm COPY ./frontend/package.json /frontend/package.json COPY ./frontend/package-lock.json /frontend/package-lock.json RUN cd frontend/ && npm install RUN cd frontend/ && pwd Here is my docker-compose.yml: version: "3.8" services: pathfinder_gunicorn: build: context: . volumes: - static:/static - ./frontend/static/:/frontend/static/ ports: - "8080:8080" image: pathfinder_gunicorn:v1 container_name: pathfinder_gunicorn nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - pathfinder_gunicorn volumes: static: Here is the path to the directory from my docker-compose and Dockerfile: ./frontend/static/css The directory looks like: DIRECTORY -
How can I add aditional conditions in Django Login
I want my login function to classify If user is an one-to-one field in Alumni or Personel table. If user is related to Alumni table, log the user in and redirect to profile page. If user is related to Personel table, log the user in and redirect to another page. model.py class Alumni(models.Model): Alumni_id = models.IntegerField(primary_key=True) User_id = models.OneToOneField(User,on_delete=models.CASCADE) Name = models.CharField(max_length=50 , null=True) Surname = models.CharField(max_length=50 , null=True) image = models.ImageField(default = 'default.jpg',upload_to='profile_pic') LinkedIn = models.CharField(max_length=256 , null=True , blank=True) Line = models.CharField(max_length=50 , null=True , blank=True) Email = models.EmailField(max_length=50 , null=True , blank=True) Province = models.CharField(max_length=50) District = models.CharField(max_length=50) Sub_District = models.CharField(max_length=50) Postal_code = models.IntegerField() Address = models.CharField(max_length=50, null=True , blank=True) PhoneNumber = models.IntegerField( null=True) def __str__(self): return ("Alumni id:%s" %(self.User_id)) def get_absolute_url(self): from django.urls import reverse return reverse('Alumni_detail', args=[str(self.Alumni_id)]) class Personel(models.Model): Personel_id = models.IntegerField(primary_key=True) User_id = models.OneToOneField(User,on_delete=models.CASCADE) Name = models.CharField(max_length=50 , null=True) Surname = models.CharField(max_length=50 , null=True) Email = models.EmailField(max_length=50 , null=True , blank=True) view.py def loginpage(request): if request.method =='POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request,user) return redirect('/profile') else: form = AuthenticationForm() return render(request,'login.html',{'form':form}) -
Add a Non-Model field only for post method on ModelSerializer DRF3
I want to add a custom field that will only be used while creating an object. For example, I have a model serializer and I want to add that field that doesn't present in my model and I want to use this only while post request.