0

Let's say I have a CreateArticleView like the following which extends CreateView.

class CreateArticleView(CreateView):
    model = ArticleModel
    fields = ['title', 'text']

ArticleModel actually has 3 fields, though; it also has category.

category is a url argument, as urls follow the following regex: 127.0.0.1/category/(?P<category>[0-z]+)/articles/new/.

I need some way to get the category from the URL (this has been answered by SO users) and some way to then take that data and put it into my ArticleModel instance (this has not).

For instance, let's say a user wants to create an ArticleModel entitled, "Russia's Military Just Bought Five Bottlenose Dolphins and It Won't Say Why" with the text, "Wow!"

I'd get the title and text from the POST (or GET) data and could plug it into the ArticleModel with article = ArticleModel.objects.create(title=title_from_POST, text=text_from_POST). However, I'd also need to provide the category kwarg for the ArticleModel. How would I plug that in?


Please note: I am not making a website where people can publish articles. The code above is entirely for example. What I'm looking for is some way to get URL variables to class-based functions.

Quelklef
  • 1,999
  • 2
  • 22
  • 37
  • Possible duplicate of [Django class-based view: How do I pass additional parameters to the as\_view method?](http://stackoverflow.com/questions/11494483/django-class-based-view-how-do-i-pass-additional-parameters-to-the-as-view-meth) – solarissmoke Jul 03 '16 at 02:59
  • @solarissmoke So then how would I plug in the kwarg value when creating my object? – Quelklef Jul 16 '16 at 02:32

1 Answers1

0

You can override the form_valid method and access url parameters using the self.kwargs dictionary.

Example:

class CreateArticleView(CreateView):
    model = ArticleModel
    fields = ['title', 'text']

    def form_valid(self, form):
        self.kwargs['category'] # Access the category or any other url parameters

        return super(CreateArticleView, self).form_valid(form)

Source: https://docs.djangoproject.com/ja/1.9/topics/class-based-views/generic-editing/

Mantu
  • 51
  • 5