Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Python 'int' object is not subscriptable [on hold]
at my models.py i got a class named Post with and ImageField called postcover. I want to save every image in PNG format which is working fine so far but i have no idea how i could keep the actual image aspectio ratio after processing the image. with the following solution i get the following error: 'int' object is not subscriptable models.py def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) if self.postcover: if os.path.exists(self.postcover.path): imageTemproary = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 500 hpercent = (baseheight / float(self.postcover.size[1])) wsize = int((float(self.postcover.size[0]) * float(hpercent))) imageTemproaryResized = imageTemproary.resize((wsize, baseheight)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.postcover.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) super(Post, self).save(*args, **kwargs) Thanks for help in advance :) -
Django facebook AuthCanceled at /oauth/complete/facebook/
I've set up social-auth-app-django in production. But after facebook redirect I got AuthCanceled and still unable to get it work. In my user model email address used to sign up. This is my user model: class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) avatar = models.ImageField(blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] in settings.py: MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ ... 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'accounts.backends.ModelBackend' ) LOGIN_URL = '/' LOGOUT_URL = '/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) SOCIAL_AUTH_FACEBOOK_KEY = '..' # App ID SOCIAL_AUTH_FACEBOOK_SECRET = '...' # App Secret SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email', } Valid OAuth redirect URIs in facebook login app: https://example.com/oauth/complete/facebook/ Thank you for your time and help. -
NoReverseMatch at /cart/ while adding new item to the cart
I'm setting up a cart app following some tutorial but using my own settings. when I try to add an item or product to the cart it gives me NoReverseMatch at /cart/ Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. here's codes in my views file: @require_POST def cart_add(request, book_id): cart = Cart(request) book = get_object_or_404(Book, id=book_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=book, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('/cart/') def cart_remove(request, book_id): cart = Cart(request) book = get_object_or_404(Book, id=book_id) cart.remove(book) return redirect('/cart/') def cart_detail(request): cart = Cart(request) context = { 'cart': cart } for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', context) and for urls file: urlpatterns = [ path('', views.cart_detail, name='cart_detail'), path('add/<int:book_id>/', views.cart_add, name='cart_add'), path('remove/<int:book_id>/', views.cart_remove, name='cart_remove'), ] -
How to add a situational field to a Serializer?
I'm trying to figure out the best way to handle a situation where a model may have sensitive information that I only want the owner to be able to see. For example the store below: class Store(models.Model): owner = models.ForeignKey(Account, on_delete=models.DO_NOTHING) name = models.CharField(max_length=128) license= models.CharField(max_length=128) menu = models.ManyToManyField(Product) address = models.ForeignKey(Address, on_delete=models.DO_NOTHING, blank=True, null=True) class StoreSerializer(serializers.ModelSerializer): owner = AccountSerializer(read_only=True) menu = ProductSerializer(many=True, read_only=True) address = AddressSerializer(read_only=True) class Meta: model = Store fields = ('owner', 'name', 'menu', 'address', 'license') In this example I want all users to be able to find stores but the license field should only be available to CRUD if the user is the owner of this object. What is the optimal solution in this case? My options so far seem to be: A) Create a separate serializer for the owner type B) Turn license into a SerializerMethodField and provide it optionally from there I'm wondering which is the better practice and if there are other more elegant ways of doing this. -
I am trying to connect oracle 12c to django 2. for that i unlocked HR schema but when i run python manage.py migrate it gives me error
settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'orcl', 'USER': 'hr', 'PASSWORD':'hr@pdborcl', } } error: django.db.utils.DatabaseError: ORA-01017: invalid username/password; logon denied but I am able to login to DB using this username and password. -
My website doesnt load the correct css parameters
I'm developing a MOOC application using Django for the back-end and simple html for the front-end. I gave one updated on 'styles.css' to make the face of the site a little friendlier but he simply refuses to use the colors I've decreed. Here u can find my full app. An example, in the /core/templates/base.html file I created a div called footer: ... <div class="footer"> Tâmer MOOC - Uma simples plataforma de ensino a distância </div> ... So, I setup some configs in the /core/static/css/styles.css file, here is the footer stuff (Im really newbie in css so, maybe the error is obvious): .footer { background: #2d3e50; color: #fff; text-align: center; padding: 1em; font-size: 80%; } But when I run the server and go to the site, i see this Basically, the bg color was meant to be #2d3e50 and actually is #111 and the font color was meant to be #fff and actually is #666. And this is for all configs ive done, he refuses do reload the configs. The css settings being displayed are the old ones. -
How does running a test in PyCharm result in an "Model class doesn't declare an explicit app_label" error?
I'm using Django, Python 3.7, and PyCharm 2018.3.5. I'm trying to run a test in PyCharm by right-clicking on the test name and selecting, "Run Test: 'test name'". This results in the following error RuntimeError: Model class appname.models.Label doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. This is the model in question, at the top of my models.py file ... class Label(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Meta: unique_together = ("name",) What is very odd is if I run the tests outside of PyCharm (e.g. at a terminal command prompt using "python manage.py test"), everything runs fine. So the problem would seem to be some misconfiguration with PyCharm. I'm unclear how to attack the problem further. Below is my project directory structure ... appname __init__.py __pycache__ admin.py apps.py fixtures management migrations models.py services.py static templates tests.py views.py manage.py templates venv appname_project -
Getting list of choices for a django model field to a vue.js frontend
I am using django restframework on the backend to create an API which I access from the frontend using vue.js. I have a 'Post' model that stores text and also has a field 'privacy_settings'. I have defined the privacy setting field as follows: What is the best way to retrieve the options/choices on the frontend when creating a new post? ONLYME = 'ME' FRIENDS = 'FR' PUBLIC = 'PU' POST_PRIVACY_CHOICES = ( (ONLYME, 'Onlyme'), (FRIENDS, 'Friends'), (PUBLIC, 'Public'), ) privacy_setting = models.CharField( max_length = 2, choices = POST_PRIVACY_CHOICES, default = ONLYME ) -
Why should we create Model fields in Django for MongoDB?
I have worked on RDBMS with Django. I'm familiar with Models, Model fields in Django. We are looking for a better way of storing large documents in database. We came across MongoDB and found that the collections in MongoDB doesn't have a schema to store documents. But I found plenty of tutorials where they mention Model fields when working with MongoDB in Django. I searched a lot for this but couldn't find why they are still mentioning model fields in Models in Django. Why are we still creating Model fields (columns) when there is no specific schema for MongoDB collection? -
Trying to set up follower functionality 'User' object has no attribute 'following' error
I have created the following model to implement a follower functionality. I then am using the shell to test the model I have run user1=User.objects.get(username='username1') user2=User.objects.get(username='username2') and then user1.following.add(user2) However I still get the following error AttributeError: 'User' object has no attribute 'following' Any help would be greatly appreciated. Very new to django class MyUser(models.Model): user = models.ForeignKey(User,on_delete=models.PROTECT) name = models.CharField(max_length=100, blank=True) following = models.ManyToManyField('self', related_name='followers', symmetrical=False, blank=True, null=True) def __unicode__(self): return self.name -
how to read PDF from in memory uploaded file python 3.6
I am trying to read a PDF file , i am uploading it using the following code: for file in request.FILES.getlist('the_file') : fp=tempfile.TemporaryFile() uploadedFile=file I understand the PyPDF2 doesn't support in memory uploaded file , tried several solutions i saw ,but couldn't solve the problem. Will appreciate any help. Thanks, Nir -
Django 2.2 breaks previously working views/urls
Decided to take out Django 2.2 for a spin (project is currently running 2.1.8) and now I can't even get the server to start. I have been maintaining this project for nearly two years and this should be a minor update. The error seems to be related to my views, but I can't find anything in the release notes that has meaningfully changed between 2.1.8 and 2.2. I suspect it may be due to my rather non-standard view system. Instead of a single file called views.py, I use a folder of view files joined by an __init__.py. But again, that's just a guess as the error message does little to point me to my problem. Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "C:\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Python37\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Python37\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python37\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Python37\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() … -
Django: production app on Heroku cant find templates with "path" urlpattern
I´m having my production site on Heroku. The app can find templates defined with url in the urlpatterns of the urls.py file. Like: url(r'^contactreport/$', views.ContactosView, name="contactos"), But not the ones defined with path. Like: path('inventario/', views.InventarioView, name="inventario"), Settings This is my static folder config in settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") This is my middleware (but I think it´s not the problem). MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Any clues welcome. Thanks in advance! -
How correctly set Media files URL for deploying in Django-Rest-Framework
For connecting my idnex.html of React Build folder and Django-Rest-Framework I set re_path in my general urls.py file. urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('userauth.urls')), path('api/', include ('articles.api.urls')), re_path('.*', TemplateView.as_view(template_name='index.html')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here is the settings.py file where I set the storage of media and static files: MEDIA_ROOT = os.path.join(BASE_DIR, 'media_files') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_files') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' The browser does not show images I think the server try to find the URLs of media files among the react-route URLs If I deploy the project without re-path(.....) the server show the standard DRF page and it seems to be the URLs of media files work fine. Please any help ,if you need more information about code I can post it. Thank you in advance. -
How to manage writable nested serializers with multiple serializers in an unique field?
I'm working on django rest framework with nested serializers and i need support on how to POST an object that can take different type of models. A good sketch is better than a long speech I want to post this: { "md5": "365v4a9e8fv4s9efb8", "computer": "computer_name", "branch": "git_branch", "planKey": "Key", "buildNumber": 25, "pullRequest": false, "result": [ { "name": "name of the app", "project": "name of project", "mode": "release" ... }, { "name": "name of the app", "project": "name of project", "mode": "release" ... } ] } Or this: { "md5": "365v4a9e8fv4s9efb8", "computer": "computer_name", "branch": "git_branch", "planKey": "Key", "buildNumber": 25, "pullRequest": false, "result": [ { "name": "name of the test", "status": "fail", "test_suite": "BB" ... }, { "name": "name of the test", "status": "pass", "test_suite": "AA" ... } ] } In both case, i want the same first top level model that is JobResult. But for the result field i want to be able to give the first model (Build) or the second one (Test) models.py: class JobResult(models.Model): md5 = models.CharField(max_length=255, default=None) computer = models.CharField(max_length=255) branch = models.CharField(max_length=255) planKey = models.CharField(max_length=255) buildNumber = models.IntegerField() pullRequest = models.BooleanField(default=False) # Generic Relation between JobResult and (Daily or Test) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, related_name='result', … -
How to allow user to modify only his data in Django Rest Framework
i'm building simple API with Django 2.1.8 and provide security with Django OAuth Toolkit. I've reached the point where user can use api only after authorization but i want to limit his acctions only to his data. I've built authorization using oauth2 which returns me access token. models.py class Client(AbstractUser): email = models.EmailField( verbose_name='email adress', max_length= 255, unique=True, ) location = models.CharField(max_length=500, default="") is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = ClientManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['location'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin views.py class SingleClientView(generics.RetrieveAPIView): queryset = Client.objects.all() serializer_class = ClientSerializer permission_classes = [IsAuthenticated, TokenHasReadWriteScope] Is there any possibility to connect returned token with user model, so every time someone would use API it filter if user matches required data? Or does oauth toolkit automatically and how to acces it? -
Creating SuperUser on a custom database (not default)
I am currently working on a multi-tenant django application. Since the requirement of multi-tenancy, for starters, I have created a second database. However, I am unable to create a SuperUser in the newly created database. I did try the answer listed Django fails to create superuser in other db than 'default' However, no luck. Getting the following output on compile: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly co nfigured. Please supply the ENGINE value. Check settings documentation for more details. Settings.py DATABASES = { 'default': {}, 'Alora': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Alora', 'USER': 'postgres', 'PASSWORD': 'somepassword', } } Python Version C:\Users\User>python --version Python 3.6.3 Django Version C:\Users\User>django-admin --version 2.2 Tried python manage.py createsuperuser --database=Alora. Received the error stated above. Any help is deeply appreciated. Thanks! -
Using Amazon S3 to save static files with Django. Collecstatic does not upload files to S3
I'm developing a project for my university and I'm using Django and Heroku. But, Heroku doesn't save my static files and for that reason I was recommended to use Amazon S3 to store static files and upload some pdf I generate. I'm tried to make my application upload all the static files using collectstatic but every time they are generated inside the staticfiles folder in my project and I want them to be uploaded to S3. I tried to follow some guides like: https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html https://testdriven.io/blog/storing-django-static-and-media-files-on-amazon-s3/ https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media- Tried all the possible ways to configure the settings file but nothing is working. This is how the settings.py files is: AWS_ACCESS_KEY_ID = 'Access key' AWS_SECRET_ACCESS_KEY = 'secret access key' AWS_STORAGE_BUCKET_NAME = 'name of the bucket' AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' This is my installed apps. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', "bootstrap4", ] I also installed the boto3 and django-storages libraries When I do collectstatic the result is: You have requested to collect static files at the destination location as specified in your settings: … -
django forms fields are not visible. but button is there. And when i click button, form is visible. help me
form is not visible in template. only button is there. But when I click button, the form is visible with validation warning 'field is required'. template <form action="{% url 'online:message_create' %}" id="contact_form" class="contact_form" method="post"> {% csrf_token %} {{ form|crispy }} <button type='submit' class="button contact_button" name="button"><span>Send Message</span></button> </form> views.py class MessageCreate(CreateView): model = Message form_class = MessageForm template_name = 'contact.html' success_url = reverse_lazy('online:home') forms.py class MessageForm(forms.ModelForm): class Meta: model = Message fields = ['name', 'subject', 'message'] -
How to fix AttributeError: 'NoneType' object has no attribute 'id' and self.assertEqual(Item.objects.count(), 1) AssertionError: 0 != 1
I've managed to go up to chapter five of the book Test-Driven Development in Python. I'd like some help to point me in the right direction to solve two errors. I have looked into all the threads of the same errors on Google. But explanations differ from my test case. So I struggle to understand what's wrong with the code below. I understand that the self.assertEqual(Item.objects.count(), 1) AssertionError: 0 != 1 tells me 'id' is not defined. But I don't know where to fix that in Django. Also for self.assertEqual(Item.objects.count(), 1) AssertionError: 0 != 1, I don't know where to look. (sup) ben@ben:~/sup1/superlists$ sudo python3 manage.py test lists Creating test database for alias 'default'... System check identified no issues (0 silenced). .........FE ERROR: test_redirects_after_POST (lists.tests.NewListTest) Traceback (most recent call last): File "/home/tim/sup1/superlists/lists/tests.py", line 93, in test_redirects_after_POST self.assertRedirects(response, f'/lists/{new_list.id}/') AttributeError: 'NoneType' object has no attribute 'id' ====================================================================== FAIL: test_can_save_a_POST_request (lists.tests.NewListTest) Traceback (most recent call last): File "/home/tim/sup1/superlists/lists/tests.py", line 87, in test_can_save_a_POST_request self.assertEqual(Item.objects.count(), 1) AssertionError: 0 != 1 MODELS.PY from django.db import models class List(models.Model): pass class Item(models.Model): text = models.TextField(default='') list = models.ForeignKey(List, default='', null=True, blank=True, on_delete = models.CASCADE) TESTS.PY from django.template.loader import render_to_string from django.urls import resolve, reverse_lazy from django.test … -
Static images not getting displayed
Created a new variable in STATIC_DIR and assigned it os.path.join(BASE_DIR, 'static') and assigned STATIC_DIR to STATICFILES_DIR as a list element.Saved an image in static/images directory.Link to the image is given as . after all this only the alt is displayed, but not the image. Please help. -
FieldError with custom filter on calculated field in admin
I am trying to use a custom filter for a calculated field in admin. I followed the documentation and some other examples and getting this error: Cannot resolve keyword 'kit_frequency' into field. Where did I go wrong? class KitFrequencyFilter(admin.SimpleListFilter): title = 'Frequency' parameter_name = 'kit_frequency' def lookups(self, request, model_admin): return ( ('Monthly', 'Monthly'), ('Bi-Monthly', 'Bi-Monthly'), ('Quarterly', 'Quarterly'), ) def queryset(self, request, queryset): value = self.value() if value == 'Monthly': return queryset.filter(kit_frequency='Monthly') if value == 'Bi-Monthly': return queryset.filter(kit_frequency='Bi-Monthly') if value == 'Quarterly': return queryset.filter(kit_frequency='Quarterly') return queryset @admin.register(Contact) class ContactAdmin(ImportExportModelAdmin): resource_class = ContactImportResource list_display = ('full_name','program_code','kit_frequency','author','first_name1', 'last_name1', 'first_name2','last_name2','address1','city','province','postal_code','active_status') list_filter = ['program_code','author', KitFrequencyFilter] (simplified) Model: class Contact(models.Model): first_name1 = models.CharField(max_length=100, verbose_name='First Name') last_name1 = models.CharField(max_length=100, verbose_name='Last Name', blank=True) etc... def get_kit_frequency(self): from programs.models import Program kit_frequency = Program.objects.get(program_code=self.program_code).kit_frequency return kit_frequency -
How do I reference the "many" of "one-to-many" relationships in Django/Python?
I'm using Python 3.7 and Django. I have the below two models ... class Article(models.Model): title = models.TextField(default='', null=False) class ArticleStat(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats') elapsed_time_in_seconds = models.IntegerField(default=0, null=False) ... class Meta: unique_together = ('article', "elapsed_time_in_seconds",) Note that an article has multiple ArticleStat objects. If I have an "article" object somewhere in my code, how do I reference its ArticleStat object with the greatest elapsed_time_in_seconds? Even doing article.articlestats results in an error so I don't even know how to reference the related ArticleStat objects from my initial object. -
Rendering HTML when request comes from browser or sending JSON dictionary when request comes from mobile
I'm trying to build a backend for an app that has both a web frontend (designed with bootstrap) and a mobile frontend (designed with Flutter). I've been trying to understand the documentation for Django REST Framework about renderers, but I can't figure out how to deal with different types of requests (one from web and one from mobile, for example) without having two different functions for both platforms. Is there a better way to do this than having a flag passed through the request that says whether the app is mobile or web, and returning a Response object or render object depending on that flag's value? -
remove images from media folder after deleting blog post
When I delete a post from my Django blog the post is successfully removed but any images associated with the post remain in my media folder. How do I ensure these are also deleted? Here are my files: models.py class News(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) thumb = models.ImageField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('news_detail', args=[str(self.id)]) views.py class NewsDeleteView(LoginRequiredMixin, DeleteView): model = News template_name = 'news_delete.html' success_url = reverse_lazy('news_list') login_url = 'login' def test_func(self): obj = self.get_object() return obj.author == self.request.user news_delete.html {% extends 'base.html' %} {% block content %} <h1>Delete</h1> <form action="" method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ news.title }}"?</p> <button class="btn btn-danger ml-2" type="submit">Confirm</button> </form> {% endblock content %}