Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM with Rest API writing complex query
I wrote a functionality like if a person have related data, user cant perform update. Here you go for my models: class Person(models.Model): alias = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=20) class Appointment(models.Model): patient = models.ForeignKey(Person, related_name="patient_for_appointment", on_delete=models.CASCADE) data = models.CharField(max_length=20) class Sales(models.Model): customer = models.ForeignKey(Person, related_name="customer_for_sales", on_delete=models.CASCADE) amount = models.FloatField() class Prescription(models.Model): patient = models.ForeignKey(Person, related_name="Patient_for_prescription", on_delete=models.CASCADE) details = models.CharField(max_length=100) My primary key is UUID named alias this is my api view: from django.shortcuts import render from . models import Person, Appointment, Prescription, Sales from . serializers import PersonSerializers from rest_framework.generics import RetrieveUpdateDestroyAPIView from rest_framework.response import Response from rest_framework.exceptions import APIException class PersonView(RetrieveUpdateDestroyAPIView): queryset = Person.objects.all() serializer_class = PersonSerializers lookup_field = 'alias' def update(self, request, *args, **kwargs): # person = Person.objects.filter(alias=kwargs['alias']) appointment = Appointment.objects.filter(patient__alias=kwargs['alias']) prescription = Prescription.objects.filter(patient__alias=kwargs['alias']) sales = Sales.objects.filter(customer__alias=kwargs['alias']) partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if prescription: raise APIException('CANT UPDATE') elif appointment: raise APIException('CANT UPDATE') elif sales: raise APIException('CANT UPDATE') else: self.perform_update(serializer) return Response(serializer.data) Look closely above view some query: appointment = Appointment.objects.filter(patient__alias=kwargs['alias']) prescription = Prescription.objects.filter(patient__alias=kwargs['alias']) sales = Sales.objects.filter(customer__alias=kwargs['alias']) I implement here if a Person have sales or appointment or prescription, user can't to perform update and throw an error. Everything … -
reverse relationship serializer in not returning field in json response
I have this models: class User(AbstractUser): username_validator = CustomUnicodeUsernameValidator username = models.CharField( _('username'), max_length=20, unique=True, help_text=_('Required. 15 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) email = models.EmailField( _('email address'), unique=True, null=False, blank=False, error_messages={ 'unique': _("A user with that email already exists."), }, ) And a Profile model which extends the previous model with personal user information: class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, primary_key=True, parent_link=True, related_name='profiles', related_query_name='profile', on_delete=models.CASCADE ) bio = models.CharField( max_length=100, null=True, blank=True ) birth_date = models.DateField( null=True, blank=True ) avatar_url = models.CharField( max_length=100, null=True, blank=True ) cover_url = models.CharField( max_length=100, null=True, blank=True ) These are my serializers: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = get_user_model() fields = [ 'email', 'username', 'password', 'first_name', 'last_name', ] extra_kwargs = { 'password': {'write_only': True} } And for profile: class ProfileSerializer(serializers.HyperlinkedModelSerializer): profiles = UserSerializer( many=False, read_only=True ) class Meta: model = Profile depth = 1 fields = [ 'url', 'avatar_url', 'bio', 'birth_date', 'cover_url', 'profiles' ] I'm trying to get a response like the following when sending a GET request from http://localhost:8000/profiles/1/ : { "user": { "url": "http://www.tribsport.com:8000/users/1/", "username": "cthulhu", "email": "cthulhu@gmail.com", }, "url": "http://www.tribsport.com:8000/v1/profiles/1/", "avatarUrl": "assets/images/avatars/rick.jpeg", "bio": "Hincha de River Plate!", … -
MySQL or NoSql? What should I use for a custom "User" model
So I'm building a django-rest project for fun, I decided to use a NoSQL with the help of mongoengine (ODM for django) just to see how things will work out. My site will be like a marketplace mainly for trading music instruments. So I defined two models, one for the User and one for the Gear, the Gear model has a field of "owner" which references to the User model, while the user model has the field of "gears" which lists the posted gears he have for trading/selling. (Btw, in mongoengine, we define models as documents) I'm blocked by this specific question. How should I approach my custom "User" model? Should I store it in a relational database or it's fine to store it to a nosql? I already researched and saw that I'll lose most of django power just using a nosql (as expected) and also that storing a "User" model in a nosql is a bad idea as it is "relational". How can I know if my data is relational or not and if it's a great idea to store it into a relational db or not? I can't seem to wrap my mind with other explanations out … -
How to call a model method in views.py
I have a Post model with a custom model method that sets a post status to "DELETED" rather than actually deleting the Post object: STATUS_DRAFT = 0 STATUS_PUBLISHED = 1 STATUS_DELETED = 2 STATUS_CHOICES = ( (STATUS_DRAFT, 'draft'), (STATUS_PUBLISHED, 'published'), (STATUS_DELETED, 'deleted'), ) class Post(models.Model): title = models.CharField(max_length=30) status = IntegerField(choices=STATUS_CHOICES, default=STATUS_DRAFT) def retire(self): self.status = STATUS_DELETED self.save() pass I am using Generic Edit Views to handle my posts: class PostDeleteView(DeleteView): model = Post success_url = reverse_lazy('delete_post_success') I want to customise the delete method to instead call the retire method in my Post model: def delete(self, request, *args, **kwargs): """ Call the retire() method on the fetched object and then redirect to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.retire() return HttpResponseRedirect(success_url) However this syntax is incorrect (it does not change the Post.status) Where am I going wrong? -
What is a better way to query a ManyToManyField for speed? entire object or id only?
I'm trying to determine the most efficient way to query a ManyToManyField for speed. I have 2 options that I know of: Add the entire object to the field Add just the id to the field If I add the object, obviously with on_delete=models.CASCADE, I get that benefit, which is huge, but I'm afraid adding it might slow query speed down because it's getting an entire object, and many of them at that. Whereas with just the id, it's just an int, so less heavy, and faster I assume. For speed only, what would you suggest? -
Access HTTP_REFERER in django Generic Views
I want to pass the previous URL in a context variable for a generic view: class PostDeleteView(DeleteView, LoginRequiredMixin): previous_url = self.request.META.get('HTTP_REFERER') ... However, I can't access either self or request. How do I go about this? -
Using category slug in url rather than pk
Right now I am able to show a product detail page by going to example.com/products/1 However I would like to be able to go example.com/<category_slug>/<product_slug> views.py def product_detail(request, pk): product = Product.objects.get(pk=pk) return render(request, 'main/product_detail.html', {'product': product}) root urls.py from main.views import product_detail path('products/<int:pk>/', product_detail, name='product-detail'), -
Use POST method to get the text of a h7 tag using Django
I am using Ajax and a POST method to store a data. To validate the data I need to take some information from a h7 tag as shown in the next code. I defined a class and an id for the h7, but the output is None instead of the h7 tag value. HTML Code: <form class= "login_assignment" method="POST" id = "log_ass"> {% csrf_token %} <br> <label><b>Name:</b></label> <h7 class = 'name'></h7> <br> <label><b>Last Name:</b></label> <h7 class = 'last_name'></h7> <br> <label><b>ID:</b></label> <h7 class = 'id_number' id = 'id_number'> </h7> <br> <label><b>Mail</b></label> <h7 class = 'mail'></h7> <br> <label><b>Login Type</b></label> <h7 class = 'login'></h7> <br> <input id = "modify" type="submit" value="Modify"> </form> Ajax Code: $(document).ready(function(){ var $regform = $(".login_assignment") $regform.submit(function(event){ var $formData = $("#log_ass").serialize() event.preventDefault() var $endpoint = window.location.href $.ajax({ method: "POST", url: '/user_login_assignment/', dataType: 'json', data: $formData, success: function(data){ if (data == 'modified') { alert('The user access have been modified'); URL Code: path('user_login_assignment/', views.user_login_assignment, name = 'user_login_assignment') View Code: def user_login_assignment(request): if request.method == 'POST': id_parameter = request.POST.get('id_number') print(id_parameter) return JsonResponse('modified', safe = False) Although the h7 tag looks empty, it actually receive information from an Ajax function, and once it received the text from the ajax function. the user press an … -
What's better to export pdf's in django python functions or Javascript ones?
I have an app where users may want to export a pdf of 1 page/view so when i searched i saw 2 approaches one is to make a button triggers a javascript function and the other is to make a view and make a button that triggers that view. So what's the best approach and why should i choose it? And is there a way that I can Inject extra HTML elements when printed as extra information pulled from the DB and Date/time to be present in the document? -
In the Wagtail how to limit what values are shown in the ManyToManyFields?
I want to limit the number of the users displayed in the ManyToManyField in the Wagtail admin. In the django version of the ModelAdmin it was enough to implement the following: def users_queryset(queryset, field="users"): if queryset and field == "users": queryset = queryset.filter(...) return queryset @django_admin.register(Partner) class PartnerAdmin(django_admin.ModelAdmin): ... def get_field_queryset(self, db, db_field, request): queryset = super().get_field_queryset(db, db_field, request) return users_queryset(queryset, db_field.name) Is there a way in the Wagtail to limit what values are shown in the ManyToManyFields? -
large jquery datatables are slow with django
I am displaying a 20k row jquery datatable through django. It is very slow to render. So I am wondering what could be the alternative approaches to process it faster e.g., through defer rendering, to load only the parts that are displayed? The database is in sql. I tried defer rendering and serverSide options in datatable options but it is still very slow. I understand that those options work only when the data is called through AJAX. The examples given in datatables website are just dumps of AJAX data into predefined columns. In my case, I am using the data as argument to generate links and create icons etc. Here is the code: <div class="container col-9 pb-5 mb-5"> <table id="drugstable" class="table table-hover" style="width: 100%"> <thead> <tr> <th scope="col">#</th> <th scope="col">Drug</th> <th scope="col">Tool</th> <th scope="col">netZoo release</th> <th scope="col">Network</th> <th scope="col">PPI <i class="far fa-question-circle" data-toggle="popover" data-trigger="hover" data-placement="top" title="Data sources" data-content="Directly download the PPI prior used for the generation of the network and check the link to the o> </i></th> <th scope="col">Motif</th> <th scope="col">Expression</th> <th scope="col">TFs</th> <th scope="col">Genes</th> <th scope="col">Reference</th> </tr> </thead> <tbody> {% for drug in drugs %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><a href="{{ drug.drugLink }}">{{ drug.drug }}</a></td> <td>{{ drug.tool }}</td> … -
How to have medium like text selector and highlighter using Django?
Medium allows users to arbitrarily select text and highlight them. How do I do that with Django? -
Selenium .click() on link doesn't give the right address
I'm testing a page. I'm writing a functional test and I want to click on a link using Selenium. The link is working (if I click on it by myself). The address should be http://127.0.0.1:8000/lists/addname/ but when selenium click on it go to http://localhost:63286/lists/addname/lists/addname/ and ofcourse it doesn't find the page (63286 is a number always different but shouldn't be the problem, if I click on the link before it does (using time.sleep, for example) I go to the page http://localhost:63286/lists/addname and it works). I'm not expert so maybe it's a trivial error and I don't know what code can be relevant, so tell me if you have to know more. My functional_tests.py: def test_can_add_name_and_read_it_after(self): # Bob go to the homepage self.browser.get(self.live_server_url) # He notice the title in header is Home self.assertIn('Home', self.browser.title) # He finds and clicks the link on the sidebar for the addname page element = self.browser.find_element_by_link_text('Add Name') # element = self.browser.find_element_by_xpath('/html/body/div/div[1]/nav/div/ul/li[2]/a') # this gives the same problem time.sleep(1) element.click() In my template.html the link appear two time but that shouldn't be the problem: <div class="navbar"> <a class="nav-link" href="{% url 'lists:addname' %}">{% trans "Add Name" %}</a> </div> [...] <div class="sidebar"> <a class="nav-link" href="{% url 'lists:addname' %}">{% trans … -
Model name not visible in html
I have some problem wyth my django project. If i am not using "custom name" of my char field - its working: models.py: class Event(models.Model): name = models.CharField(max_length=50) forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ('name') event_detail.html {% extends 'base.html' %} {% block content %} <h2>{{ object.name}}</h2> {% endblock %} But if I try to use some 'custom name' like below, I cant see this field "custom_name". models.py: class Event(models.Model): name = models.CharField(max_length=50, name='custom_name') forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ('custom_name') event_detail.html {% extends 'base.html' %} {% block content %} <h2>{{ object.name}}</h2> {% endblock %} What is the problem? -
Image filed is not returning images in Post request Django
hi I am using this structure to upload a image . I want to use a small image saying to attach a image instead of Upload File button . When I display:none to input filed It dosen't return any image in return in post request. when I normally use this <input type="file" name="img" multiple> its returning image in request.Files <div class="image-upload"> <label for="file-up"> <img src="{% static 'MainApp/img/attachment-clip.png' %}"/> </label> <div id="img-file-upload-up" class="post-Attach-Img-file m-1"> <input onchange="showFiles_up(this.files)" type="file" id="file-up" multiple name="images" accept="image/*" style="display:none"/> </div> -
How to filter users in the queryset by the group to which they belong to?
I have a queryset with the users: <QuerySet [<User: usr0>, <User: usr1>]> I know that I can verify if the user belongs to the group like so: In [18]: usr1 = queryset[1] In [19]: usr1.groups.filter(name='Partners').exists() Out[19]: True How can I filter out all the users from the queryset which do not belong to the custom group(s)? -
Error saving model in Django Admin with many FK objects pointing to it
Using Django==2.2.4 Example of the problem using fake models, in a fake parties Django app: class CakeModel(models.Model): . . . class CandleModel(models.Model): . . . cake = models.ForeignKey( 'parties.CakeModel', related_name='candles', on_delete=models.SET_NULL, ) . . . The Django admin page: class CandleModelAdmin(admin.ModelAdmin): model = models.CandleModel extra = 0 fields = [..., some_field, ...] def get_queryset(self, request): '''Override to display less items in the admin page''' qs = super().get_queryset(request) # exclude some items from the QuerySet return limited_qs @admin.register(models.CakeModel) class CakeModelAdmin(admin.ModelAdmin): list_select_related = True inlines = (..., CandleModelAdmin, ...) list_display = (..., some_field, ...) There is no issue when a CakeModel has few CandleModel pointing to it. I have a few that have about 700, and I am testing with fake 1000. Whenever I save the page, it will take forever to save (30+ seconds) and sometimes timeout and display an error page. What can I do to prevent the CakeModel admin page from erroring out when edit a CakeModel field, and click "save" or "save and continue editing"? I might need to add another CandleModel as well, or edit a CandleModel. I tried overriding save_model(), save_related(), response_change(), but not sure how to proceed. Thank you! -
Django extending user model with a onetoone, but have several model.py files in applications
I have a django project with many applications in it, each one has models.py for pieces that are related to that portion of the project (The specific application) though I am using django's model login and user auth but I need more data with that, I saw here: https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#custom-permissions That there is a way to create another model that has the extra information and make it a onetoone to the user. The thing is, this extra data I need available to all my other applications, so what models.py do I stuff this new table to be built? -
install psycopg2 failing python 3.7
I am following this tutorial - https://medium.com/@qazi/how-to-deploy-a-django-app-to-heroku-in-2018-the-easy-way-48a528d97f9c so far I've: built my Django app and ran locally - works perfectly wrote Procfile with content web: gunicorn project_name.wsgi imported django_heroku to settings I need to install psycopg2 so I ran pip install psycopg2 but getting the error Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/niamhtohill/ios_dev/vf_api/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/kk/0xnrjqj950qdky6pkv1dws4r0000gn/T/pip-install-q5q1ago2/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/kk/0xnrjqj950qdky6pkv1dws4r0000gn/T/pip-install-q5q1ago2/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/kk/0xnrjqj950qdky6pkv1dws4r0000gn/T/pip-wheel-3u2cfbpc --python-tag cp37 cwd: /private/var/folders/kk/0xnrjqj950qdky6pkv1dws4r0000gn/T/pip-install-q5q1ago2/psycopg2/ Complete output (144 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_json.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extras.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/compat.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errorcodes.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/tz.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_range.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_ipaddress.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_lru_cache.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extensions.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errors.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/sql.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/pool.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.macosx-10.9-x86_64-3.7 creating build/temp.macosx-10.9-x86_64-3.7/psycopg gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.3 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=100005 -DHAVE_LO64=1 -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -I. -I/usr/local/Cellar/postgresql/10.5/include -I/usr/local/Cellar/postgresql/10.5/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-x86_64-3.7/psycopg/psycopgmodule.o gcc -Wno-unused-result … -
Django - read raw custom field from db without calling to_python
I have written my own CustomField for Django called JsonField. This field is stored as TextField in the DB, but when loaded to python it is loaded using json.loads inside to_python and from_db_value. Sometimes I want to read the value from the DB and instead of deserializing it, get the raw str (e.g when I just want to read this str and immediately serialize it back to some file). Is it possible to make Django avoid calling to_python and just let me use it directly? -
Save data to another table in Django
I have two Django projects and I need to use users table from first project in second project. The problem is I don't know how to save users data (address foreign key) in second project to first projects database. Already added two databases in settings.py: DATABASE_ROUTERS = ('users.dbrouters.UsersDBRouter',) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'first', 'USER': ..., 'PASSWORD': ..., 'HOST': 'localhost', 'PORT': 5432, }, 'users': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'second', 'USER': ..., 'PASSWORD': ..., 'HOST': 'localhost', 'PORT': 5432, }, } and routing: from .models import User class UsersDBRouter(object): def db_for_read(self, model, **hints): if model == User: return 'users' return None def db_for_write(self, model, **hints): if model == User: return 'users' return None def allow_relation(self, obj1, obj2, **hints): return True In SECOND project to save user data in users app views: class ProfileView(TemplateView): template_name = 'users/profile.html' def get_object(self, queryset=None): obj = self.request.user return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['states'] = State.objects.all().order_by('name') # I think it's better to import this context from first database context['streets'] = Street.objects.all().order_by('name') # same return context def post(self, request, *args, **kwargs): user = self.request.user user.last_name = request.POST.get('last_name') user.first_name = request.POST.get('first_name') user.address = Address.objects.get_or_create( state=State.objects.get(pk=request.POST.get('state')), street=Street.objects.get(pk=request.POST.get('street')))[0] user.save() return redirect('users:profile') I need something like Address.objects.using('users').get_or_create … -
Is it possible to get display name from inside concat in Django?
So let's say I have this Model: class Cable(models.Model): id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) type = models.IntegerField(choices=choices.cableTypes, default=1) notes = models.TextField(blank=True) length = models.DecimalField(decimal_places=2, max_digits=6) objects = CableQuerySet().as_manager() def __str__(self): return str(self.get_type_display()) + " Cable, " + str(self.length) + "m" I need to be able to pull results from the database using the __str__, and that has proven to not be possible. So instead, I was advised to use .annotate() with Concat() to achieve the same result. My problem is that I need the display name of Cable.type and not the value, or I need to be able to use the value of type as the key, and search the choices with that to then return the proper value. Is it possible to get display name from inside concat, or is there something that I can do that provides a similair outcome? -
Setting a value for when value isn't present
Using request.POST.get you can do this: token = request.POST.get('token', False) Is there a way to do the same thing using request.data['token'] -
How do you add parens to a CheckConstraint in Django
The following constraint: models.CheckConstraint(name='approved_by_someone', check=(models.Q(approved_at__isnull=True) | (models.Q(approved_by__isnull=False) & models.Q(approved_at__isnull=False)))) Generates a postgres constraint that looks like this: Check constraints: "approved_by_someone" CHECK (approved_at IS NULL OR approved_by_id IS NOT NULL AND approved_at IS NOT NULL) The parens in my python code disappear when converted into a sql constraint. My first thoughts were, OK, I can put those back by adding a models.Q around the AND condition: models.CheckConstraint(name='approved_by_someone', check=(models.Q(approved_at__isnull=True) | models.Q(models.Q(approved_by__isnull=False) & models.Q(approved_at__isnull=False)))) But still, NO the constraint is unchanged. -
NOT NULL constraint failed: articles_comment.article_id
I am following a tutorial where i build a newspaper app. So far so good but know I'm trying too add a comments section. If I add the comment true the admin in django i can see the comment and delete and update the comment on my site. But when i want too add a comment on the site I get the following error: NOT NULL constraint failed: articles_comment.article_id. Can somebody tell me what I'm doing wrong? This is my models.py from django.db import models from django.conf import settings from django.contrib.auth import get_user_model from django.urls import reverse class Article(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) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments',) comment = models.TextField() author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return self.comment def get_absolute_url(self): return reverse('comment_detail',) This is my views.py from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import Article, Comment class ArticleListView(ListView): model = Article template_name = 'article_list.html' class ArticleDetailView(LoginRequiredMixin, DetailView): model = Article template_name = 'article_detail.html' login_url = 'login' class ArticleUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): …