Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I implement five star rating in Django DetailView?
I'm currently working on a restaurant review site and I'm struggling with displaying a five star rating comment form in a class based DetailView page. How do I implement a five star rating system for my class based RestarurantDetail page? I would like to change the appearence on my Integerfield "rate" to a five star rating field. I would still like to display all other fields in the comment form as normal, perhaps with crispy forms (but it's perhaps not possible if I want to customize the rate field?) If you need aditional information, just let me know! Code Restaurant Model (parts of it) in Models.py class Restaurant(models.Model): name = models.CharField(max_length = 100) country = models.CharField(max_length = 75) city = models.CharField(max_length = 75) address = models.CharField(max_length = 100) categori = models.ManyToManyField(Kategori) description = models.CharField(max_length = 300, blank=True) approved = models.BooleanField(default=False) geom = PointField(null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: unique_together = ('country', 'city', 'adress') Comment Model in Models.py class Comment(models.Model): ALTERNATIVES_1 = ( ('Alt 1', 'Alt 1'), ('Alt 2', 'Alt 2'), ('Alt 3', 'Alt 3'), ) restaurant = models.ForeignKey(Restaurant, on_delete = models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 50, blank = … -
Django static folder with css and javascript wont load
Hey I have a problem with the static files directory in Django, Inside the html template I already used the {% load static %} above the link tag and in the link tag I used href="{% static 'style.css' %}" (keep in mind the style.css is in the static folder which is located in the projects root folder (after several times "still not working" I even created the same static folder with the same css file in the respective app folder... and still not working). In the settings.py I used all of the following lines one at a time and even all together STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/static") STATIC_DIRS = ( '/static', ) the html renders perfectly fine and is showing in the browser without any errors but for whatever reason the styling just wont apply (internal and inline sytling works, but I want to use external css). There seems to be a problem in the settings.py file but since I gave the path to the static folder in any way possible, I really don't know what to do. I didnt try with .js files yet but it'll be the same problem I guess. I'm thankfull for any answer. -
ImproperlyConfigured at /posts/new-comment/12/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
How can i fix this error. When i write comment and click on 'add comment' button than it shows me the error which i mentioned in the title. I don't get it how can i fix it. Please help me to fix this error. I shall be very thankful to you. I just want that after commenting he should redirect to the post detail view on which post a person leave a comment. model.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post,related_name='comments', on_delete=models.CASCADE) body = models.TextField() create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.author.username def get_absolute_url(self): return reverse("posts:post_detail", kwargs={"pk": self.post_id,"slug":self.post_slug}) urls.py app_name = 'posts' urlpatterns = [ path('int:pk/str:slug/',views.PostDetailView.as_view(),name ='post_detail'), path('new-comment/int:pk/',views.CommentCreateView.as_view(),name= 'comment_create'), ] view.py class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm template_name = "posts/snippets/comment_form.html" def form_valid(self, form,*args, **kwargs): form.instance.post_id = self.kwargs['pk'] # form.instance.post_slug = kwargs['slug'] form.instance.author = self.request.user return super().form_valid(form) template(postdetail.html) {% if not post.comments.all %} No comments <a href="{% url 'posts:comment_create' pk=post.pk%}">Add one</a> {% else %} <a href="{% url 'posts:comment_create' pk=post.pk%}">Add one</a> if more details are require than tell me in the comment session. i will update my question with that detail. -
'int' object is not iterable?(Django template)
Here is Django template code. I tried to put out images to template. amount of image put out to template is depending on {{object.image_amount}} {% for i in object.image_amount %} <td><img src="{% static 'rulings_img/' %}{{object.item_hs6}}/{{object.id}}-{{object.image_amount}}.jpg" width="100" height="100"></td> <td>{{object.image_amount}}</td> {% endfor %} When I tried this code error message appeared. 'int' object is not iterable How can I solve this error? -
How to create the dummy the redis in Django test?
I am trying to create the dummy redis in Django test. My tests.py looks as below class TestInitiatePositive(SimpleTestCase): databases = '__all__' def setUp(self): pass @responses.activate def test_initiate_payment(self): self.credentials = { 'username': '*****', 'password': '*****' } User.objects.create_user(**self.credentials) self.client.login(username='*****',password='*****') abc.objects.create(user_id_id ='1',nick_name = 'KONTO', access_token ='eyJ0eXAiOiJ') response = self.client.post('/hello/initiate/', data={"from": "*****", "to": "*****"}) self.assertContains(response, 'dummyUrl', status_code=200) self.assertTemplateUsed(response, 'hello/redirecting.html') The model signal will be triggered once the data is inserted into the abc table and celery will pick up the task from the model signal and insert it into redis @receiver(post_save, sender=access_tokens) def access_token_added(sender, instance, created, **kwargs): if created: accessToken.delay(x) I am getting the following error Error 60 connecting to ****:6379. Operation timed out. I need to create the dummy redis to complete this test case. -
How can i run Django with Vue and Webpack Loader using Nginx?
I'm trying to deploy a very simple Django app that uses VueJS with Webpack-Loader using Django-Webpack-Loader. I can run my app in local without any problem using manage.py runserver and npm run serve. Now i'm trying to deploy this simple app to DigitalOcean using Gunicorn and Nginx. The problem is that while i can see the standard templates being rendered by django, my Vue files are not loading and i only get a lot of errors: GET http://URL/static/vue/js/index.js net::ERR_ABORTED 404 (Not Found) The full code of the application is HERE, it's not mine, i'm just running a simple example to get started. Can anyone help me on this? I made sure to build my frontend for production using npm run build and i collected my static files using manage.py collectstatic, but i still get the error. Any kind of advice is appreciated. -
React: sending component as html + css to server?
I want to send react component with styles, as it looks on dev server, to another server (django in my case), and there create a PDF with exact look. So I want to pass identical component (as html with styles?) via POST to server. I've found ReactDOMServer.renderToString and it works, but it cant provide styles. Any solutions? Thanks. -
How to override django-allauth templates in django 3.0.7 and django-allauth 0.43.0
I want to override django-allauth templates. I have done it before in django==3.0.2 and django-allauth==0.41.0. Now I am using django==3.0.7 and django-allauth==0.43.0. Lasttime I configured my settings like that in the code sample. I have tried this it doesn't work. I have also tried other solutions like placing the templates inside another app's templates directory but still no luck. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),os.path.join(BASE_DIR, 'templates', 'allauth')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And the templates folder structure is like this. templates allauth account openid socialaccount tests What am I doing wrong here? -
Celery task - cancel previous calls with same parameters (re-calls)
I need to have a celery task which is called every time I change a field on a model. Imagine having a name field on a Book model, and every time it's changed, I need to start a complicated celery task which does some long-running things for the book, like re-ordering it in the library. The thing is, that the name is an input field so a user can type slowly in the name field, and a celery task will be called every letter. The important thing is here that I don't care about previous calls, and I want to execute the task only when it's relevant i.e it's the last call. I thought about throttling or maybe somehow revoking all previous task calls with the same name that takes care of this book, but from what I've seen here, terminating tasks under perfectly normal circumstances isn't something I should be doing. Throttling may also be an option. The solution also has to support both SQS and Redis for local & production environments. Any help would be appreciated, thanks so much in advance! -
Django - why user.is_authenticated asserting true after logout
I am trying to write a test for logging out a user in Django. Here is the code: urls.py from django.conf.urls import url from django.contrib import admin from accounts.views import LoginView, LogoutView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', LoginView.as_view(), name='login'), url(r'^logout/', LogoutView.as_view(), name='logout'), ] views.py from django.http import HttpResponseRedirect from django.contrib.auth import login, logout from django.views.generic import View class LogoutView(View): def get(self, request): logout(request) return HttpResponseRedirect('/') tests.py from django.test import TestCase, Client from django.contrib.auth.models import User class LogoutTest(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user( username='user1', email='user1_123@gmail.com', password='top_secret123' ) def test_user_logs_out(self): self.client.login(email=self.user.email, password=self.user.password) self.assertTrue(self.user.is_authenticated) response = self.client.get('/logout/') self.assertFalse(self.user.is_authenticated) self.assertRedirects(response, '/', 302) The assertion self.assertFalse(self.user.is_authenticated) is failing. Testing through the browser seems to work fine. It seems like the user would not be authenticated after called logout(). Am I missing something? -
DRF displaying default image even if user uploaded an image
I wonder which method in which part of my Django backend I should use to change the representation of the user's profile picture/ the path of the user's profile picture. Because I have an default image '/media/default_l.png' which is used in my model like so: class User(AbstractBaseUser,PermissionsMixin): id = models.AutoField(primary_key=True) # custom User models must have an integer avatar = models.ImageField(upload_to=avatar_upload, blank=True, default='default_l.png', validators=[validators.FileExtensionValidator(['jpg','jpeg', 'gif', 'png',])]) ... This default image is used to display an image as long as the user didn't upload an profile image of his choice. When the user uploads an image, he uploads the image to upload_to=avatar_upload like so: def avatar_upload(instance, filename): #https://c14l.com/blog/django-image-upload-to-dynamic-path.html #return os.path.join('images/user_avatar/', 'user_{0}', '{1}').format(instance.user.id, filename) new_filename = '{}_{}.{}'.format('user',instance.pk, 'png') return "user_avatar/{}".format(new_filename) So the default image is /media/default_l.png and the uploaded image is /media/user_avatar/user_3.png (= user_pk.png) The serializer for uploading an image is # Upload User Profile Picture class AvatarSerializer(serializers.ModelSerializer): avatar = serializers.ImageField(max_length=None, use_url=True) class Meta: model = User fields = ['avatar'] def save(self, *args, **kwargs): if self.instance.avatar: #delete if not default if "/media/default_l.png" not in self.instance.avatar.url: self.instance.avatar.delete() return super().save(*args, **kwargs) The uploading works fine with the view class UserUploadImage(RetrieveUpdateAPIView): #permission_classes = (IsLoggedInUser, ) parser_class = [MultiPartParser, FormParser] serializer_class = AvatarSerializer queryset = User.objects.all() … -
Django Invalid block tag: 'urls' error on loading tag
I'm trying a tutorial to load a ML script into Django. I've completed the tutorial but right now i'm getting an error TemplateSyntaxError at / Invalid block tag on line 9: 'urls'. Did you forget to register or load this tag? HTML <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Home page</title> </head> <body> <h1>Titanic survival prediction</h1> <form action="{% urls 'result' %}"> {% csrf_token %} extra code with form items </form> URLS file in python: from django.contrib import admin from django.urls import path from djangoweek import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('result/', views.result, name='result'), ] I've looked at other questions at stack but I don't got the answer. -
Django how to include URLs from different apps into the same single extended template html using namespace
I have created a 2nd app in my django project and I am trying to create a HTML files that contains links to both the main app and the 2nd app. I am getting this error: Reverse for 'deploy' not found. 'deploy' is not a valid view function or pattern name. My code is: urls.py from django.conf.urls import url from django.contrib import admin from django.urls import path, include from applications.atoll_queue_manager_fe_project.fe import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('create/', views.createtodo, name='createtodo'), # App2 - Deploy Side Branch path('deploy-side-branch/', include('fe2.urls')), ] 2nd app fe2/urls.py from django.urls import path from applications.fe2 import views app_name = 'fe2' urlpatterns = [ path('', views.deploy_side_branch, name='deploy'), ] navbar section in base.html (extended by new.html) <ul class="navbar-nav mr-auto"> <li class="nav-item {{ deploy }}"> <a class="nav-link" href="{% url 'deploy' %}">Deploy</a> </li> <li class="nav-item {{ current }}"> <a class="nav-link" href="{% url 'currenttodos' %}">Current</a> </li> <li class="nav-item {{ completed }}"> <a class="nav-link" href="{% url 'completedtodos' %}">Completed</a> </li> <li class="nav-item {{ create }}"> <a class="nav-link" href="{% url 'createtodo' %}">Create</a> </li> </ul> -
Django keeps saying field is required even if the fields are already provided
My View: code = 111 score = 3 test = models.Test.objects.filter(code__iexact=code)[0] first_name = data['first_name'] last_name = data['last_name'] password = data['password'] form = forms.EntryForm(data=data) if form.is_valid(): form.instance.test = test form.instance.first_name = first_name form.instance.last_name = last_name form.instance.password = password form.instance.score = score form.save(commit=True) Running this however will give me this warning saying test and score fields are required: <ul class="errorlist"><li>test<ul class="errorlist"><li>This field is required.</li></ul></li><li>score<ul class="errorlist"><li>This field is required.</li></ul></li></ul> But as you can see, all the fields are already provided. It doesn't also give an error for first_name, last_name and password so I guess Django have read that one. Here is my Entry model: class Entry(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=200, default=None) score = models.CharField(max_length=100, default=None) def __str__(self): return "Test: {t} | By: {f} {l}".format(t=self.test, f=self.first_name, l=self.last_name) And the form: class EntryForm(forms.ModelForm): class Meta: model = models.Entry fields = '__all__' Any ideas? Thanks a lot! -
Custom pagination in Django is not working properly
I created a pagination in django using a dropdown which lists the pages for the user to select from. When any value is selected a javascript function is called which calls the django backend to fetch the data. The response object from django includes the page number which was selected so that the same page can be kept selected in HTML (since the page reloads to render the template). <div> Pages : <select name="pagination" id="pagination_id" onchange="pageChange()"> {% for i in pages %} <option value={{i}} {% if page_selected == i %} selected="selected" {% endif %}> {{i}} </option> {% endfor %} </select> </div> However, the dropdown selection is always the first item even though the data in HTML table changes. The value in page_selected is appropriate but the dropdown does not select on the correct page. What am I doing wrong ? -
Accepting localized Date input on Django REST framework
I have a form with date field for submitting date in russian, typical input will be like: "1 апреля 2020" Also have a serializer: class CartSerializer(serializers.Serializer): ... delivery_date = serializers.DateTimeField(input_formats=['%d %B %Y',]) At settings.py have: LANGUAGE_CODE = 'ru' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True When sending delivery_date to rest API it returns an error: {"delivery_date":["Datetime has wrong format. Use one of these formats instead: DD [January-December] YYYY."]} Is possible in DRF to accept non-english Date value? -
spacy nlp is taking long time to answer (django backend)
I have django backend and I'm using spacy for text processing Here is a sample of my code nlp = spacy.load('en_core_web_sm') def process_data(jd): # print(jd) print('process_data start', time.time()) #doc = nlp(jd) doc = nlp.pipe([jd]) print('process_data pipe', time.time()) for each in doc: print('process_data inside loop', time.time()) doc = each print('process_data done loop', time.time()) print('process_data nlp', time.time()) Here is the output of the same process_data start 1603023551.9794967 process_data pipe 1603023551.979678 process_data inside loop 1603023564.9438393 process_data done loop 1603023565.172661 process_data nlp 1603023565.2528574 process_data skills 1603023570.6167505 spacy.load occurs when the application is initialised itself... but if you see to get inside the for loop is taking a lot of time (1603023564.9438393 - 1603023551.979678) Could anyone suggest how to make it faster -
creating a bubble chart using chartjs from three lists of data
I am trying to build a bubble chart using chartjs having 3 lists of data I collected. Using below code for html var ctx = document.getElementById('chart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'bubble', // The data for our dataset data: { datasets: [{ label: 'list1-list2-list3', backgroundColor: 'rgb(255, 99, 132)', pointStyle:'circle' borderColor: 'rgb(255, 99, 132)', data: { x: {{list1|safe}}, y: {{list2|safe}}, r: {{list3|safe}} } }] }, // Configuration options go here options: {} }); I have tried converting these lists to array and then using it but no success. I am getting this enter image description here I want to achieve something like this enter image description here. please guide, much appreciated. -
python manage.py is'nt running and not showing any results
python manage.py is not working also it isn't showing any error when I run the command Django admin runserver it showing me thisenter image description here -
OperationalError: create_superuser doesn't work
I'm trying to make custom user model for my app named Bookjang. When I typed python manage.py createsuperuser Error raised like this django.db.utils.OperationalError: no such column: Bookjang_user.rank Here is my custom user manager class code. class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('user_type', 'Manager') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) And my custom user model. class User(AbstractBaseUser, PermissionsMixin): USER_TYPE_CHOICES = ( ('reader', 'Reader'), # 독자 ('author', 'Author'), # 저자 ('publisher', 'Publisher'), # 출판사 ('manager', 'Manager'), ) email = models.EmailField(unique=True) rank = models.IntegerField(default=1) exp = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]) user_type = models.CharField( max_length=10, choices=USER_TYPE_CHOICES, default=USER_TYPE_CHOICES[0] ) created_date = models.DateField(auto_now_add=True) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'email' objects = UserManager() I already check migrations and here it is. migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('email', models.EmailField(max_length=254, unique=True)), ('rank', models.IntegerField(default=1)), … -
Django-Cookiecutter: Why is dist listed in .gitignore?
A fundamental question about the .gitignore list that's auto generated by django-cookiecutter. I suppose this it's best practice to ignore dist. I am not a front-end/UI master but many javascript packages come with a dist folder which I just copy into the static folder. Is that a bad idea? Is there something I should know about files in a dist folder? -
Djongo (Django+Mongo) - Can't insert new documents [django.db.utils.DatabaseError Error]
I'm using djongo to connect to Mongo DB with Django. This is my DATABASES configuration in my settings.py: DATABASES = { 'default': { 'ENGINE': 'djongo', 'CLIENT': { 'host': 'mongodb+srv://{}:{}@{}/?retryWrites=true&w=majority'.format( USERNAME, PASSWORD, HOST), 'username': USERNAME, 'password': PASSWORD, 'name': DB_NAME, 'authSource': 'admin', 'ssl':False, 'authMechanism': 'SCRAM-SHA-1', } } } I can't insert new documents using djongo, but i can update existing ones. I have a view that upserts a document based on the primary key field: def upsert_document_view(request): try: form_data = request.POST form = self.form(form_data) if form.is_valid(): print("SAVING TO MONGODB. Data:\n{}".format(form_data)) form.save() except Exception as err: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] msg_text = msg_text + "\n\nPython Error:\n{} `{}`\nfile_name: {} | line_number: {}".format(exc_type, exc_obj, fname, exc_tb.tb_lineno) print(msg_text) When a document does not exist, djongo should insert a new document when the code gets to form.save(). Unfortunately i'm getting this weird empty error: <class 'django.db.utils.DatabaseError'> `` As you can see, its a django.db.utils.DatabaseError error, but the error message is empty. Like i mentioned, when i try to use form.saves() for existing documents, djongo does not throw any errors and works properly. -
http://<domain> gets redirected to https://<ip> (NGINX, Django, Gunicorn)
I'm hosting a website using nginx, Django and Gunicorn and just installed the SSL certificate so I can use HTTPs for the website. Everything works perfectly fine when using https://.com, even http://www..com works like it should, but http://.com gets redirected to https:// for some reason. My sites nginx config is: server { listen 443 ssl; listen [::]:443 ssl; ssl on; ssl_certificate /etc/ssl/<crt>; ssl_certificate_key /etc/ssl/<key>; server_name <domain>.com; client_max_body_size 100M; access_log on; location /static/ { alias /opt/<dir>/; } location /uploads/ { alias /opt/<dir>/; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } server { listen 80; server_name <domain>.com www.<domain>.com; return 301 https://<domain>.com$request_uri; } When I cURL my site, its properly redirected to its HTTPs version, but in Firefox in gets redirected to the server IP. I'm very unsure why this is the case, so I'd appreciate any ideas! -
Websites for smartphones, tablets and pc [closed]
I wanna design a website that works on smartphones, tablets and pc. So which platform will be able to do that effectively. -
my django api view.py not showing list and creat new list
Hello developer I'm beginner to django , im following a tutorial in which he create concrete views classes and convert them to viewset.ModelViewSet classes. and he use default router in urls.py my app showing list of articles with viewset but not perform the post method with the ArticleViewSet(viewset.ModelViewSet) so im confused about it to use viewset This is my api/view.py file im using Concrete View Classes in which i using concrete view classses ** class ArticleListView(ListAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleDetailView(RetrieveAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleUpdateView(UpdateAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleDeleteView(DestroyAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleCreateView(CreateAPIView): permission_classes = [] #parser_classes = (FormParser,MultiPartParser, FileUploadParser ) serializer_class = ArticleSerializer queryset = Articles.objects.all() #serializer = ArticleSerializer(queryset, many=True) def post(self, request): serializer = ArticleSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(True, status=200) # class ArticleViewSet(viewsets.ModelViewSet): # parser_classes = (FormParser,MultiPartParser, FileUploadParser ) # serializer_class = ArticleSerializer # queryset = Articles.objects.all() **this are my urls patterns api/url.py in Article app ** urlpatterns = [ path('articles', ArticleListView.as_view() name=""), path('xyz', ArticleCreateView.as_view()), path('<pk>', ArticleDetailView.as_view()), path('<pk>/update/', ArticleUpdateView.as_view()), path('<pk>/delete/', ArticleDeleteView.as_view()) ] #from articles.api.views import * # from rest_framework.routers import DefaultRouter # router = DefaultRouter() # router.register(r'', ArticleViewSet, basename='articles') # urlpatterns = router.urls …