I want to add my own attribute 'fileName' inside method 'as_view()'
path('dialogs/', CodeResponseView.as_view(fileName='Dialogs.py')),
Django give's me an arror:
TypeError: CodeResponseView() received an invalid keyword 'fileName'. as_view only accepts arguments that are already attributes of the class.
The error tells you exactly what you should do:
as_view only accepts arguments that are already attributes of the class
So add fileName
as attribute to your class:
class CodeResponseView(View):
fileName = ''
# rest of view code can now use the fileName attribute
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['file'] = self.fileName
return context
Now, any url pattern passing fileName
to as_view()
will work:
path('dialogs/', CodeResponseView.as_view(fileName='Dialogs.py')),
path('alerts/', CodeResponseView.as_view(fileName='Alerts.py')),
you can add your attribute. your in case 'filename' as in context.
if you want to pass and use at templates side is help full when you use DetailView , ListView , CreateView , TemplateView etc generic-class-base view
there is two way
1. first way is pass argument in as_view function see here not need to pass at view side or view if you have model you can also pass at urls.py in another keyword arguments model=< Your model name >
urls.py
path('dialogs/', CodeResponseView.as_view(extra_context={'fileName':'Dialogs.py')),
Then you can access filename attribute at your template side like
Your Template file
<h1> My file name is : {{ filename }} </h1>
My file name is Dialogs.py
2. Second way assign extra_context dictionary in your view class where you define at view.py file
urls.py
path('dialogs/', CodeResponseView.as_view()),
views.py Here you not need to override a get_context_data method for pass filename
class CodeResponseView(DetailView):
extra_context={'filename':'Your File name'}
model=models.<model-name> # here your model name
Then you can access filename attribute at your template side like
Your Template file
<h1> My file name is : {{ filename }} </h1>
My file name is Your File name
This stuff may help you let me know it's answer is right or wrong .....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.