Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0.3 adding data to the database
I have a small problem with adding data to the database in django 2.0.3 I created the following model: from django.contrib.auth.models import User class UserInputSignal(models.Model): name = models.CharField(max_length=512) author = models.ForeignKey(User, on_delete=models.CASCADE) input_file = models.FileField(upload_to='signals/', null=True) I tried to solve the problem using this form: from django import forms from .models import UserInputSignal class UserInputSignalForm(forms.ModelForm): name = forms.CharField() input_file = forms.FileField() class Meta: model = UserInputSignal fields = ('name', 'input_file', ) and this view: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate from .forms import UserInputSignalForm @login_required def storage(request): form = UserInputSignalForm(request.POST or None) if request.method == 'POST': if form.is_valid(): name = request.POST.get('name') author = request.POST.get(request.user) input_file = request.POST.get('input_file') return redirect('home') else: form = UserInputSignalForm() return render(request, 'storage.html', {'form': form}) In the template I called, I created the form as follows: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> I am able to load a page with a form, but it does not post data to the database. I would like to add that I am a novice in django and some mechanisms are just plain understandable for me. Can I ask someone for help with this problem? -
Django rest framework send email verification
I'm using Django djangorestframework-jwt this is my models.py for user creation class UserManager(BaseUserManager): def create_user(self, username, email, password=None): if username is None: raise TypeError('Users must have a username.') if email is None: raise TypeError('Users must have an email address.') user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save() return user I want to send email verification before it generates token .. what's the easiest way to do that? -
UpdateView unable to process POST request - form is not callable?
According to the documenation on UpdateView this should be really simple and indeed the form is showing with the content from the database, but when clicking the submit button django displays a message saying: 'ProfileForm' object is not callable'. Why would it need a callable form ? The form works well with CreateView for example so no problem there, dont get why it would complain now. I have researched stackoverflow and search on google and indeed there are results, but none of them seem to apply to my situation as I dont see that im making any mistakes although clearly I apparently am according to django. My code is as follows: class PortfolioEditBase(UpdateView): post_req = False url_name = '' def form_valid(self, form): self.post_req = True return super(PortfolioEditBase, self).get_form(form) def get_context_data(self, **kwargs): context = super(PortfolioEditBase, self).get_context_data(**kwargs) context['post_req'] = self.post_req context['pk'] = self.kwargs['pk'] return context def get_success_url(self): return reverse(self.url_name, args=self.kwargs['profile_id']) class PortfolioEditGeneralInfo(PortfolioEditBase): model = Profile form_class = ProfileForm url_name = 'plan:general-info-edit' template_name = 'plan/portfolio/edit/general_info_edit.html' Profile form has the following code: class ProfileForm(ModelForm): class Meta: model = Profile fields = ['company', 'exchange', 'ticker', 'investment_stage', 'investment_type'] widgets = { 'earnings_growth': Textarea(attrs={'cols': 1, 'rows': 2}), } I dont think the error message django gives me … -
How can i start Satellite Navigation live map development Startup using Python?
I am quit interested in satellite live navigation map development for transportation using Python Geo-Django. If some one have experience then please guide me.. -
Django pagination in the same search page
I am displaying the results of a search in the same page as the search. I am tryin gto use the pagination in django to, well, paginate my results. The pagination works, except when I click on next or previous, the page reloads to scratch. I know I have to pass something in the template to add after the page, but I am kind of lost. Here is my view: def lookup(request): if request.method == "POST": form = SearchForm(request.POST) now = datetime.datetime.now() if form.is_valid(): l_city = request.POST['city'] l_state = request.POST['state'] l_country = request.POST['country'] result_list = Listing.objects.filter( location_Country__icontains=l_country).filter( location_City__icontains=l_city).filter( location_State__icontains=l_state).order_by('listing_from_date') paginator = Paginator(result_list, 5) # Show 5 contacts per page page = request.GET.get('page') try: result = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. result = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. result = paginator.page(paginator.num_pages) return render (request, 'lookup.html', {'result':result}) empty_data = False return render (request, 'lookup.html', {'empty_data':empty_data}) and here is my template code: {% for results in result %} display my list {%endfor%} <div class="pagination"> <span class="step-links"> {% if result.has_previous %} <a href="?page={{ result.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ result.number }} … -
Django auth backend - catch an exception and redirect to login page with modified app settings?
I have a handful of Django apps that I am setting up Auth0 as an identity provider for using python-social-core and social-app-django with the the Auth0 backend provided in their Django tutorial. Everything has gone smoothly except for one thing - when a user signs into one of these apps, they should be able to access all of the other apps without having to log in again. These apps are on different domains, so I'm not sure a shared cookie/session is an option. Per the Auth0 docs I can add silent single sign on by passing 'prompt': 'none' into the authorize url, and this works fine if I: log into an app, modify my Auth0 backend to add 'prompt': 'none' to all calls with this in the settings file SOCIAL_AUTH_AUTH0_AUTH_EXTRA_ARGUMENTS = {'prompt': 'none'}, then navigate to one of the other apps. Success, I am logged in without hitting the login page. However, if I'm logged out and the extra argument is provided I get a 500 response and an Authentication Required Exception is raised, as expected. Not sure how to handle the exception so.... My question then becomes: how can I catch this exception, modify my app settings to remove … -
Django IntegryError Response does not work
i am writing a rest api where users are able to register, login and add keyword. But the keyword will only be added if they equals to one of the AllowedKeyword Model. I have done all so far, but i have to catch the IntegrityError if the combination of keyword and owner already exists. But if i try a api call it response the keyword i wanted to add (but he does not save it, which is correct) instead of Response the error. Here is the relevant code: apy.py class KeywordViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, ] serializer_class = KeywordSerializer def get_queryset(self): return self.request.user.keywords.all() def perform_create(self, serializer): try: serializer.save(owner=self.request.user) except IntegrityError as e: return Response({ "IntegrityError": "This combination already exists." }) serializers.py def allow_keyword(key): if AllowedKeyword.objects.filter(allowed_keyword=key).exists(): return key else: raise serializers.ValidationError('This Keyword ist not allowed') class KeywordSerializer(serializers.ModelSerializer): #keyword = serializers.StringRelatedField() keyword = serializers.CharField(max_length=255, validators=[allow_keyword]) class Meta: model = Keyword fields = ('id', 'keyword', ) models.py class AllowedKeyword(models.Model): allowed_keyword = models.CharField(max_length=255, null=True, default=None, blank=True) def __str__(self): return str(self.allowed_keyword) class Keyword(models.Model): keyword = models.CharField(max_length=255, null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='keywords') # owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='keywords') def __str__(self): return str(self.keyword) class Meta: unique_together = ('keyword', 'owner') Output if keyword is not in AllowedKeyword … -
Heroku and Django 2.x ModuleNotFoundError: No module named 'rest_auth'
I've installed django-rest-auth locally with Django 2.x and it works fine. However, when I deploy to Heroku I get a "ModuleNotFoundError: No module named 'rest_auth'" error. I made sure that the requirements.txt is OK (pip freeze). I also ran commands with CLI and the Heroku CL interface : pip install django-rest-auth Any ideas why it's not working? -
Django file field stays required
I have a partial (Model)form which has a single field, namely FileField. I put this FileField as 'required=False', and inside the model I put 'blank=True, null=True'. Still, the input field contains "required" inside, seen in the HTML. This makes it so I have to upload a file in order to submit. Is there anyway to not make this a required field? The HTML <input type="file" name="invoice" class="invis" required="" id="id_invoice"> The model class Orders(models.Model): class Meta: verbose_name_plural = "Orders" invoice = models.FileField(default='default_invoice.pdf', upload_to='invoices/', blank=True, null=True) The partial ModelForm class PartialOrderForm(forms.ModelForm): invoice = forms.FileField(required=False) class Meta: model = models.Orders fields = ('invoice',) def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(PartialOrderForm, self).__init__(*args, **kwargs) self.fields['invoice'].label = "" self.fields['invoice'].widget.attrs.update({'class': 'invis'}) -
How to access another app model in django?
I have two apps main and table in my main I have a model UserSelect and in table is a model Bowler I need to do this from main.models import UserSelect, User class Bowlers(models.Model): users = models.ManyToManyField(User, through='UserSelect') but it gives error that "Field specifies a many-to-many relation through model 'UserSelect', which has not been installed" so how can I do this? -
Django Custom User form : Error: UNIQUE constraint failed: auth_user.username
I am using Django(2.0.7) UserCreationForm with three extra fields namely- first_name, last_name and email. I am getting the following error in the terminal window when I signup a new user (Though the user is created). return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: auth_user.username return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username My forms.py is class SignupForm(UserCreationForm): alphabetic = RegexValidator(r'^[a-zA-Z]+$') email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput(attrs={'placeholder': 'Email Address', })) first_name = forms.CharField(max_length=254, required=True, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'style': 'text-transform:capitalize'}), validators=[alphabetic]) last_name = forms.CharField(max_length=254, required=True, widget=forms.TextInput(attrs={'placeholder': 'Last Name', 'style': 'text-transform:capitalize'}), validators=[alphabetic]) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') widgets = {'username': forms.TextInput(attrs={'placeholder': 'Username'})} def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.fields['password1'].widget = forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Choose a Password'}) self.fields['password2'].widget = forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Confirm the Password'}) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() I have also tried overriding the default save method in the form, but that didn't work either. I have deleted my db multiple times and created fresh db but none has helped so far. I am using a login modal in bootstrap. So my views.py is some what like this:- def register_view(request): data = dict() if request.method … -
TemplateDoesNotExist when using render to pass a parameter in django
I'm trying to add an edit feature to already uploaded images in my Content Management System built using Django. @login_required def edit(request): if request.method == 'POST': ZSN = request.POST['ZSN'] ZSN = 'images/' + ZSN + '.' image = Images.objects.filter(file__startswith=ZSN) if image: for im in image: pk = im.pk return render('/photo-edit/', pk) else: return HttpResponse("Invalid ZSN.") else: return render(request, 'cms/edit.html') @login_required def photoedit(request, image_pk): image = get_object_or_404(Image, pk=image_pk) return render(request, 'cms/photo-edit.html',{'image':image}) But because of this line, return render('/photo-edit/', pk) I'm getting a TemplateDoesNotExist exception. Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/shadowsaint/Programs/my_project/templates/190 (Source does not exist) django.template.loaders.app_directories.Loader: /home/shadowsaint/Programs/my_project/venv/local/lib/python2.7/site-packages/django/contrib/admin/templates/190 (Source does not exist) django.template.loaders.app_directories.Loader: /home/shadowsaint/Programs/my_project/venv/local/lib/python2.7/site-packages/django/contrib/auth/templates/190 (Source does not exist) Notice here 190 is the pk of the image being searched. Please help. -
Can't match item ids in Django two objects array with if condition
My queryset code in view 'seats': Seats.objects.filter(bus=bid).order_by('seat_name'), 'booking': Booking.objects.filter(schedule=sid), If condition code in template {% for seat in seats %} {% for book in booking %} {% if seat.id == book.seat_id %} match: {{seat.id}} == {{book.seat_id}}<br> {% else %} <input type="checkbox" name="checks[]" value="{{ seat.id }}"> {{ seat.seat_name }}{{ seat.seat_no }} {% endif %} {% endfor %} I need to disable the booked seats but the Django system can't check if condition and it shows all seats. -
Optimize a primary key that I won't use
I'm creating a new Django (1.7) model: class MyModel(models.Model): field1 = models.ForeignKey('OtherModel') field2 = models.ForeignKey('AnotherModel', null=True) field3 = models.PositiveSmallIntegerField(db_index=True, null=True) other_field1 = models.FloatField(default=0, db_index=True) class Meta: unique_together = (('field1', 'field2', 'field3'), ) Ideally, I would have liked it to have the tuple (field1, field2, field3) as primary key, but that's not possible at the moment. So instead, I have this automatically generated and incremented id column that is required by Django but totally useless for the rest of my code. The thing is that I'd like to be able to delete and recreate instances of this model very often (almost continuously). For performance reasons, I'd like to avoid having to use a create_or_update approach, as deleting and creating is much quicker from what I've tested (18op/s with the create_or_update method, 72op/s with the "delete all and create" method, and I expect these numbers to be higher on our production server). But I'm afraid to reach the auto_increment upper limit too soon (about a year it seems). Other possibilities that I've imagined : using a Bigint primary key: that would work, but it would probably be less effective, especially considering that I will never use this primary key (and BigAutoField is … -
ValueError: Signal receivers must accept keyword arguments (**kwargs). - django
I am trying to make SignalProcessor as per haystack documentation, here is my code: from haystack.signals import RealtimeSignalProcessor from products.models import ProductCreateModel from django.db import models from star_ratings.models import Rating class BatchingSignalProcessor(RealtimeSignalProcessor): def handle_save(self): using_backends = self.connection_router.for_write(instance=instance) for using in using_backends: try: index = self.connections[using].get_unified_index().get_index(instance.__class__) index.update_object(instance, using=using) except NotHandled: # TODO: Maybe log it or let the exception bubble? pass def setup(self): models.signals.post_save.connect(self.handle_save, sender=Rating) Here you can see documentation - https://django-haystack.readthedocs.io/en/v2.2.0/signal_processors.html#custom-signalprocessors Here is what I find in django documentation but unable to figure out solution - https://docs.djangoproject.com/en/2.0/_modules/django/dispatch/dispatcher/ How to resolve this error ? -
I am learning web development using django ..can i use same database or i have to write a new one for app? how do i merge?
1..I am learning python and web development using django(framework of python for web development). I wanted to ask if i can connect the database (backend code written in django)of my website to my app also? 2..or can i convert my whole website to app using some tools? 3.. I have learnt that to make an app , you neccesarily need to learn java and write code in java in android studio . And does that mean I cant design my website in Django?? because i have to maintain both my website and app (and if database is same , it would be a bonus). 4...instagram code was written in python(backend and database) ,so how the instagram app is running? do they have written a separate code in java for their app,and database or they have somehow connected the django database with app.... any help is highly appreciated. If i am wrong with something, suggestions are most welcome -
Retrieve Data From ManyToMany Field in Form Django
I am trying to retrieve data from a modelform in which the user can select multiple options for a group permissions; for this, I am using a ManyToMany relationship. The form is structured like this: class GroupForm(ModelForm): class Meta: model = Gruppo fields = ("nome", "Autorizzazioni") def __init__(self, *args, **kwargs): super(GroupForm, self).__init__(*args, **kwargs) self.fields["Autorizzazioni"].widget = CheckboxSelectMultiple() self.fields["Autorizzazioni"].queryset = Permesso.objects.all() self.fields["Autorizzazioni"].required = False The field called Autorizzazioni has a ManyToMany relation with a Permesso model. The problem is that, since I wrote the form out manually (boss'choice), the queryset retrieved by the form is empty(althoug the ids are set correctly) This means that any choice that the user made is not saved, and the ones that were already selected aren't any longer. I use a simple form.save() which, according to documentation, should also save m2m relationships. Can you guys help me? Thanks -
Django filter by the number of rows matching a certain condition in a ManyToMany
I need to filter for objects where the number of elements in a ManyToMany relationship matches a condition. Here's some simplified models: Place(models.Model): name = models.CharField(max_length=100) Person(models.Model): type = models.CharField(max_length=1) place = models.ManyToManyField(Place, related_name="people") I tried to do this: c = Count(Q(people__type='V')) p = Places.objects.annotate(v_people=c) But this just makes the .v_people attribute count the number of People. -
Class based view that inherits from a custom class based view does not see context variables in parent
I have written a Class based view which acts as a base view for several other class based views. So the other class based views is just subclassing the base view, but the subclassed views are not getting the effect of the get_context_data or form_valid functions, so the context variables set in the base view is not getting sent to the template when requests are executing using the view subclassing the base view, they are only being sent when the base view itself it used. Class based view: class PortfolioNewBase(CreateView): url_name = '' post_req = False def form_valid(self, form): self.post_req = True return super(PortfolioNewBase, self).form_valid(form) def get_context_data(self, **kwargs): context = super(PortfolioNewBase, self).get_context_data(**kwargs) context['profile_id'] = self.kwargs['profile_id'] context['post_req'] = self.post_req return super(PortfolioNewBase, self).get_context_data(**kwargs) def get_success_url(self): return reverse(self.url_name, args=self.kwargs['profile_id']) When creating a new class based view which is one of the views that will be using this code it does not get access to the "profile_id" or "post_req" variables for some reason, it does not get sent to the template, but if you only use the base view written above that view will send the variables so that they are available in the view. Code for one of the class based views using … -
Django Display multiple Objects in template and Assign it
class Organization_Information(models.Model): Organization_name = models.CharField(max_length=25) Organization_address = models.CharField(max_length=40) Organization_admin = models.OneToOneField(MyUser, on_delete=models.CASCADE, null=True, blank=True) class Project(models.Model): project_name = models.CharField(max_length= 25, default='') project_description = models.CharField(max_length=50) Org_detiles = models.ForeignKey(Organization_Information, on_delete=models.CASCADE) class Asset(models.Model): asset_name = models.CharField(max_length=20, default='') project_name = models.ForeignKey('Project', on_delete=models.CASCADE) related = models.ManyToManyField(MyUser) class Finding(models.Model): finding_reference_to_asset = models.ForeignKey('Asset', on_delete=models.CASCADE) related = models.ManyToManyField(MyUser) finding_name = models.CharField(max_length=100, default='') recommendation = models.TextField(max_length=3000, default='') USER 'Organization_admin' Can View The Detiles of All the classes USER 'Researcher' Can View the Organization_Information and the ASSigned Asset then Submit Finding """ My View: """ def index(request): template = loader.get_template('home.html') context = { 'Organization_Information' : Organization_Information.objects.all(), 'Project' : Project.objects.all(), 'Asset' : Asset.objects.filter(model=Asset), } return HttpResponse() def home(request): form = Finding_Submit(request.POST) if form.is_valid(): form.save() return render(request, 'submit.html', {'form': form}) """ forms """ class Finding_Submit(ModelForm): class Meta: model = Finding fields = [ 'finding_reference_to_asset', 'finding_name', 'recommendation' ] """ My Template : """ {% extends 'base.html' %} {% block title %}HOME{% endblock %} {% block content %} {% if user.is_authenticated %} <html> <head> <title> Home </title> </head> <body> <cneter> <h4>{{ user.first_name }} {{ user.last_name }}</h4> <h4> 0rganization Information </h4> {{user.organization_information.Organization_name}}</h4> {{user.organization_information.Organization_address }} </h4> <h2>{{user.organization_information.Organization_admin}}</h2> <h2> Project </h2> {% with user.organization_information.project_set.get as orgo %} <h4> project name: {{ orgo.project_name }} </h4> <h4>{{orgo.project_description}}</h4> <h4> ASSET … -
if request.user.is_anonymous: - Else: is not working well
I'm creating a row in DB which have 2 different conditions, when there is no user logged in, and when a user is logged in I used if request.user.is_anonymous: [....] else: [....] But it only saves to DB when the 1st line is true which is if request.user.is_anonymous: but it never saves to DB when a user is logged in . def add_ad_mod(request): created_otp = uuid.uuid4().hex[:6].upper() current_user = request.user current_ip = get_client_ip(request) selected = Temp.objects.filter(created_by_ip=current_ip).order_by('-created_at')[0] selected_category = selected.cat classi = Category.objects.filter(category_name__icontains="Classifieds")[0] jobs = Category.objects.filter(category_name__icontains="Jobs")[0] if request.user.is_anonymous: if request.method == 'POST': add_ad_mod_form = AddAdModForm(request.POST, request.FILES, cat=selected_category) if add_ad_mod_form.is_valid(): model_instance = add_ad_mod_form.save(commit=False) model_instance.category = selected_category model_instance.post_otp = created_otp model_instance.save() add_ad_mod_form.save_m2m() current_email = model_instance.email send_mail( 'Activate your Ad on Jehlum', 'Use the code ' + created_otp + '.', 'test@jehlem.org', [model_instance.email], fail_silently=False, ) request.session['created_otp'] = created_otp # set 'student_id' in the session request.session['current_email'] = current_email # set 'student_id' in the session return redirect('post_confirm') else: add_ad_mod_form = AddAdModForm(cat=selected_category) else: if request.method == 'POST': add_ad_mod_form = AddAdModForm(request.POST, request.FILES, cat=selected_category) if add_ad_mod_form.is_valid(): model_instance = add_ad_mod_form.save(commit=False) model_instance.created_by = current_user.email model_instance.category = selected_category model_instance.email = current_user.email model_instance.post_otp = 0 if request.user.is_superuser: model_instance.is_active = True else: model_instance.is_active = False model_instance.save() add_ad_mod_form.save_m2m() return redirect('post_success') else: add_ad_mod_form = AddAdModForm(cat=selected_category) add_ad_mod_form = AddAdModForm(cat=selected_category) … -
Invalid HTTP_HOST header: '*.*.*.*:8000'. You may need to add '*.*.*.*' to ALLOWED_HOSTS
all. I have some problem. when i use django. when i run server as python3 manage.py runserver 0:8000. and I connect to my page. but it shows "Invalid HTTP_HOST header: '...:8000'. You may need to add '...' to ALLOWED_HOSTS." I already set the Allowed_hosts =['*'] in the settings.py. do you know what is problem? -
Django ManytoManyField add function not working.
I'm trying to add objects into a Django ManytoManyField as I create them. But for some reason after I call the add function when I try to print whats in that field I get none. This is the code where I am attempting to add objects into the field. new_recommendation = Recommendation.objects.create(recommender=sender, recomendee=reciever, relationship=relationship, recomendee_position=position) new_recommendation.save() for id in event_final_id: event = Event.objects.get(id=id) event.save() new_recommendation.recomendee_events.add(event) new_recommendation.save() This is the code for the class I am using. class Recommendation(models.Model): recommender = models.ForeignKey(StartupMember, related_name='recommender') recomendee = models.ForeignKey(StartupMember, related_name='recommendee') recommendation_text = models.TextField(max_length=500, default='') relationship = models.CharField(max_length=100) recomendee_position = models.ForeignKey(Experience, default=None) recomendee_events = models.ManyToManyField(Event, default=None) recomendee_ventures_projects = models.ManyToManyField(Startup, default=None) -
I am new to django i am not understanding class based views when we call {as_view ()} method in url pattern how the class methods are invoked
# urls.py from django.urls import path from myapp.views import MyView urlpatterns = [path('about/', MyView.as_view()] #views.py from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request): # return HttpResponse('result') -
Instance of 'DateTimeField' has no 'strftime' member
I was following a book "Django 2 By Example". But, stuck at here. I tried searching over the internet , but didn't get anything specific. The models.py >> from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=126) slug = models.SlugField(max_length=126, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_post', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES,default='draft') objects = models.Manager() #default manager published = PublishedManager() #custom manager class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blogposts:post_detail', args=[ self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug ]) This tutorial is following the doing the same. But i'm getting an error from pylint that E1101: Instance of 'DateTimeField' has no 'strftime' member What am i missing?