Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework detail_route not working in get method
I defined a viewset using ModelViewSet as follow I tried to redefine the GET method to do something like getting something from celery . but this part of code just won't work , it acts just like a standard API and didn't do what I wrote in the get_job_detail function. How should I correctly define the "detail_route" function. views.py class JobViewSet(viewsets.ModelViewSet): queryset = job.objects.all() serializer_class = JobSerializer @detail_route(methods=['get']) def get_job_detail(self, request, pk=None): # print('these part wont proceed') job_item = self.get_object() if job_item.isReady or job_item.isSuccessful: return Response(self.serializer_class(job_item).data) celeryjob = sometask.AsyncResult(pk) celeryjob.get() if celeryjob.state == 'SUCCESS': job_item.state = celeryjob.state job_item.result = celeryjob.result job_item.isReady = True job_item.isSuccessful = True job_item.save() if celeryjob.state == 'FAILURE': job_item.state = celeryjob.state job_item.result = celeryjob.result job_item.isReady = True job_item.isSuccessful = False job_item.save() return Response(self.serializer_class(job_item).data) urls.py from django.conf.urls import url, include from apply_api import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'job',views.JobViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] -
multiple authentication backends configured and therefore must provide the `backend` argument or set the `backend` attribute on the user
first of i am new to django/python . i am trying to create a login website that allows the user to register an account and verify via email or directly login via fb or google(Oauth) i receive the error when i click on the validation url sent to the email. error: ValueError at /activate/Mjk/4p1-dcc5f7ed2e7c847fe362/ You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user. Request Method: GET Request URL: http://127.0.0.1:8000/activate/Mjk/4p1-dcc5f7ed2e7c847fe362/ Django Version: 1.11.3 Exception Type: ValueError Exception Value: You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user. Exception Location: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/init.py in login, line 149 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/gaby/django projects/simple-signup-master/profile-model', '/usr/local/lib/python2.7/dist-packages/virtualenv-15.1.0-py2.7.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/gaby/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Wed, 30 Aug 2017 12:34:31 +0000 mysite/settings AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) this is the function being called when i receive the error def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() … -
Django render doesn't works with for loop but yes without it
I have been looking for this for a while and i didn't found any solution for my issue. I'm rendering with Django according next sentence: render(request, url, context). This is my problem: If I write manually de context of the render in the template: Manual template <p>Data starting...</p> <ul> <li>Data1</li> <li>Data2</li> <li>Data3</li> </ul> The webpage looks fine and every data is shown as I want because, obviously, the output after and before rendering is: <p>Data starting...</p> <ul> <li>Data1</li> <li>Data2</li> <li>Data3</li> </ul> But when I write a dynamic template to retrieve dynamic data, according next template's code: Dynamic template <p>Data starting...</p> <ul> {% for vdom in ioDict %} <li>{{ vdom }}</li> {% endfor %} </ul> The output BEFORE rendering is like in the manual example: <p>Data starting...</p> <ul> <li>Data1</li> <li>Data2</li> <li>Data3</li> </ul> But the output AFTER rendering is what follows: <p>Data starting...</p> <ul> </ul> ioDict is a dictionary like this: {'Data1':{...}, 'Data2':{}, 'Data3':{...}} Could someone help me? I'm really lost with this. Note: I've been using loops in others templates oof my proyect and there aren't issues on them Thanks, Mike. -
filter drop down data using model form according to selection of one drop down in django 1.11.2
I am working on a project where i have three models defined class Vendors(models.Model): user = models.ForeignKey(Users,null=True,) vendor_name = models.CharField(max_length=100, null=True, blank=True, default=None) store_name = models.CharField(max_length=100, null=True, blank=True, default=None) store_image = models.FileField(upload_to='store_pic/',null=True, blank=True, default=None) lat = models.DecimalField(max_digits=9, decimal_places=6, null=True) long = models.DecimalField(max_digits=9, decimal_places=6, null=True) auto_response = models.BooleanField(default=False) max_discount = models.CharField(max_length=100, null=True, blank=True, default=None) objects = VendorsManager() class Meta: verbose_name_plural = 'Vendors' def __unicode__(self): return str(self.vendor_name) class Dishes(models.Model): vendor = models.ForeignKey(Vendors,null=True) dish_name = models.CharField(max_length=100,null=True, blank=True,default=None) Description = models.CharField(max_length=250,null=True, blank=True,default=None) price = models.CharField(max_length=20,null=True, blank=True,default=None) # discount = models.CharField(max_length=20,null=True, blank=True,default=0) dish_image = models.FileField(upload_to='dish_pic/' ,null=True, blank=True, default=None) class Meta: verbose_name_plural = 'Dishes' def __unicode__(self): return str(self.dish_name) class Offers(models.Model): vendor_id = models.ForeignKey(Vendors,null=True) dish_id = models.ForeignKey(Dishes, null=True) discount = models.FloatField(null = True, default=None) per_discount = models.FloatField(null=True,blank=True,default=None) discounted_price = models.FloatField(null=True,default=None) offer_name = models.CharField(max_length=100,null=True,default=None) offer_description = models.CharField(max_length=100,null=True,default=None) class Meta: verbose_name_plural = 'Discounts' def __unicode__(self): return str(self.dish_id.dish_name) Now I am creating a create view for Offer model in which I want all the data in drop down for disk_id created using ModelForm in Offers model according to selected item in vendor_id in same form. My forms.py file code is as follows: class OffersForm(ModelForm): class Meta: model = Offers fields = [ 'vendor_id', 'dish_id', 'discount', 'per_discount', 'discounted_price', 'offer_name', 'offer_description', ] … -
Django: django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')
A new migration, adding a single, simple table, gives me the error "Cannot add foreign key constraint" during migration. Here's an existing model, called EventLog: class EventLog(models.Model): """ The event log. """ user = models.ForeignKey(User, blank=True, null=True) timestamp = models.DateTimeField(auto_now=True) text = models.TextField(blank=True, null=True) ip = models.CharField(max_length=15) metadata = JSONField(default={},blank=True) product = models.TextField(default=None,blank=True, null=True) type = models.ForeignKey(EventType) def __unicode__(self): return "[%-15s]-[%s] %s (%s)" % (self.type, self.timestamp, self.text, self.user) def highlite(self): if self.type.highlite: return self.type.highlitecss return False Here is then the new model, which I'm trying to create: class EventLogDetail(models.Model): eventlog = models.ForeignKey('EventLog', related_name='details') order = models.IntegerField(default=0) line = models.CharField(max_length=500) class Meta: ordering = ['eventlog', 'order'] Seems simple enough, right? So I make the migration: ./manage.py makemigrations: Migrations for 'accounts': accounts/migrations/0016_eventlogdetail.py - Create model EventLogDetail So far, so good. Then, I migrate, like so: ./manage.py migrate: Operations to perform: Apply all migrations: accounts, admin, attention, auth, contenttypes, freedns, hosting, info, mail, sessions, sites, taggit, vserver Running migrations: Applying accounts.0016_eventlogdetail...Traceback (most recent call last): File "./manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/the_user/code/the_project/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) … -
Storing multiple select values in django
I am a fresher in Django. I was searching for a article or SO thread describing the way django stores multiselect list box values in the database but couldn't find one. In my case I have categories list box with options for example(C1,C2,C3). The category name can be a long one. I want to assign multiple categories to single user. It can be single category assigned to a user as well. My model will look like this(cat_name fiels depends on how it stores in the db) class Category(models.Model): user = models.ForeignKey(User) cat_name = models.CharField(max_length=100) #or cat_name = models.TextField() My question is how django will store the values in the db id user_id cat_name 1 1 C1&C2&C3 2 2 C1&C2 3 3 C3 Or id user_id cat_name 1 1 C1 2 1 C2 3 1 C3 4 2 C1 5 2 C2 6 3 C3 If it's the first case then I'll use TextField else CharField. & used in the first case is just an example. Any suggestion/link is highly appreciated. Thanks in advance. -
django CreateView class return to the Previous page
i have tow models in my models file: Project model Task model every project have a tasks and the user can see the project and click on it then it view the tasks i make the user able to update the task title but i want them to be redirect to the project detail again i know how if it was a function that update the task but i am using the class : class UpdateTask(UpdateView): ... success_url = ???? -
Python django error
am new to python and django I am trying to build a small python django application on my local windows laptop. i am not able to underlying tables required for my Django project as when i run "python manage.py syncdb" i get the below error ` Error :django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? ' And when i try running "pip install mysqlclient" i get the below error 'error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279' I am stuck in this step and not able to find any leads. can someone suggest any workaround -
How to generate multiple SVG plots dependent on incoming JSON
My end goal is to create something like this: The Timeseries shows total sales per department over time The slider (red) selects a month of interest that drives the radar plots The radar plot(generated for each Job Role) show the data for the specific month, broken out to show sales per department per Job Role (over time) My timeseries chart is working correctly (loading from a csv file). However, I am now stumped at how to: Dynamically generate as many SVGs as are required from the incoming JSON array. Have the eventual radar plots only plot the corresponding month of the passed JSON (according to the slider) My attempts so far have mostly be around trying to create new d3 objects pointing and appending to #svg-container-RadarPlots based on the below HTML skeleton: <body> <div class="container"> <div class="row" id="svg-container-RadarPlots"> <div class="col-md-4"> <svg class="center-block Junior"> <circle cx="150" cy="100" r="70"></circle> </svg> </div> <div class="col-md-4"> <svg class="center-block Senior"> <circle cx="150" cy="100" r="70"></circle> </svg> </div> <div class="col-md-4"> <svg class="center-block Manager"> <circle cx="150" cy="100" r="70"></circle> </svg> </div> </div> <div class="row" id="svg-container-TimeSeries"> <div class="col-lg-12"> <svg id="timeline" class="center-block" width="800" height="500"></svg> <input id="slider" type="range" min="1" max="20" step="1" value="10"/> </div> </div> </div> </body> The javascript/D3 code I have is based … -
Django auto increment value
I'm using Django models and I would like to get current value of auto increment field "id". I use this in my model class but still getting erros when I access with "userLog.id" id = models.AutoField(primary_key=True) SO, how can I know id value of my object ? Thanks -
Vue.JS on top of existing python/django/jinja app for filter and list render
I have an existing python/django app with jinja template engine. I have a template with a filter and a list the gets rendered correctly via server, also the filters work perfectly without javascript. (based on url with parameters) The server also responds with json if the same filter url is requested by ajax. So it's ready for an enhanced version. Now: I would like to make it nicer and update/rerender the list asynchronously when I change the filter based on the json response I receive. Questions: When I init the vue on top of the page template, it removes/rerenders everything in the app. All within the vue root element becomes white. Can I declare only parts of my whole template ( the one filter and the list) as separate vue components and combine these instances (there are other parts that are not part of the async update part vue should not take of) Can I somehow use the existing markup of my components in jinja to be used to rerender the components again with vue or do I have to copy paste it into javascript (please no!) ? TLDR: I don't wan't to create the whole model with vue and … -
Django custom form validation in ListView
I am using a ListView to set a form and to show results. However i am not sure how can I make form validation and having the same form with errors in case form.is_valid() is not True. this is my code forms.py class InsolventiForm(forms.Form): anno_validator = RegexValidator(r'[0-9]{4}', 'L\'anno deve essere un numero di 4 caratteri') anno = forms.CharField(label='Anno', required=True, max_length=4,validators=[anno_validator]) def clean_anno(self): anno = self.cleaned_data['anno'] return anno views.py from .forms import InsolventiForm class InsolventiView(LoginRequiredMixin, ListView): template_name = 'insolventi.html' model = Archivio form_class = InsolventiForm def get(self, request): import datetime if self.request.GET.get('anno'): form = self.form_class(self.request.GET) if form.is_valid(): date = '31/12/'+self.request.GET.get('anno') dateTime = datetime.datetime.strptime(date, "%d/%m/%Y") dateC = '01/01/'+self.request.GET.get('anno') dateTimeC = datetime.datetime.strptime(dateC, "%d/%m/%Y") context = Archivio.objects.filter(~Q(quoteiscrizione__anno_quota__exact=self.request.GET.get('anno')) \ & Q(data_iscrizione__lte=dateTime) \ & (Q(cancellato__exact=False) | (Q(cancellato__exact=True) & (Q(data_canc__gte=dateTimeC))))) self.request.session['insolventi_queryset'] = serialize('json', context) return render(request, self.template_name, {'form':form}) else: return redirect(reverse('insolventi')) return render(request, self.template_name, {'form':self.form_class()}) this is my template and I am displaying the form manually. insolventi.html <form method="get" action=""> {% for field in form %} {{ field.errors }} {{ field.as_widget() }} {% endfor %} <input type="submit" value="Ricerca" /> </form> Even if there are errors and form.is_valid() is returning False (giving me a redirect to the same view) on the template I never get {{ form.errors }}. … -
How to create a form in django that fill the fields on a related model
I Have a Model that have a OnetoOne relationship with django.contrib.auth.models auth. When i create one User Model i send a signal to the Profile Model wich is related to this User. Then the Profile Object is created, but i cant figure out how to fill the others fields of Profile Object. Eg. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Could some one help me? How can i fill these bio, location and birth_date on a form? Thanks. -
Django: assert 'Many-to-many' relation exists in test
I am writing tests for my project, but I've run into a problem when trying to verify the existence of a 'ManyToMany' relationship. The test concerns the following two models, that are linked together with a ManyToMany Models: class Project(models.Model): (...) linked_attributes = models.ManyToManyField(attributes, blank=True) class Attributes(models.Model): (...) class linked_projects = models.ManyToManyField(Project, blank=True) In my test I wanted to verify that the form created a new many to many relationship. I created the assert on the last line, based on some example code, but it doesn't seem to be working. Test: class ProjectTest(TestCase): (...) form_data = {'linked_attributes' : self.attribute} form = ProjectForm(data=form_data, project=self.project, instance=self.project) self.assertTrue(Project.attributes_set.filter(pk=self.Project.pk).exists()) Does anyone know what I am doing wrong? -
When overriding the reset_password template, it is being shown in the context of the admin panel
When overriding the reset_password template, it is being shown in the context of the admin panel. This is something I dont want. I want it to just be visualised. As plain HTML. I am registering it as follows: urlpatterns = [ ... url(r'^password_reset/$', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html')), ] This is the code of the form: {% extends "frontend/base.html" %} {% block content %} <form action="" method="post">{% csrf_token %} {% if form.email.errors %}{{ form.email.errors }}{% endif %} <p>{{ form.email }}</p> <input type="submit" class='btn btn-default btn-lg' value="Reset password" /> </form> {% endblock %} frontend/base.html is something that my other templates are are extending and are not shown as part of the admin panel. Here is a screenshot: EDIT: INSTALLED_APPS = [ 'waffle', 'jet', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontend', 'blog', 'profiles' ] where the template is in profiles/templates/registration/ -
Preventing Mezzanine CMS from filtering the style tag
I am trying to insert style tags into RichText Pages, but despite specifying "RICHTEXT_FILTER_LEVEL" as 3 (no filtering) in "local_settings.py", the style tag is still filtered. Short of directly modifying the page content in my database, is there a way of properly turning off RichText filtering? -
Installating Django on Godaddy Deluxe with mysql as database (Linux Plan)
I am trying to setup the Django in GoDaddy. I have IP address say 123.154.12.152. The plan enables me to have multiple domains. so i have abc.com as primary domain(/public_html) and xyz.com as addon domain under it(/public_html/xyz/). To my knowledge, I believe that both share the same IP i managed to install virtual env with latest Python 3.6.2 and connect to the database(mySQL). the I have the SSH access. But I don't know how Django connect to xyz.com domain that I have in GoDaddy. Couldn't find any solution. Any help is really appreciated Thanks your time. -
filtering many to many relationship admin.py
I have three objects. in admin.py i have instaled the three models. I wish when i add a new room, the field "img_galery", only show the images related with the hotel i am adding a new room. How can i filter the many to many, in django admin.py?. class Hotel(models.Model): name = models.CharField(max_length=30, blank=True, null=True) class Room(models.Model): hotel = models.ForeignKey(Hotel) name = models.CharField(max_length=20, blank=True, null=True) img_galery = models.ManyToManyField(Images) class Images(models.Model): hotel = models.ForeignKey(Hotel) name = models.CharField(max_length=30, blank=True, null=True) img = models.FileField(upload_to="front/img_hotels/", blank=True, null=True) -
JavaScript - Front-end MVC
My actual question here: I'm wondering if (beargrylls.com) uses Django or it's packages. Or some other framework. Or a custom framework? Also, if you take a look at the website (beargrylls.com), you can see that it uses a lot of paralax scrolling, sliders and cool animations. Is this custom-made or is this another framework/plugin/whatever? If found an awesome website (beargrylls.com) on awwwards.com. I'm familiar with the MVC model that Laravel uses. So I know the basics. But I found out that (beargrylls.com) uses some kind of routing inside it's scripts!? What I also found remarkanble is that the script(s) and the entite css of the website is loaded in inline HTML. So there are no HTTP requests, no files to load except the images Which framework/plugin compiles this? Example: , Route = function t() { classCallCheck(this, t); var e = new Router({ xhr: !0 }); e.get("/", HomeController), e.get("/about", AboutController), e.get("/television", TelevisionController), e.get("/live", LiveController), e.get("/experiences", ExperiencesController), e.get("/socialwall", SocialwallController), e.get("/adventurers", AdventurersController), e.get("/termsofuse", TermsofuseController), e.get("/faqs", FaqsController), e.get("/signup", SignupController), e.error(ErrorController), e.run() } , App = function t() { classCallCheck(this, t), Support.init(), index.TopWhenRefresh(), new Route }; new App; Another example that boosted my suspisions can be found inside it's createClass function or class. Where it … -
django forms min and max selection in ModelMultipleChoiceField
I have problem with determine min and max selection in ModelMultipleChoiceField used with widget CheckboxSelectMultiple. can some one help? my code in forms.py: class MyForm(forms.Form): def __init__(self, *args, **kwargs): extra = kwargs.pop("extra") super(MyForm, self).__init__(*args, **kwargs) for q in extra: if q.type == '1': self.fields['question_%s' % q.id] = forms.ModelMultipleChoiceField( queryset=q.answers.all().filter(is_active=True), label=q.text, required=q.is_required, widget=forms.CheckboxSelectMultiple(), # mix_length=3, # min_length=2, ) -
How To Convert ISOFormated date to Python datetime?
I have a datetime string in the format 2017-08-30T10:21:45.337312+00:00 send from django server using timezone.localtime(timezone.now()).isoformat() I need to parse it back to a timezone object. How to do it? I tried the following but its not working kolkatta_tz = pytz.timezone("Asia/Kolkata") kolkatta_tz.localize(datetime.strptime(product_list[index][5], '%Y-%m-%dT%H:%M:%S.%fZ')) -
Django and formsets
I try to understand how the internal of Django formsets work. After a formset class is created by formset_factory function, inheriting/getting attributes from BaseFormSet, a object of the new created class is initialize, example: ArticleFormSet = formset_factory(ArticleFormA, extra=2) formset = ArticleFormSet() If I check with dir(formset) both form and forms attributes are available, but if I try to print forms nothing is printed, I suppose this is related to the decorator @cached_property(but when is called ?) In the initialization of the formset object there are no operations related to forms attribute. So, I suppose is called when {{formset}} or {{formset.as_p}} etc is called. The method has: forms = ' '.join(form.as_p() for form in self) Why in self, I don't understand, because form based on dir() is just a class, and self is the formset object. What is the logic behind ? (PS I understand what is doing going to every form), but is not form in forms, besides the fact forms is now populated And after that, the fields are created using management_form that before. return mark_safe('\n'.join([six.text_type(self.management_form), forms])) -
Getting no result when using cursor from django.db.connections
I'm basically trying to run the following query. In a custom sql statement. CREATE TEMPORARY TABLE input ( id serial, certified boolean ); INSERT INTO input (id, certified) VALUES (DEFAULT, True), (DEFAULT, False), (DEFAULT, True), (DEFAULT, False), (DEFAULT, True), (DEFAULT, False); CREATE OR REPLACE FUNCTION update_record(_input input) RETURNS input AS $$ UPDATE "tests_person" SET certified=_input.certified WHERE certified=_input.certified RETURNING _input.id, _input.certified $$ LANGUAGE SQL; WITH new_updated AS ( SELECT upd.* FROM input, update_record(input) as upd WHERE upd.id is not NULL ), except_updated AS ( SELECT * FROM input EXCEPT ALL SELECT * FROM new_updated ) SELECT id, certified FROM except_updated; The code for that looks like the following. from django.db import connections sql = '''the above sql code''' with connection.cursor() as cursor: cursor.execute(sql) row = cursor.fetchone() The sql throws no errors at all. But when trying to fetch a row I get no result at even though there should be results. I have the same sql in a fiddle here: http://sqlfiddle.com/#!17/48a30/75 In the fiddle I get some results from the last select statement: SELECT id, certified FROM except_updated; So not really sure why things get different when I try this out in django. For the record, I'm using postgres 9.6 and … -
Archive widget using CBV in django
I'm new to django and I do not know good practices. My problem is how to make a widget where I can select (dropdown) the month and year in which events will appear for that time? I care about doing this without using external packages and using CBV. I will be grateful for every hint. -
render() takes exactly 2 arguments (3 given) Django view while I want to pass varibale
I want to pass a variable to template when I get this error. I saw many stackoverflow answers but it tells , Django send Self by default that's why It saying I am sending 3 arguments. But whats the solution of it I am not getting Url.py url(r'^(?P<lid>\d+)/labels/$' , login_required(LayerView.as_view('ImportLabelView')), name='mapport.maps.layers.importlabel') view.py return self.render('mapport/maps/layers/Labels_detail.html' , {'lid': self.layer.id}) So how can I enable my 3rd argument to pass ?