Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django templates iterate model fields with indices
I have the follow model: class UserProfile(...): ... photo1 = models.URLField() photo2 = models.URLField() photo3 = models.URLField() photo4 = models.URLField() photo5 = models.URLField() And in the Create/Update template, I have to write five copies of the following div for file1 to file5: <div> Photo 1: {% if userProfileForm.instance.file1 %} <a href="{{ userProfileForm.instance.file1 }}" target=_blank>View</a> {% endif %} <input type=file name=file1> {% if userProfileForm.instance.file1 %} <a href="{% url 'account:deletePhoto' userProfileForm.instance.id %}">Delete</a> {% endif %} </div> Is there a way to iterate field file<i>? {% for i in '12345' %} <div> Photo {{ forloop.counter }}: ... </div> {% endfor %} -
Django - display all products created by a user
I have built a product app where a logged in user can create products by filling out a form. There is a products page that lists all products created by all users. When a user clicks on the profile link they will see a list of products they have created. When a user is logged in their username appears in the nav bar (this will be relevant further down this post). I want to create a page where visitors can can view products by user. I created this view: def designs_by(request, username): user = get_object_or_404(User.objects, username=username) products = Product.objects.filter(user=user) return render(request, 'designs_by.html', {'user':user,'products': products}) with this url: url(r'^designs_by/(\w+)/$', views.designs_by, name='designs_by'), which works, for the most part, but when a visitor clicks on the link to view the products by a user, the users profile link appears in the nav bar. The link won't work but I have no clue why it appears. Yeah, an odd one. -
Error Dockering Django with Webpack_Loader
Getting a stack of errors concluding to "ImportError: No module named webpack_loader". I have a Django app created that I'm trying to Docker using Gunicorn. My Dockerfile and start.sh are in a root directory alongside another directory called approot. In approot is everything you'd expect to see from running django-admin startproject. My wsgi.py file is in a directory called app inside of approot. Here is my... requirements.txt: Django>=1.8 gunicorn==19.6.0 Dockerfile: #Dockerfile # FROM directive instructing base image to build upon FROM python:2-onbuild # COPY startup script into known file location in container COPY start.sh /start.sh # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 # CMD specifies the command to execute to start the server running CMD ["/start.sh"] start.sh: #!/bin/bash echo Starting Gunicorn. cd approot exec gunicorn app.wsgi:application \ --bind 0.0.0.0:8000 \ --workers 3 My settings.py includes: INSTALLED_APPS = [ ..., 'webpack_loader' ] WSGI_APPLICATION = 'app.wsgi.application' WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': join(PROJECT_ROOT, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, } } error stack is $ docker run -it -p 8000:8000 app Starting Gunicorn. [2017-10-31 02:23:31 +0000] [1] [INFO] Starting gunicorn 19.6.0 [2017-10-31 02:23:31 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2017-10-31 02:23:31 +0000] [1] … -
How to represent value which have same field name in Django?
How to represent two columns which have the same name in Django? I have designed views and template below. However, the second and third column didn't show. Here is the my raw query cursor = connection.cursor() query = str("SELECT\n" " MG.valData,\n" " MG0.valData as value1,\n" " MG1.valData as value2,\n" " FROM\n" " T_USER AS TU\n" " LEFT JOIN M_GENERAL AS MG\n" " ON MG.Cd='002'\n" " LEFT JOIN M_GENERAL AS MG0\n" " ON MG0.Cd='001'\n" " LEFT JOIN M_GENERAL AS MG1\n" " ON MG1.Cd='001'\n") cursor.execute(query) row = dictfetchall(cursor,) return row Here is template {% for item in table_data %} <tr> <td>{{ item.MG.valData|default_if_none:"" }}</td> <td>{{ item.MG0.valData|default_if_none:"" }}</td> <td>{{ item.MG1.valData|default_if_none:"" }}</td> </tr> {% endfor %} I also tried used the alias like item.value1 and item.value2 in template. But it still showed blank values. Does anyone knows the mistakes? Thank you in advance. -
'str' object is not callable Am I wrong to assign User to method wrong?
I wanna print out composite_id in views.py. I wrote in response method like from django.shortcuts import render from .models import User def response(request): user = User() composite_id = user.composite(User) print(composite_id) return render(request, 'response.html') in models.py from django.db import models import uuid import random class User(models.Model): uu_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) id = models.IntegerField(null=True) regist_date = models.DateTimeField(auto_now=True) random_id = random.randint(1000,9999) @property def composite(self): return ''.join([str(self.uu_id), '_', str(self.regist_date), '_', str(self.random_id)]) I really cannot understand why this error happens because I do not think I assign string somewhere. But I think ,maybe am I wrong to assign User to method wrong? But I think argument of views.py's composite method should be User bacause models.py's self = User.How should I fix this?What should I write it? -
Call A Django View Without Refreshing The Page
Here's the view that updates the timestamp of a model in database whenever it's called, def data(request): new = Data.objects.filter(user=request.user) new.update(timestamp=timezone.now()) return HttpResponse('') This view is related to this URL, url(r'^go/$', views.data, name='data') Everything is fine, but how can I call this view & update the database without refreshing the page? -
Django Rest Framework: Filtering in Read/Write Related Field
I have Users and Groups, where Groups are a PrimaryKeyRelatedField on Users. When retrieving a User, I only want to show the Groups that it has in common with the current users. For example, suppose user_1 belongs to group_1, and user_2 belongs to group_2. If user_1 pings my LIST USERS endpoint I want to get: [{'groups': [1], 'username': 'user_1'}, {'groups': [], 'username': 'user_2'}] Note that although group_2 exists, it is not listed under user_2's groups, because user_1 is not in it. Thoughts so far: Overloading to_representation seems like it will just change how the group is shown in the list of groups, not whether it is shown at all There are some guides about how to filter the writable group choices here, meaning that user_1 couldn't, for instance, add itself to group_2 There are some guides about how to filter for a read-only field I could combine the above two and do a read-only field and a write-only field, as suggested here for a different problem, but I'd rather not. I don't see any guides on how have a single read/write RelatedField filtered by the current user. Any ideas? My code: # serializers.py, vanilla from django.contrib.auth.models import User, Group from … -
Translation instructions in Wagtail don't work
trying to create multiple language fields in wagtail based on the instructions. My base.py file contains: MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ] USE_I18N = True My blog/models.py file looks like this: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailsearch import index from django.utils import translation class TranslatedField(object): def __init__(self, en_field, es_field): self.en_field = en_field self.es_field = es_field def __get__(self, instance, owner): if translation.get_language() == 'es': return getattr(instance, self.es_field) else: return getattr(instance, self.en_field) class BlogIndexPage(Page): intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] subpage_types = ['blog.BlogPage'] class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) #body_en = RichTextField(blank=True) #body_es = RichTextField(blank=True) body = TranslatedField( 'body_en', 'body_es', ) search_fields = Page.search_fields + [ index.SearchField('intro'), #index.SearchField('body'), ] content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('intro'), #FieldPanel('body', classname="full"), ] parent_page_types = ['blog.BlogIndexPage'] When I run ./manage.py makemigrations it runs fine, but when I run ./manage.py migrate, I get the error: django.db.utils.ProgrammingError: column "body_es" of relation "blog_blogpage" already exists How do I resolve this error? -
django-auth-ldap AUTH_LDAP_FIND_GROUP_PERMS not working
Problem As far as I can tell, django-auth-ldap is doing everything I need given my configuration. Except that it's unable to establish a mapping from ldap groups to django groups. I have a group in ldap called dev, i.e., cn=dev. I also have a group in django called dev. When I login with my user in Django (uid=fkilibarda), django-auth-ldap is able to get my firstname, lastname, and email, but it fails to add me to the dev group. Debugging django_auth_ldap.backend line: 203 def get_group_permissions(self, user, obj=None): if not hasattr(user, 'ldap_user') and self.settings.AUTHORIZE_ALL_USERS: _LDAPUser(self, user=user) # This sets user.ldap_user if hasattr(user, 'ldap_user') and (user.ldap_user.dn is not None): return user.ldap_user.get_group_permissions() else: return set() I've found that hasattr(user, 'ldap_user') is always false. Thus, user.ldap_user.get_group_permissions() never runs, which is why the group mapping is never established. I just don't understand the significance of the above. Why doesn't user have the ldap_user attribute? Configuration AUTH_LDAP_SERVER_URI = "example_server" AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=group,dc=example,dc=example,dc=com', ldap.SCOPE_SUBTREE, '(objectClass=posixGroup)', ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': 'cn=dev,ou=group,dc=example,dc=example,dc=com', 'is_staff': 'cn=dev,ou=group,dc=example,dc=example,dc=com', 'is_superuser': 'cn=dev,ou=group,dc=example,dc=example,dc=com', } AUTH_LDAP_USER_SEARCH = LDAPSearch( 'ou=people,dc=example,dc=example,dc=com', ldap.SCOPE_SUBTREE, '(uid=%(user)s)' ) AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_ALWAYS_UPDATE_USER = True Version django-auth-ldap==1.2.14 python3 -
Determining IsAuthenticated in DRF Using DRF-JWT to retrieve a list testing with Postman
So I'm using DRF JWT for my authentication. User submits credentials, and if valid, responds with a JWT that is stored in sessionStorage. Any time the user navigates the protected routes, the JWT /api/auth/refresh to refresh the token if it is still valid. Anyway, moving on from authentication and onto protected routes where data is retrieved based on if the user is IsAuthenticated according to DRF. The problem is I am having difficulty figuring out how to determine IsAuthenticated in DRF without having the user supply credentials again. I should mention right now I am testing with Postman. API URL: /api/help/questions I have the view as: class GetQuestionsAPIView(ListAPIView): queryset = Help.objects.all() serializer_class = GetQuestionsSerializer permission_classes = [IsAuthenticated,] The serializer is: class GetQuestionsSerializer(ModelSerializer): class Meta: model = Help fields = '__all__' def validate(self, data): return data I have a valid token from /api/auth/signin/. I'm trying to pass it on to the /api/help/questions/ route to retrieve the list of questions. GET /api/help/questions/ doesn't work because it wants credentials. Authentication credentials were not provided. GET /api/help/questions/ with Content-type: application/json and 'Authorizationand the token in the header also saysAuthentication credentials were not provided.` Thought maybe it should be POST since I submitting credentials and … -
how to I log the subaddress of HTTP request
I am trying to make a simple webserver. For example, when try to visit website wordpress/mywebsite/thisiswhatIwanttorecord the backend will record the thisiswhatIwanttorecord part in a db or even just txt file and return a standard error page no matter what the suburl is. Does anyone know how to do this in Python Django? Seems like it could be as easy as changing a config file for example in Tomcat. Log all HTTP requests of Tomcat Server? -
Django Model Form: data query from selected primary key
This is my models.py file from django.db import models # Create your models here. class SchoolInfo(models.Model): school_name=models.CharField('School Name', max_length=100) built_date=models.DateTimeField('Built Date') def __str__(self): return self.school_name class TeacherName(models.Model): schoolinfo=models.ForeignKey(SchoolInfo, on_delete=models.CASCADE) teacher_name=models.CharField('Teacher Name', max_length=100) teacher_subject = models.CharField('Subject Name', max_length=100) teacher_contact_number = models.CharField('Phone Number', max_length=100) date_published = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.schoolinfo class Student(models.Model): std_name=models.CharField('Student Name ', max_length=200) CLASS_NAME=( ('6','SIX'), ('7','SEVEN'), ('8','Eight'), ('9','Nine'), ('10','Ten'), ('Ex-10','EX-Ten'), ) std_class_name=models.CharField('Class Name', max_length=7, choices=CLASS_NAME) std_roll_number=models.IntegerField('Roll Number') GENDER=( ('Male','Male'), ('Female','Female'), ) std_gender=models.CharField('Gender', max_length=7, choices=GENDER) GROUP=( ('Science','Science Group'), ('B.Studies','Business Group'), ('Arts and Humatics','Arts and Humatics'), ('General','General'), ) std_group=models.CharField('Group', max_length=17, choices=GROUP) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.std_name class ExaminationName(models.Model): examination_name=models.CharField('Examination Name ', max_length=100) exam_date=models.DateTimeField('Exam Date: ') pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.examination_name class MainSubject(models.Model): main_subject_name = models.CharField('Main Subject Name', max_length=100) main_subject_code=models.DecimalField('Main Subject Code', decimal_places=0, default=0, max_digits=10) subject_full_marks = models.DecimalField('Subject Full Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.main_subject_name class SubjectName(models.Model): mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subject_name=models.CharField('Subject Name', max_length=100) subject_full_marks=models.DecimalField('Subject Full Marks',max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.subject_name class SubjectPart(models.Model): #mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subjectname = models.ForeignKey(SubjectName, on_delete=models.CASCADE) subject_part_name=models.CharField('Subject Part', max_length=100) subject_part_full_marks = models.DecimalField('Full Marks', max_digits=6, decimal_places=0, default=100) subject_part_pass_marks = models.DecimalField('Pass Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) … -
Save Data Without Refreshing The Page
I have a view that refresh the time of a model in database whenever it's called. def data(request): new = Data.objects.filter(user=request.user) if new: new.update(timestamp=timezone.now()) This view is related to the URL, url(r'^data/$', views.data, name='data') So, how can I call this view & update the time in database when user click a URL or a button without refreshing the page? -
Query for Many to Many Fields in Django
I have these classes - class DocumentType(models.Model): type_id = models.AutoField(primary_key=True) name = models.CharField('type name', max_length=200) class MetaData(models.Model): metadata_id = models.AutoField(primary_key = True) name = models.CharField('metadata name', max_length=200, unique=True) description = models.TextField('description') class DocumentTypeMetaData(models.Model): documentType_id = models.ManyToManyField(DocumentType,) metadata_id = models.ManyToManyField(MetaData,) required = models.BooleanField(default=False) For example, a DocumentType value of 'Photo' would have Required Metadata of 'Decade' and 'Orientation'. In the DocumentTypeMetaData class I would like to have a def __str__(self) function that returns something like the following in the admin page - Photo: (Decade, Photo Type) required The format is not critical, I just want to know which metadata is required. Currently, all that is displayed is DocumentTypeMetaData object on the admin page. I am struggling with how to write the queries for this function. Thanks! Mark -
javascript increment value of hidden input and pass it to django view
I am trying to increment the number of inputs in a form when a user clicks on a map. It should pass coordinates of the clicked spot to the input. There are two options to add an input to the form: 1. By clicking on 'Add' button (then we receive an empty input). 2. By clicking on the map (then we receive an input with coordinates). To increment the number of inputs I use a hidden input which stores the value of additional points. When I use the 'Add' button, everything works correctly. I get the empty input and when I reload the page I am able to see just created fields. But when I add this inputs by clicking on a map, after reloading the page I lose all of the inputs. However I see that the value of hidden input was incremented but the fields don't show up on the page. I have tried using ajax to solve it but it didn't work... or I don't know how to use it properly. This is my code: <h2> New Trip: </h2> <form action="{% url 'trips:new' %}" method="post"> {% csrf_token %} <div id="trip-form"> {% for field in trip_form %} {{ … -
OAuth2 Client (Python/Django)
I'm creating a single sign-on (SSO) service using Python, Django, Django Rest Framework and Django OAuth Toolkit (https://github.com/evonove/django-oauth-toolkit). The SSO service will be a central, stand-alone application providing user identity services (granting access to user information as an OAuth2 Protected Resource). Django OAuth Toolkit helps to implement the OAuth2 Authorisation Server. Is there a similarly good quality Django or Python library that can help in implementing the OAuth2 Client (see following diagram snippet taken from https://tools.ietf.org/html/rfc6749#section-1.2)? +--------+ +---------------+ | |--(A)- Authorization Request ->| Resource | | | | Owner | | |<-(B)-- Authorization Grant ---| | | | +---------------+ | | | | +---------------+ | |--(C)-- Authorization Grant -->| Authorization | | Client | | Server | | |<-(D)----- Access Token -------| | | | +---------------+ | | | | +---------------+ | |--(E)----- Access Token ------>| Resource | | | | Server | | |<-(F)--- Protected Resource ---| | +--------+ +---------------+ (I expect the main use case wouldn't be a problem to implement myself, but if a good library provides handling of corner cases, errors, retries and is well tested, then it would be a shame to reinvent.) Thanks, Paul. -
Django: use first name instead of username in login success message
I am using the following view to display a welcome back message when users login successfully. I want to use first name instead of the username attribute in the message, I tried to implement methods such as request.user.get_short_name(), but somehow I could not get it right. Is there a short way for this or I have to define a method inside the class? class LoginView(SuccessMessageMixin, FormView): form_class = AuthenticationForm template_name = 'registration/login.html' success_message = 'Welcome back %(username)s!' -
Django: determine language on a mobile device?
I read on internationalization and localization in the django documentation (https://docs.djangoproject.com/en/1.9/topics/i18n/) - but somehow I missed the point, how Django actually determines the language - and how it would be possible to adapt it's default behaviour. It's about displaying a website on a mobile device in the correct language. I'm on Django 1.9 -
Django template inheritance not rendered
I'm following the django docs on template inheritance, and I think my code is correct but it doesn't work, the template people_index.html is not rendered. I have three templates, base.html, base_index.html, people_index.html, each one inherited on the previous. Like this: base.html {% include "base/header.html" %} <body> {% include "base/navbar.html" %} {% include 'base/messages.html' %} <div class="container container-content"> {% block content %} {% endblock content %} </div><!-- /.container --> </body> </html> base_index.html {% extends "base/base.html" %} <h3 class="snps-slim-font">Index de {{ index_of }}</h3> <div class="input-group"> <span class="input-group-addon">Filtrar</span> <input id="filter" type="text" class="form-control" placeholder="Ingrese un criterio"> </div> <table class="table table-hover table-condensed"> {% block table_content %} {% endblock table_content %} </table> And finally people_index.html {% extends "base/base_index.html" %} {% block table_content %} <thead> <tr> <th class="snps-slim-font">APELLIDOS</th> <th class="snps-slim-font">NOMBRES</th> <th class="snps-slim-font">DOCUMENTO</th> <th class="snps-slim-font">CUIL</th> <th class="snps-slim-font">ACCIONES</th> </tr> </thead> <tbody class="searchable"> {% for person in object_list %} <tr> <td>{{ person.last_names }}</td> <td>{{ person.first_names }}</td> <td>{{ person.document_number }}</td> <td>{{ person.cuil_number }}</td> <td class="snps-text-align-center"> <a href="{% url 'people:person-detail' person.id %}" title="ver perfil"><i class="glyphicon glyphicon-eye-open" aria-hidden="true"></i></a>&nbsp;<a href="{% url 'people:person-update' person.id %}" title="editar perfil"> <i class="glyphicon glyphicon-edit" aria-hidden="true"></i></a></td> </tr> {% endfor %} </tbody> {% endblock table_content %} The view if someone asks: class PersonListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): model = Person template_name = 'people/people_index.html' … -
Django: Messaging
Here's the model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) I wants to order the Users based upon who sent a message to request.user & to whom request.user sent a message most recently! As we see on social networks. This is what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message(It's re-orders it's name & place it to the top). But, It's not changing the order of users in case if someone sends a message to request.user. I also tried, users = Message.objects.filter(sender=request.user, receiver=request.user).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. Also, I have to use {{ users.sender }} OR {{ users.receiver }} in order to print the users name which is a problem itself in case of ordering & distinct users. How can I fix this problem? -
Django - filter with multiple para
I am trying to create a filter with multiple parameters. I found the first answer of this link is useful, so took his idea. However, I don't know how to create a string variable containing all values.Here is my code: {% with amount_comments|to_string+","+limit_amount_comments|to_string as args %} {% if page_nr|page_not_over_amount:args %} <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a> {% endif %} {% endwith %} and this is to_string filter: @register.filter(name='to_string') def to_string(value): return str(value) then page_not_over_amount filter using that args: @register.filter(name='page_not_over_amount') def page_not_over_amount(page_nr, args): if args is None: return False else: arg_list = [arg.strip() for arg in args.split(',')] comment_amount = arg_list[0] comment_limit = arg_list[1] if page_nr*comment_limit < comment_amount-comment_limit: return True else: return False But I get this exception: Could not parse some characters: amount_comments|to_string|+","+limit_amount_comments||to_string Thanks in advance! -
Running python bot in django background
I've got a django project with simple form to take users details in. I want to use python bot running in the background and constantly checking django database for any changes. Is it Celery the right tool for this job? Any other solution? Thank you -
Write to elastic search from inside Django view
I'm trying to sync a local SQLite database-entry with an elastic search index. Here is the view: def sync_greasebook(request, model_id): data = create_json(model_id) es = Elasticsearch(hosts=[{'host': 'my_host', 'port': '9200'}]) res = es.index(index='my_index', doc_type='my_doctype', id=model_id, body=data) return redirect('/') And error at line 4: ConnectionError(: Failed to establish a new connection: getaddrinfo() argument 2 must be integer or string) caused by: NewConnectionError(: Failed to establish a new connection: getaddrinfo() argument 2 must be integer or string) The put to elastic search works normally. Am I missing knowledge that doesn't allow this behavior inside Django? Any help would be much appreciated -
momentJs with class not work correctly django
hi i have a difficulty with moment.js first entry it good but after i have invalid date . I call my data in front with {{....}} : {% for lastRequest in listLastRequeteClient %} <!-- en attente --> <li class="collection-item"> <span class="title">{{ lastRequest.categoryName }}</span> <div class="row"> <div class="col s5 ultra-small leftalign "style="padding-left: 0px"> {{ lastRequest.nameRequest }} </div> <div class="col s3 ultra-small center-align"> <span class="countDateTime">{{ lastRequest.dateRequest }}</span> </div> <div class="col s4 ultra-small "> {% if lastRequest.isWaitingWorking == True %} <span class="new badge orange" data-badge-caption="En attente"></span> {% elif lastRequest.isWaitingWorking == True %} <span class="new badge blue" data-badge-caption="En cours"></span> {% elif lastRequest.isFinish == True %} <span class="new badge" data-badge-caption="Effectué"></span> {% endif %} </div> </div> </li> % endfor %} and my Javascript : function countDateEntry() { $(".countDateTime").each(function() { // get it Oct. 27, 2017, 2:27 p.m var dateEntry = $(this).text(); console.log(dateEntry); // format it var delSpace = dateEntry.replace(/ /gi, ""); var delVir = delSpace.replace(/,/gi, ""); var delDoublePoint = delVir.replace(/:/gi, ""); var FinishSerialize = delDoublePoint.replace(/\./gi, ""); console.log(FinishSerialize); // test is date is valid console.log(moment(FinishSerialize, 'MMMDYYYYhma').isValid()); var formatMomentDate = moment(FinishSerialize, 'MMMDYYYYhma').fromNow(); console.log(formatMomentDate); //$(this).text(formatMomentDate); }); } but show my console.log invalid date : First entry it is ok after it is bad . Oct. 27, 2017, 2:27 p.m. … -
DateInput in django admin form
I'm editing the form of my app admin section. model.py class Friend(models.Model): id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) genre = models.CharField(max_length=1, choices=(("M", "Male"), ("F", "Famale"))) birth_date = models.DateField() admin.py class FriendAdmin(admin.ModelAdmin): change_form_template = 'admin/change_form.html' change_list_template = 'admin/change_list.html' admin.site.register(Friend, FriendAdmin) form.py class FriendForm(admin.ModelAdmin): form = Friend fields = ('birth_date',) widgets = {'birth_date': forms.DateInput(attrs={'class': 'form-control'})} I expect that my form contains only the "birth_date" field and that it has the "form-control" class and the "DateInput" type. Nevertheless, my form contains all the fields and the "birth_date" is a simple text field. What am I doing wrong? P.S. I've imported bootstrap, bootstrap-daterangepicker, jquery and moment library and I've added this code to my change_form.html page: <script type="text/javascript"> $('.datepicker').datepicker(); </script>