5

मैं Django के Createview में एक चर घोषित कैसे करूं, इसलिए मैं इसे अपने टेम्पलेट से उपयोग कर सकता हूं? उदाहरण के लिए मैं टेम्पलेट में {{place_slug}} का उपयोग करना चाहता हूं। मैं पारित कि urls.py से नीचे की तरह:Django - CreateView - परिवर्तनीय घोषित कैसे करें और टेम्पलेट्स में इसका उपयोग कैसे करें

urls.py:

urlpatterns = patterns('', 
    (r'^new/(?P<place_slug>[\w\-\_]+)/?$', PictureCreateView.as_view(), {}, 'upload-new'), 
) 

views.py:

class PictureCreateView(CreateView): 
    model = Picture 

    def dispatch(self, *args, **kwargs): 
     self.place = get_object_or_404(Place, slug=kwargs['place_slug']) 
     return super(PictureCreateView, self).dispatch(*args, **kwargs) 

    def form_valid(self, form): 
     more code here 
+0

क्या आप अपने urls.py से 'PictureCreateView.dispatch' को कॉल नहीं करना चाहिए? – vikki

+1

as_view है [सही] (https://docs.djangoproject.com/en/dev/topics/class-based-views/#simple-usage) – dokkaebi

+0

@ डॉककाबेई मैं देखता हूं! – vikki

उत्तर

12

अवहेलना get_context_data और सेट context_data [ 'place_slug'] = your_slug

कुछ इस तरह:

def get_context_data(self, **kwargs): 
    context = super(PictureCreateView, self).get_context_data(**kwargs) 
    context['place_slug'] = self.place.slug 
    return context 

Django docs में इस पर कुछ और जानकारी।