Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reactjs - Current User from JWT token
So, I have created a django-rest-framework backend with JWT Authentication and now, I am trying to solve the problem where when user manually provides a URL, I have to check If the user was previously logged in. So since, I am storing the token to localStorage when the user logged in. I am doing this: componentDidMount() { if (localStorage.getItem('token')) { // fetch current user this.props.ctx.toggleLoggedIn() // this.props.ctx.setUsername('') } } If I find a token in localStorage, then I have to fetch the current User and then, toggleLoggedIn and also set the current user's username in the context. So, I am planning to create another API end-point which provides the current user when a token is given. The problem is I don't know how to start that! -
Django ValidationError when deleting queryset
I am writing a Django command to delete data older than x days from my app. The filtering is made using the following: qs = Data.objects.filter(date_created__lte=timezone.now()-timedelta(days=days_del)) With days_del being an integer and date_created a DateTimeField. When trying to either print this queryset, or calling .delete() on it result in a JSONDecodeError and ValidationError. I don't really get why this happens or how I can prevent it trying to decode JSON fileds in this case. Note that I am using the jsonfield pypi package and the Data model has a JSONField. It is possible that some data are stalled and causing the problem (see traceback), is there a way to ignore the validation and proceed with the deletion anyway? Traceback (most recent call last): File "/root/virtualenvs/myproj-prod/lib/python3.6/site-packages/jsonfield/fields.py", line 83, in pre_init return json.loads(value, **self.load_kwargs) File "/usr/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 464 (char 463) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/root/virtualenvs/myproj-prod/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in … -
Django - add & delete & update a model in a single view
How can I add a new instance, delete an instance, and update an instance of a model in one views.py ? Currently I have views.py that looks like this: class BHA_UpdateView(UpdateView): template_name = 'bha_test.html' model = BHA_List pk_url_kwarg = 'pk_alt' fields = '__all__' I know that I can update a current model instance using form: <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" class='btn btn-primary' value="Submit"> </form> But what if I want to do delete, create, and update on the same page? I'm not sure how to do if I want to add & delete & update a model instance in a single page. Ideally, if a user clicks on Delete, or Create, Update button on a page, a modal screen will show up, and within that modal screen the user will be able to do whatever thing he wants to do. What should I do? Is it possible to inherit multiple CBV, like this: class BHA_UpdateView(UpdateView, CreateView, DeleteView):? If not, what should I do? -
Configure mod_wsgi on centos webpanel
How to configure mod_wsgi on centos webpanel for django hosting. Can e host django using cwp. -
Django, How to access dynamically, related models of object
I have the model instance User. User has two 1 to 1 relations wit another two models,model1 and model2. I don't want to do user.model1 instead I want to do something like this: model_name = 'model1' user.__dict__[model_name] I found that I can do this by: user.__dict__['_wrapped'].__dict__['_' + model_name + '_cache] But I find it ugly, there is another way? -
Django ORM to combine 3 models and fetch data
## I am facing a problem in fetching the data from 3 tables combined.## ------------ 1st model- inbuilt auth_user table which is for authentication of an employee because even employee has his own dashboard after authenticating. 2nd model- it is the employee table where all the employee details will be stored . And it has the foreign key which refers to auth_user table. 3rd model- this model contains salary details of each employee in the company . And it has the foreign key which refers to auth_user table. enter code here class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class employees(models.Model): employee_name = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True, to_field='username') department = models.CharField(max_length=100) dob = models.DateField() doj = models.DateField() blood_grp = models.CharField(max_length=100, null=True) father_name = models.CharField(max_length=100, null=True) add1 = models.CharField(max_length=100, null=True) add2 = models.CharField(max_length=100, null=True) # doj = models.ImageField(upload_to='profile_pics', blank=True) con_relation = models.CharField(max_length=100) # email_id = models.EmailField(max_length=254, blank=True, null=True) webmail_id = models.CharField(max_length=100, blank=True, null=True) emergency_mob = models.CharField(max_length=100) contact_person = models.CharField(max_length=100, blank=True, null=True) biometric = models.CharField(max_length=100, blank=True, null=True) biometric_id … -
How to use Ajax in Django
I need some help here , i'm trying to make a simple POST to transfert data to view in django , and I'm getting an error ,the template contain a simple input where when we click on , the POST process start this is my template : template code this is the JS block : JS code and views file : views file and URl : URLS file filnally the error : error in the browser -
Django Post Objects Without Serializer?
I am currently dealing with an API for two models: Users and PasswordReset. class PasswordReset(models.Model): uniqueID = models.UUIDField(db_column = 'uniqueID', default= uuid.uuid4, editable=False, primary_key=True) email = models.EmailField(max_length = 150, db_index = True, unique = True) #changed to EmailField, added db_index class Meta: managed = True db_table = 'PasswordReset' class Users(AbstractUser): userID = models.AutoField(db_column ='userID', primary_key = True) email = models.EmailField(max_length = 150, db_index = True, unique = True) #changed to EmailField, added db_index password = models.CharField(max_length = 150) The front end will have access to the UUID and the password the user wants to replace with their old one. I want the front end to post this to me so that I can use the UUID to find the users email, and then use the email to go to the Users table and change the password. My problem is that I cannot serialize both the UUID and the Password together. I have no need to write any data into the database directly from the post. I just need to receive the UUID and Password and perform some basic data manipulation. Is there a way to write a post method without using serializers or to create a serializer that either 1. … -
Sum up a field in the queryset in Django
models.py class QaCommission(models.Model): user = models.ForeignKey(PlUser, on_delete=models.CASCADE, blank=True, null=True, related_name='user_commission') ref = models.ForeignKey(PlUser, on_delete=models.CASCADE, blank=True, null=True, related_name='ref_commission') price = models.FloatField(blank=True, null=True) pct = models.FloatField(blank=True, null=True) commission = models.FloatField(blank=True, null=True) status = models.IntegerField(blank=True, null=True, default=0) serializers.py class QaCommissionSerializer(serializers.ModelSerializer): class Meta: model = QaCommission fields = '__all__' views.py class QaCommissionList(viewsets.ModelViewSet): queryset = QaCommission.objects.all() serializer_class = QaCommissionSerializer If we are filtering ref=60 in this view, results show like this: { "count": 18, "next": "http://127.0.0.1:8008/api/qacommission/?ref=60&page=2", "previous": null, "results": [ { "id": 1, "price": 20.0, "pct": 0.1, "commission": 2.0, "status": 1, "user": 7, "ref": 60 }, { "id": 2, "price": 10.0, "pct": 0.1, "commission": 1.0, "status": 1, "user": 7, "ref": 60 }, ...... ...... ...... { "id": 10, "price": 15.0, "pct": 0.1, "commission": 1.5, "status": 1, "user": 7, "ref": 60 } ] } I wanna sum up all the "commission" field in the results and attach the sum to the original queryset (maybe next to "count":18), as shown above, there are 18 commission need to be count. How could I implement this? Need your help, thanks! -
Django File Upload Using a Modelform
I am currently struggling with uploading files using a Django Modelform. The form itself looks like this: class AddAzienda(ModelForm): class Meta: model = Azienda fields = ('logo', 'nome', 'indirizzo', 'citta', 'provincia', 'cap', 'p_iva', 'rea', 'email', 'top_pdf', 'bottom_pdf', 'is_active') This is the view responsible for the model creation if request.method == "POST": form = AddAzienda(request.POST, request.FILES) if form.is_valid(): print("valid") instance = form.save(commit=False) action.send(request.user, verb="ha creato l'azienda", target=instance, ip=get_ip(request)) messages.success(request, "Azienda <strong>" + instance.nome + "</strong> configurata con successo") instance.save() return redirect("/aziende/") else: form = AddAzienda() context = {"form":form, "title": "Aggiungi Azienda", "parent":"Amministrazione","page_title": "Aziende configurate", "form_title": "Aggiungi Azienda","pul": "Salva", "link_back":"/aziende/"} return render(request, "azienda_add.html", context) The form template contains the correct enctype(according to docs) and the fields seem appropriately named. This is an example for the logo field: <label class="col-lg-2 col-form-label">Logo</label> <div class="col-lg-4"> <div class="custom-file"> <input type="file" class="custom-file-input" name="logo" id="id_logo" value="{{azienda.logo.url}}" required> <label class="custom-file-label" for="id_logo">Seleziona file</label> </div> Can you guys help me? Thanks -
D3 fetch from django serialized model json returning blank array
I only write questions when I'm truly desperate, I hope someone can point me in the right direction. I am trying to build a pie chart using the data from a django model that would appear in a user page, so each user is getting different data returned in their http get query. I am currently in development, so I'm still fetching from localhost. I believe my Django is well because js ajax works well, as it should. Maybe the problem is the production environment (fetching from localhost?) // javascript var original_data = [{ "coin": "BTC", "stake": 5 }, { "coin": "LTC", "stake": 6 }, { "coin": "DASH", "stake": 9 } ]; var data = []; var url = "http://localhost:8000/wallet/data"; d3.json(url, (datos) => { loadGraph(datos) }); function loadGraph(data) { console.log("NEW DATA: "); console.log(data); var svgWidth = 500, svgHeight = 300, radius = Math.min(svgWidth, svgHeight) / 2; var svg = d3.select('svg') .attr("width", svgWidth) .attr("height", svgHeight); //Create group element to hold pie chart var g = svg.append("g") .attr("transform", "translate(" + svgWidth / 2 + "," + radius + ")"); var color = d3.scaleOrdinal(d3.schemeCategory10); var pie = d3.pie().value(function(d) { return d.stake; }); var path = d3.arc() .outerRadius(radius) .innerRadius(radius / 2); var arc = … -
Django - getting a list of groups of a loggedin user. No data or "Cannot resolve keyword 'group' into field. Choices are: id, name, permissions, user"
The version of Django I am using is 2.0.7. In my app, which is basically kind of a multiple users blog, there are users and groups, to which they belong to. There is a Many-To-Many relationship between them. Each user can sign up, later log in set up or join a group and post in his/her group. I have a problem with restrictions in the form that the user can post only in the group to which he/she belongs to. I think that the whole issue I have is limited to retrieving the fields from Many-To-Many relationships. I cannot obtain the list of groups to which a logged in user belongs to. groups/models.py class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') description_html = models.TextField(editable=False, default='', blank=True) members = models.ManyToManyField(User, through='GroupMember') def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('groups:single', kwargs={'slug':self.slug}) class GroupMember(models.Model): group = models.ForeignKey(Group, related_name='memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_group', on_delete=models.CASCADE) def __str__(self): return self.user.username class Meta: unique_together = ('group', 'user') posts/models.py class Post(models.Model): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', … -
Posting data using Django unit testing not saving to backend
I am creating a django app which i which implement most of my logic before the design aspect of the application. I created a testcase for user registration but anytime I post to the registration url, it received my posted data but never populates it to database. class AuthTest(TestCase): def setUp(self): self.client = Client() def test_reg_index(self): response = self.client.get(reverse_lazy('register')) return self.assertEqual(response.status_code, 200) def test_registration(self): data = { 'last_name': 'test_user', 'first_name': 'test_user', 'email': 'fashtop3@gmail.com', 'phone': '08035112897', } response = self.client.post(reverse_lazy('register'), data) self.assertEqual(response.status_code, 302) def test_login(self): # self.client.login(username='foo', password='bar') # request.user is now user foo data = { 'email': 'test_user@example.com', 'password': 'pass123', } response = self.client.post(reverse_lazy('login'), data) self.assertEqual(response.status_code, 200) class RegisterView(FormView): """ this handles users registration """ form_class = RegForm template_name = "club/register.html" success_url = reverse_lazy("register") # def get(self, request, *args, **kwargs): # return super(RegisterView, self).get(request, *args, **kwargs) def form_invalid(self, form): print(form.errors.as_data) return super().form_invalid(form) def form_valid(self, form): """ Process valid registration form :param form: :return: redirects to success_url """ random_password = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(6)) try: with transaction.atomic(): """Allow database transactions""" data = form.cleaned_data user = User.objects.create_user( email=data['email'], password=random_password, remember_token=hashlib.sha1(str(datetime.now()).encode('utf-8')).hexdigest() ) user.profile.last_name = data['last_name'] user.profile.first_name = data['first_name'] user.profile.phone = data['phone'] user.save() send_notification.delay(user.pk, random_password) print('Reg success') messages.success(self.request, "Regular successfully registered … -
Does Django have a way to do something only at the time of user creation (and not every save)?
I am trying to get around difficulty bulk importing users with user info via django allauth social login. I am doing this by creating a separate model which I can csv upload user information to, which will be ported over to the real table after the user logs in for the first time. Essentially, it will pre-populate the user's information for them based on their email. The issue I am running into is that because I am using a post_save sender, it is trying to update the information every time the user changes an aspect of their profile. My issue with this is in the case where user information legitimately changes, but it wasn't updated in the UserData table (which is only meant to be used for initial import), it will simply change back. I am curious for any ideas to get around this. Thanks! @receiver(post_save, sender=User) def imported_info_update(sender, instance, **kwargs): imported_info = UserData.objects.get(email=instance.email) job = Jobs.objects.get(job=imported_info.department) location = Locations.objects.get(location=imported_info.team) school = Schools.objects.get(school=imported_info.school) UserProfile.objects.update_or_create(user_id=instance.id, job=job, location=location, school=school) -
how to override wagtail admin login page
I am trying to build my own custom login page for wagtail admin login page. Everything is working fine I removed all the content by extending {% extends "wagtailadmin/login.html" %} Login is working but the default sign in button is still showing in my custom login page. How to remove it. Here my own custom login page code is {% extends "wagtailadmin/login.html" %} {% load staticfiles i18n %} {% block css %} #Loaded my css files here {% endblock %} {% block branding_login %}{% endblock %} # to Remove branding login(login to wagtail site) {% block fields %} #Login form here {% endblock %} -
Run python script from js file
I am trying to develop a chatbot using Django and depending on the user's input, various python scripts need to be run. Having the project structure (presented below), is there a way to call the news.py in chatbot.js? I have tried with an ajax request: $.ajax({ type: "POST", url: "news/", data: { } }).done(function( o ) { print('success') }); and defined news/ in my urls.py url('news/', getNews) where getNews is defined in my views from artemis.static.marketdata.news import scrape class getNews(): scrape() but I get a 500 error saying that TypeError: object() takes no parameters What would be the preferable approach in this case? Any tip would be greatly appreciated! -
Get data-id variable from Django POST request
My template: <h1 data-post-id="{{ obj.id }}"></h1> views id = request.POST.get('post-id') print('ID:', id) #prints None How can I get access the post-id data attribute in my python/django views? -
Slug and rename the same field in Django Serializer
If I have it correct (and this is the way I use it) SlugRelatedField in Django Serializer can be used to return the string value from the ID of a foreign-key field. Like I said I regularly do this. I also regularly change the field name in a table to something different by using CharField. But how do I use both of these together? What I have so far is: class ProductContainersSerializer(serializers.ModelSerializer): containernameid = serializers.SlugRelatedField(read_only=False, slug_field='containername', queryset=Productcontainernames.objects.all()) container = serializers.CharField(source='containernameid') productid = serializers.SlugRelatedField(read_only=False, slug_field='productid', queryset=Productlist.objects.all()) class Meta: model = Productcontainers fields = ('container','productid') The model has two fields: class Productcontainernames(models.Model): containername = models.CharField(db_column='containerName', max_length=255, blank=True, null=True) # Field name made lowercase. members = models.ManyToManyField(Productlist, through='Productcontainers') The above would work fine, if it was not for the fact that when I run my code it says that I must include the containernameid due to the fact that I have declared it. This kind of defeats the purpose because now I basically send the same information through twice (as container and containernameid). How can I return the string value (not id) of containernameid AND change the name of the field to container? -
django haystack whoosh not showing any errors also no results
I am trying to django-haystack whoosh. Django Haystack & Whoosh search working but in page no giving result. I have looked up this similar question too Django-haystack-whoosh is giving no results Django Haystack & Whoosh Search Working, But SearchQuerySet Return 0 Results pip freeze python==3.6 django==2.0.7 Whoosh==2.7.4 -e git://github.com/django-haystack/django.haystack.git#egg=django-haystack Here is my code: search_indexes.py import datetime from haystack import indexes from search.models import Articles class ArticlesIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document = True, use_template = true pub_date = indexes.DateTimeField(model_attr = 'pub_date') content_auto = indexes.EdgeNgramField(model_attr='title') def get_model(self): return Articles def index_queryset(self, using=None) return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now()) viws.py from .models import Articles from haystack.query import SearchQuerySet def home(request): article=SearchQuerySet().autocomplete(content_auto=request.POST.get('search_text', '') return render(request, 'home.hmtl') home.html <form method='post'action=''> {% csrf_token %} <table> {{form.as_table}} <tr> <td><input type='search'></td> <td><input type='submit' value= 'Search'></td> </tr> </table> {% if query %} <h3>Results</h3> {% for article in articles %} <p><a href="{{article.object.get_absolute_url}}">{{article.object.title}}</a></p> {% empty %} <p>No results found </p> {% endfor %} {% endif %} </form> models.py from django.db import models class Articles(models.Model): title = models.CharField(max_length = 255) body = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title projectfile/templates/indexes/search/articles_text.txt {{object.title}} {{object.body}} settings.py INSTALLED_APPS = [ 'haystack', 'whoosh', ] WHOOSH_INDEX=[os.path.join(BASE_DIR, 'whoosh/'),] HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'), }, } I ran … -
Cannot login using user model Django
I have inserted data using User.objects.create() to the the User model and I cannot seem to login using the correct email and password. Whenever I try to Django always returns "wrong username or password" even though I have checked that the user exist using Django ORM. However, if I register using the link on the webpage, I can login but it created a user with a blank username so I can only create one user, change the username using Django ORM, and then create another one. Is there anything I did wrong? Thanks in advance Here is my User model: from django.contrib.auth.models import AbstractUser, UserManager from django.core.urlresolvers import reverse from django.db import models from django.db.models import Q from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ class MyUserManager(UserManager): def create_user(self, *args, **kwargs): """ Set username field as email. """ kwargs['email'] = self.normalize(kwargs['email']) kwargs['username'] = self.normalize(kwargs['email']) return super(MyUserManager, self).create_user(*args, **kwargs) @python_2_unicode_compatible class User(AbstractUser): ADMIN_AREA = 'aa' FINANCE = 'fn' RELATIONSHIP_MANAGER = 'rm' BUSINESS_MANAGER = 'bm' SENIOR_BUSINESS_MANAGER = 'sbm' ADMIN_INTERNAL = 'brm' POSITION_CHOICES = { (ADMIN_INTERNAL, 'Admin Internal'), (SENIOR_BUSINESS_MANAGER, 'Senior Business Manager'), (BUSINESS_MANAGER, 'Business Manager'), (RELATIONSHIP_MANAGER, 'Relationship Manager'), (FINANCE, 'Finance'), (ADMIN_AREA, 'Admin Area') } name = models.CharField(_('Nama Lengkap'), blank=True, max_length=255) phone … -
Can I have Django template tags inside a django-compressor tag?
For example: {% compress css %} <link rel="stylesheet" href="{% static 'css/foo.css' %}"> {% if foobar %} <link rel="stylesheet" href="{% static 'css/bar.css' %}"> {% endif %} {% endcompress %} As above, can I have an if tag inside the compress tag? Does this work with the OFFLINE_COMPRESSION mode? -
django migration error message
I have the following models: from django.db import models from django.utils import timezone # Create your models here. class customer(models.Model): # Need autoincrement, unique and primary cstid = models.AutoField(primary_key=True, unique=True, default=1) name = models.CharField(max_length=35) age=models.IntegerField() mobile=models.IntegerField() class doctor(models.Model): docid = models.AutoField(primary_key=True, unique=True) # Need autoincrement, unique and primary name = models.CharField(max_length=35) regid = models.CharField(max_length=15, default="", blank=True) photo = models.CharField( max_length=35, default="", blank=True) email = models.EmailField(default="") phone = models.IntegerField(default=0, blank=True) qualifications = models.CharField( max_length=50, default="", blank=True) about = models.CharField( max_length=35, default="", blank=True) specialities = models.CharField( max_length=50, default="", blank=True) department = models.CharField(max_length=50, default="ENT", blank=True) fees = models.FloatField(default=300.0) displayfee = models.IntegerField(default=0, blank=True) slotrange = models.CharField(max_length=50) slotdurn = models.IntegerField(default=10) breakrange = models.CharField( max_length=50, default="", blank=True) slotsleft = models.CharField( max_length=50, default="", blank=True) def __str__(self): return self.name class appointment(models.Model): date = models.DateField(default=timezone.now) time = models.TimeField(default=timezone.now) docid = models.ForeignKey(doctor, on_delete=models.CASCADE, blank=True) cstid = models.ForeignKey(customer, on_delete=models.CASCADE, blank=True) CstSlot = models.CharField(max_length=10) SlotsAvailable = models.CharField(max_length=40) Durn = models.IntegerField() During migration, I get the following errors: You are trying to add a non-nullable field 'cstid' to appointment without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a … -
Read and write on a local serial device from Django based web application hosted on a AWS linux machine.
I have a local linux machine that interacts with our product locally over serial ports for communication, now i'm stuck at making an Django web application that is running on our AWS linux machine and can make direct communication to the local machine's serial port (for reading as well as writing) whenever the Django web application is accessed on that local machine. Things i've tried before posting : Ive tried socat and netcat, for accessing the serial device over the same local network( LAN ) Tried to forward all the data recived on the /dev/ttyS0 to 35.154.21.234 (Public IP) this ip's port number 1234 : nc 35.154.20.239 1234 < /dev/ttyS0 Tried to start continuous listening on the 1234 port and forward it to the virtual port /dev/pts/2 loacted on the : sudo nc -lvp 1234 > /dev/pts/2 I want to use serial port of local linux machine as a serial port of my cloud hosted linux server. Does anyone has any idea about what i am doing wrong or how to make it possible?? -
TemplateDoesNotExist even if the path set is correct
Look and help I think the path entered in the code is correct,still it's showing template doesn't exist. -
django datefime filed ignore milisecond and extra data
By default, Django DateTime filed save and show second and millisecond and extra info in data for example it saves and show date like: 2018-07-21 05:27:29.736956+00:00 is there any way to or any global function to ignore extra info and get only date and time when trying to retrieve data? like 2018-07-21 05:27:29 model: class Enrolled(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id', related_name='enroll') created_date = models.DateTimeField(auto_now_add=True) serilizer class EnrolledSerializer(ModelSerializer): ptitle = serializers.SerializerMethodField() instructor = serializers.SerializerMethodField() instructorid = serializers.SerializerMethodField() pslug = serializers.SerializerMethodField() def get_instructor(self, object): return object.product.author.username def get_instructorid(self, object): return object.product.author.id def get_ptitle(self, obj): return obj.product.title def get_pslug(self, obj): return obj.product.slug class Meta: model = Enrolled fields = [ 'id', 'user', 'product', 'ptitle', 'instructorid', 'pslug', 'instructor', 'created_date', ] read_only_fields = ['product', 'created_date', 'id', 'user', 'instructor', 'instructorid', 'pslug', 'ptitle']