Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return api response on 2 sec delay
Given below is my serializer class. class MyListSerilizer(ModelSerializer): class Meta: model=MyModel fields=['Name','Address_ID','Portal','Address','City','DisplayOrderDateTime','Email','Order_ID','Order_Code','Item_Code','DispatchedOn','Payment_Mode','Shipping_Charge','ShippingMethodCode','ShippingMethodCharges','CashOnDeliveryCharges','CurrencyCode','BillingAddress','GiftWrapCharges','SaleOrderItemCode','Shipping_ref','Cancellable','OnHold','Quantity','Invoice_No''Portal',........] So in my view class defined and output corresponding to them also mentioned over here. class MyListAPIView(ListAPIView): def list(self,request): queryset=MyModel.objects.all() serializer=MyListSerilizer(queryset,many=True) return Response({'Records':serializer.data}) Output :---------->Corresponding to view is [{"apikey":"abcdefghijklmne","project_id":12356,"identifiers":{"phone":"123456","email":"divuiuou@gmail.com"},"activity_type":"purchase","timestamp":1502440673,"order_info":{"currency":"INR","discount":"0.00","shipping_method":"STD","payment_method":"","revenue":"4899.00","order_id":"3652802299","coupon":"","total":"4899.00","tax":"","shipping":"0.00"},"cart_info":{"currency":"INR","total":"4899.00","revenue":"4899.00"},"custom_properties":{"source":"channel_PT"},"products":[{"sku":"mff80GCD6lbs","discount":"0.00","brandName":"myfitfuel","name":"MFF Whey Protein 80 3 kg (6.6 lbs) Rich Chocolate Delight","currency":"INR","price":"4899.00","id":"777","quantity":1.0}]}, {"apikey":"fajdifojiaflj","project_id":564829,"identifiers":{"phone":"12345678","email":"myemnailid@gmail.com"},"activity_type":"purchase","timestamp":1502431810,"order_info":{"currency":"INR","discount":"0.00","shipping_method":"STD","payment_method":"","revenue":"2449.00","order_id":"3652328","coupon":"","total":"2449.00","tax":"","shipping":"0.00"},"cart_info":{"currency":"INR","total":"2449.00","revenue":"2449.00"},"custom_properties":{"source":"channel_PT"},"products":[{"sku":"mfdfaef","discount":"0.00","brandName":"abjd","name":"abcd","currency":"INR","price":"2449.00","id":"777","quantity":1.0}, so on ....]} so my question is how would i achieve to make response of each element by iteration of list in difference of 2 sec delay. example: { "identifiers":{ "email":"abcd@gmai.com", "phone":"123664" }, "activity_type": "purchase", "timestamp": "UNIX TIMESTAMP", "products": [{ "brandName": "abc", "id": "1", "sku": "abcd", "name": "mnis", "price": 12.9, "discount": "", "quantity": "", "currency": "" }] "cart_info":{ "total":"", "revenue":"", "currency":"" }, "Order_info":{ "total":"2121", . . . } } -
django rest framework saving base64 file
how can i handle base64 file field in django rest framework. I am using django extra fields but its not working. serializers.py from drf_extra_fields.fields import Base64FileField class ProductSerializer(serializers.ModelSerializer): file = Base64FileField() class Meta: model = Product fields = ( "name", "file" ) class ProductApi(SerializerMixin, APIView): serializer_class = ProductSerializer def post(self, request): serializer = ProductSerializer(data=request.data) if serializer.is_valid(): return Response("Valid serializer", status=status.HTTP_201_CREATED) return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) but when i tried this i am getting this error. Exception Value: 'NotImplementedType' object is not callable How can i save base64 file in the database using django rest framework -
How to show error messages Django
I have this in my model name = models.CharField(max_length=250, unique=True, error_messages={'unique': 'Name already exists'}) Then I have this form template {% for field in form %} <span>{{ field.error }}</span> <label>{{ field.label_tag }}</label> <div> {{ field }}</div> {% endfor %} Whenever I put an existing name and click submit, the object does not add but no error message is displayed. How do you display the error message? -
django-allauth with react forms
I've been having some trouble using allauth because I'm trying to use it without django forms. I am using react and I'm rendering my form as a set of react components. Is there a way to achieve what I'm trying? So far I've tried overriding the template to render my own react elements, and injecting the provider data into JS so I can use it via react: {% load socialaccount %} {% get_providers as socialaccount_providers %} <script> // (Assume that myapp is already 100% initialized, this is just for uniqueness) window.myapp.providerData = []; {% for provider in socialaccount_providers %} {% if provider.id == "openid" %} {% for brand in provider.get_brands %} window.myapp.providerData.push({ title: "{{brand.name}}", providerId: "{{provider.id}}", brandId: "{{brand.id}}", href: "{% provider_login_url provider.id openid=brand.openid_url process=process %}", }); {% endfor %} {% endif %} window.myapp.providerData.push({ title: "{{provider.name}}", providerId: "{{provider.id}}", href: "{% provider_login_url provider.id process=process scope=scope auth_params=auth_params %}", }); {% endfor %} </script> And injecting the urls in a similar way. This way I get two errors: I can't get the login errors - I've dug through the source code and I don't know how to retrieve them into JS. Any help? For some reason CSRF verification doesn't work. I'm using django-react-csrftoken to … -
Django Group_by Date with Sum Data
I need to combing many acct_id's records into a single summary grouped by the "month" field. All the other data like "value" and "cash_in" need to be Sum() class Cashflow ( models.Model ): acct_id = models.ForeignKey ( Acct ) month = models.DateField ( auto_now = False, auto_now_add = False, null = False, blank = True ) value = models.IntegerField ( blank = True, default = 0 ) cash_in = models.IntegerField ( blank = True, default = 0 ) cash_out = models.IntegerField ( blank = True, default = 0 ) transfer = models.IntegerField ( default = 0 ) I am having a difficult time getting all the data to group. Also would like the months to be in order. -
TypeError: ManyRelatedManager object is not iterable
I am not able to resolve the error named Many Related Manager is not iterable. I have Models named A and B as shown below: class B(models.Model): indicator = models.CharField(max_length=255, null=True) tags = models.CharField(max_length=255, null=True, blank=True) class A(models.Model): definitions = models.ManyToManyField(B) user = models.ForeignKey('userauth.ABCUSER', null=True, blank=True) project = models.ForeignKey('userauth.ProjectList', null=True, blank=True) I want to retrieve definitions attribute of Model A which includes attributes of Class B. I have tried to retrieve it as shown below, But It gives me an error: TypeError: ManyRelatedManager object is not iterable if tbl_scope == 'Generic': checked_objects = A.objects.get(user=user, project=project) for checked_object in checked_objects.definitions: print(checked_object.indicator) -
How to use facebook comments with django
I have a blog web site, where I have 7 apps in which I post with django admin. Every app has the simplest view (the views that call, filter the objects and return the template) and the post_detail view, that open another template where is showed informations about only one post. I don't have slug in my posts, I am sorry because I have a litle idea of what is this, but I think I have unique urls, because the posts urls are automatically called by regex. So, I am trying to put facebook comments plugin in my website, but when I put the facebook comments, I cant list the comment with the respective post. I am sorry, I have no idea what is the correct way to do this. I would like to know what I have to do to list facebook comments with my posts. Very thanks, the code is below: views.py: def index(request): posts = Evento.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'core/index.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Evento, pk=pk) Evento.objects.get(pk=pk) return render(request, 'core/post_detail.html', {'post': post}) models.py: class Evento(models.Model): nome = models.CharField(max_length=200, null=False, blank=False) apresentacao = models.TextField(null=False, blank=False) foto = CloudinaryField('foto', null=True, blank=True) created_date = models.DateTimeField( default=timezone.now) published_date = … -
How to access the SelectDateWidget in UpdateView?
How to implement something similar to SelectDateWidget in forms in class-based generic views? For example: class UserUpdateView(LoginRequiredMixin, UpdateView): fields = ['birthday',] model = User def get_success_url(self): return reverse('users:detail', kwargs={'username': self.request.user.username}) def get_object(self): return User.objects.get(username=self.request.user.username) -
Django CVB attribute with parenthesis
I am trying to learn Django using the Book Django unleashed. In chapter 9, the author is rewriting a form display method to a Class-Based View (CBV). I am trying to understand why a set of parenthesis were used when a class attribute was called. I am assuming it is since the class attribute is going to store a form object, but I wanted to further understand it. from django.shortcuts import render, get_object_or_404, redirect from .models import Tag, Startup from .forms import TagForm from django.views.generic import View class PostCreate(View): form_class = PostForm template_name = 'blog/post_form.html' def get(self, request): return render( request, self.template_name, {'form': self.form_class()}) def post(self, request): bound_form = self.form_class(request.POST) if bound_form.is_valid(): new_post = bound_form.save() return redirect(new_post) else: return render( request, self.template_name,{'form': bound_form}) As you can see, on the 14 line the code is {'form': self.form_class()}) But on the last line, the code is self.template_name, I am confused as to why the author used parenthesis on the first class attribute and not the second. Can you please explain that Thank you -
Calling celery task on remote machine from Django application
I have been trying to call a celery task on remote machine. When I start celery worker on remote machine , It starts task as TestFunction.doStuff (classname.taskname) but when I am trying to call it from a Django application , it sends task as TestApp.TestFunction.doStuff(AppName.classname.taskname). If I call that task on remote machine directly and not from Django Application , it works fine. How do I handle it? -
Django HTML POST delete button with information
I have a table with email addresses and I need to delete email addresses from the table. The table is to have delete buttons next to the email addresses. On initial page load my view sends the email addresses to the Django template. When a user clicks the delete button next to the email address you wish to delete, I need the button to POST along the information of the corresponding email address so that my view can remove the right email address from the database. I've looked around about submit buttons and POST information, but POST usually works by sending along input data. In this case, there is no input data. Here is the code from the template: <tr> <td>{% trans "Email" %}</td> <td>{% trans " " %}</td> </tr> </thead> <tbody> {% for licensed_user in licensed_users %} <tr> <td>{{ forloop.counter }}</td> <td>{{ licensed_user.user.email }}</td> <td> <form class="flex-container" method="post" action="{% url 'reseller_dashboard' %}" > {% csrf_token %} <div class="input-group"> <button name="delete" type="submit" class="btn btn-default">DELETE </button> </div> </form> </td> </tr> I need to send licensed_user.user.email along with the POST method when the button is submitted. -
Data migration to Heroku Postgres DB?
What options do I have to migrate data to hosted with Heroku Postgres Database? I have Django app and my client is migrating is moving from his existing software will most likely produce data in excel format. I will figure out the data model and data conversion I just need to know what tools to use to do the actual update of the DB. -
Using Stripe elements feature: form elements not showing up. javascript django
I have a file called base.html All of my django templates use it as a base (hence the name.. yay) the stripe code tag is in this base file at the end. base.html <script src="https://js.stripe.com/v3/"></script> <!-- Stripe intergration for checkout, on all pages for fraud features to work site wide --> I then have a js file called stripeCheckout.js which contains all the code for the elements feature to work (according to the stripe docs on the matter: https://stripe.com/docs/elements#setup ) that will be posted at the end as it is long and just copy and paste from the stripe docs.. Then I have my actual html file with the stripe checkout form with the stripeCheckout.js script being included in. checkout.html {% extends 'base.html' %} {% load staticfiles %} {% block content %} <form action="/charge" method="post" id="payment-form"> <div class="form-row"> <label for="card-element"> Credit or debit card </label> <div id="card-element"> <!-- a Stripe Element will be inserted here. --> </div> <!-- Used to display form errors --> <div id="card-errors" role="alert"></div> </div> <button>Submit Payment</button> </form> <script src='{% static "javascript/stripeCheckout.js" %}'></script> {% endblock %} following the docs this should all be working but when I show my page I'll I get is this: <form action="/charge" … -
Django Model's styling convention within field
I'm curious as to what the proper styling is within a Django model. The documentation provides examples like so: Do this: class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=40) Don’t do this: class Person(models.Model): FirstName = models.CharField(max_length=20) Last_Name = models.CharField(max_length=40) But what I'm curious is what to do when there's a lot of information within the field such as: class example(models.Model): first_name = models.CharField(max_length=20, blank=true, help_text=blahblahblahblahblahblah, related_name='related name example') Is it appropriate to leave this long one-liner chunk of code, even when it reaches the line limit, or is there a proper way to do it? Here's what I've been doing, which tends to look good at times, but bad during others: class example(models.Model): first_name = models.CharField(max_length=20, blank=true, help_text=blahblahblahblahblahblah, related_name='related name example' ) -
Django not serving static image file
Django is currently not displaying the profile.jpg file in the template. I looked at some tutorials but it didn't solve the issue. Any suggestions on how to serve the static files? I'm using Django version 1.10.6 settings.py: """ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'send_email', 'resume', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ... # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/resume/static/' Heres the line inside the template where I'm trying to display the image: <img src="{% static 'resume/img/profile.jpg' %}" class="responsive-img" style='max-height:100px;' alt="face"> -
Apache2.2 windows 2012 django waits and fails
I have 3 django projects, 2 of them are demo/lightweight and works just fine with apache 2.2 . The other i.e. the main one does not load at all. It appears scarcely and on restart does not responds at all. Config django 1.8.5 apache 2.2 windows server 2012 <VirtualHost ip:80> ServerName dom.org Alias /static "C:/Apache2.2/htdocs/p1/p3/static" WSGIScriptAlias / "C:/Apache2.2/htdocs/p1/p2/wsgi.py" <Directory C:/Apache2.2/htdocs/p1/p2> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> DocumentRoot "C:/Apache2.2/htdocs/p1/p2" </VirtualHost> mind you the above works with other two, but fails most of the time, with the heavy one. I have no idea diagnose. tried increasing mpm threads but no changes. Can anyone help, or at least tell me me how to diagnose? error.logs just show [Sat Aug 19 04:27:41 2017] [warn] mod_wsgi: Compiled for Python/2.7. [Sat Aug 19 04:27:41 2017] [warn] mod_wsgi: Runtime using Python/2.7.11. [Sat Aug 19 04:27:41 2017] [notice] Child 10200: Child process is running [Sat Aug 19 04:27:41 2017] [notice] Child 10200: Acquired the start mutex. [Sat Aug 19 04:27:41 2017] [notice] Child 10200: Starting 64 worker threads. [Sat Aug 19 04:27:41 2017] [notice] Child 10200: Starting thread to listen on port 80. -
Django Views:Getting ListView inside Detailed View
I have the following setup. I have Teachers, which can have many Students. Both of them are Django Users. Students can leave reviews for Teachers. I'm building the Teacher Detail View. That is the url /teachers/1 where /teachers/ is the List View. Now the problem: I want all reviews, left by the user to be visible in the given teacher view. That would correspond to a 'ListView' within a DetailedView. Urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.TeacherView.as_view(), name='detail'), ] Models.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher') availability = models.BooleanField(default=False) def __str__(self): return self.user.username class Student(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Student') teacher = models.OneToOneField(Teacher, on_delete=models.PROTECT, related_name='Student') reviewed = models.BooleanField(default=False) def __str__(self): return self.user.username class Review(models.Model): teacher = models.OneToOneField(Teacher, on_delete=models.PROTECT, related_name='Teacher') student = models.OneToOneField(Student, on_delete=models.PROTECT, related_name='Student') star = models.IntegerField(default=5) body = models.TextField() And finally the main problem - views.py class IndexView(ListView): # context_object_name = 'latest_teacher_list' def get_queryset(self): """Return the last five published questions.""" return Teacher.objects.all()[:5] class TeacherView(generic.DetailView): model = Teacher def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(TeacherView, self).get_context_data(**kwargs) # Add extra context from another model context['reviews'] = Review.objects.filter(teacher_pk=pk) return context This doesn't work, it complains that pk is not defined. … -
Celery won't discover shared_tasks in django 1.11 and celery 4.0.0 or 4.1.0
I have a layout in my project like this: (As the documentation saids it has to be) /zonia /backend __init__.py celery.py ... /musics tasks.py ... ... In the init.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] In the celery.py: from __future__ import absolute_import, unicode_literals import os import environ from celery import Celery env = environ.Env() environ.Env.read_env() # set the default Django settings module for the 'celery' program. os.environ.setdefault('C_FORCE_ROOT', 'true') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') app = Celery('backend', backend='rpc://', broker=env('broker')) # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self)) I have several shared_tasks in the tasks.py module that are like this: @shared_task def recalc_ranking_music(): musics = musics_models.Music.objects.all().order_by("-num_points") for music, rank in enumerate(musics): music.ranking = rank + 1 music.save() When i start the celery with command: celery -A backend worker -l info As you can … -
Assign user to tasks automatically (Viewflow, Django)
I'm using Viewflow/Django (http://viewflow.io/) and trying to assign tasks created by dynamic nodes - I'm using the same nodes.py in https://github.com/viewflow/viewflow/tree/master/demo/customnode - however, I need to automatically assign each new task based on information in the MOCTask model (the assignee). However, tasks don't allow an Assign with anything other than a specific user object, and I don't have access to the MOCTask objects (they are related by foreign key to MOC, which is related by foreign key to MOCProcess, the flow itself). My code I was trying (flows.py): ... split_on_task_assignment = ( DynamicSplit(lambda p: MOCTask.objects.filter(MOC=p.MOC).count()) .IfNone(this.end) .Next(this.task_completion) ) task_completion = ( flow.View(views.TaskCompletion) .Permission('MOC.is_MOC_actor') .Assign(this.assign_actors) .Next(this.join_on_task_completion) ) ... def assign_actors(self, activation): task = MOCTask.objects.filter(MOC=activation.process.MOC, assigned=False).first() task.assigned = True task.save() return User.objects.filter(email=task.assignee).first() However, I can't put a this reference in the assign block, so I'm not sure how to proceed. Any ideas? -
Django URL defaults to undefined location
I created my first Django project, but when I go to the localhost address (http://127.0.0.1:8000), it immediately redirects to http://127.0.0.1:8000/catalog and gives the Page not found at /catalog/ 404 error. Based on the code I've written, I expected it to go to /index. The catalog url is not defined anywhere in my project, and that word appears nowhere in any of the associated files. Here's the relevant code: urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', include('portal.urls')), url(r'^$', RedirectView.as_view(url='/index/', permanent=True)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) portal/urls.py: from . import views urlpatterns = [ url(r'^$', views.indexView.as_view(), name='index'), url(r'^portal/(?P<pk>\d+)$', views.mapView.as_view(), name='portal'), ] I have been using the Chrome browser to do all this. When I tried on Firefox, it worked correctly (i.e. when I typed in http://127.0.0.1:8000 it redirected to /index/). Regardless of browser, if I go to 127.0.0.1:8000/index everything appears as it should. The only thing I can think of that would create this problem is that I went through the MDN Django tutorial that did use the catalog url, so I deleted all history from Chrome that involved localhost, but the problem persists. Seems like it should work regardless of history or cookies, anyways. What part of my code isn't strong enough … -
How to call two html file (templates) from one render in django?
Is it possible to render one request to two different HTML tamplet? I'm not taking about extending or including HTML file with the help of {% include .html %} or contact block -
django annotate not working properly
I have two models SaleItem and Product. Here i want to get the count of the products in the SaleItem table . I used annotate but not getting the desired result class SaleItem(models.Model): product = models.ForeignKey(Product, related_name="sale_products") quantity = models.PositiveIntegerField() class Product(models.Model): name = models.CharField(max_length=128) views.py SaleItem.objects.values("product__name").annotate(count=Count("product__name")) when i tried this in shell. i am getting all the products with count 1 <QuerySet [{'count': 1, 'product__name': u'Rice'}, {'count': 1, 'product__name': u'Rice'}, {'count': 1, 'product__name': u'Mango'}, {'count': 1, 'product__name': u'Mango'}, {'count': 1, 'product__name': u'Mango'}, {'count': 1, 'product__name': u'Apple'}, {'count': 1, 'product__name': u'Apple'}, {'count': 1, 'product__name': u'Apple'}, {'count': 1, 'product__name': u'Apple'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}]> here i want the totalcount of the each Product in the SaleItem table. How can i do that. Somebody please help me. -
Django Dict of List Template
I am trying to print out some stuff from a dictionary of lists in django. Here is my dict_: defaultdict(<class 'list'>, {'UIT ENERGY PRODUCERS CLASS': [6, 3, '08-18-2017'], 'EQUITY GROWTH CLASS': [18, 3, '08-18-2017'], 'UNCONSTRAINED BOND CLASS': [13, 3, '08-18-2017']}) In my views.py: context['obj_items'] = dict_ return context Then in my templates.html: {% for key, value_list in obj_items.items %} {% for value in value_list %} {{ value }} {% endfor %} {% endfor %} But nothing is getting printed out. Any ideas? -
Save Data from Django Model Formset
How do I save data from a django model formset to the database? models.py: from django.db import models from django.utils import timezone class MyModel(models.Model): idno = models.CharField(max_length=20) date = models.DateTimeField(default=timezone.now) entity = models.CharField(max_length=50) logic = models.CharField(max_length=100) choices = ( ('1', 'Choice1'), ('2', 'Choice2'), ('3','Choice3'), ) choices = models.CharField( max_length=20, choices=dispositionChoices, null=True, ) comment = models.CharField(max_length=500, null=True) def __str__(self): return self.idno forms.py: from .models import MyModel from django.forms import modelformset_factory, ModelForm class MyForm(ModelForm): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['idno'].disabled = True self.fields['date'].disabled = True self.fields['entity'].disabled = True self.fields['logic'].disabled = True MyFormSet = modelformset_factory(MyModel, extra=1, exclude=(), form=MyForm) views.py: from django.shortcuts import render from django.http import HttpResponse from .models import MyModel from .forms import MyFormSet def index(request): modelObjects = MyModel.objects.filter(choices__isnull=True) modelformset = MyFormSet(queryset=modelObjects) context = {'modelformset':modelformset} if request.method == 'POST': modelformset = MyFormSet(request.POST) if modelformset.is_valid(): modelformset.save() return render(request, 'myapp/index.html', context) else: return render(request, 'myapp/index.html', context) index.html: <form method="post" action=""> {% csrf_token %} {{ modelformset.management_form }} <table> <tr> <th>idno</th> <th>date</th> <th>entity</th> <th>logic</th> <th>choices</th> <th>comment</th> </tr> {% for form in modelformset %} <tr> <td>{{ form.idno }}</td> <td>{{ form.date }}</td> <td>{{ form.entity }}</td> <td>{{ form.logic }}</td> <td>{{ form.choices }}</td> <td>{{ form.comment }}</td> <td><input type="submit" value="Submit"></td> </tr> … -
custom decorator for permission and login required
I'm following the "Django Unleashed Book" and I've created a custom decorator. I do struggle a little with understanding some parts of the code. The lack of understanding may result from a lack of python knowledge. Here is the code: def require_authenticated_permission(permission): def decorator(cls): if (not isinstance(cls, type) or not issubclass(cls, View)): raise ImproperlyConfigured( "require_authenticated_permission" " must be applied to subclasses " "of View class.") check_auth = method_decorator(login_required) check_perm = method_decorator( permission_required( permission, raise_exception=True)) cls.dispatch = check_auth(check_perm(cls.dispatch)) return cls return decorator I have one problem with understanding the code. The decorator takes a GCBV, uses the dispatch function and stores the GCBV in the "permission" object as an argument for "require_authenticated_permission". Then it takes the arguments from the GCBV (e. g. DetailView) and stores it in the "cls" object. Since there is only one cls object and not something like *args, I would expect the decorator to just work with one argument such as "class ThisIsAView(Detailview)" but it also works with views like this "class ThisIsAView(GetObjectMixin, Detailview)" ... this would mean that it stores both arguments in the cls object?