Get value from url in detail view

Hi, anyone can help me with this. I want to use category value fetched from urls in the model of this DetailView class.

class ProductDetailView(DetailView):
model = category

path(‘productdetail/str:category/slug:slug/’, views.ProductDetailView.as_view(), name=‘product-detail’),

Use how?

See the docs at Built-in class-based generic views | Django documentation | Django, particularly the section Dynamic filtering

Side note - when posting single lines of code, enclose the line with backtick - ` characters. If it’s multiple lines, surround the block of code with lines of three backtick - ` characters. You’ll have a line of ```, then the code, then another line of ```.

1 Like

Thanks, I got the solution for this but I am stuck at this now.
I want to access the models.Fashion accessed Dynamically from ‘cat’ selected value. can you help me with this to get model attribute value dynamically.
class AddProductForm(forms.ModelForm):
    cat = models.Category.objects.all()
    cat_choice = []
    for item in cat:
        val = (item.category, item.category_name)

    cat = forms.ChoiceField(choices=cat_choice, label="Select Category", widget=forms.Select(attrs={'class':'form-control'}))

    class Meta:
        model = models.Fashion
        fields = "__all__"
        exclude = ("slug", "seller_name")
class SellerUpload(CreateView):
    form_class = AddProductForm
    template_name = 'seller/seller_upload.html'
    success_url = "/thankyou"

I’m sorry, I’m not understanding what you’re trying to do here. Can you be a little more specific about what you’re trying to achieve?

Also, your method of building cat_choice at the class level isn’t the best way to do this. Your better off making that a function in the class and referencing the function in the field. See Form fields | Django documentation | Django
(Also, that block of code can be replaced by:
cat_choice = Category.objects.all().values_list('category', 'category_name')
See QuerySet API reference | Django documentation | Django)

Ok, In cat_choice i have these values

[(‘Electronic’, ‘Electronics’), (‘Fashion’, ‘Fashion’), (‘HomeDecor’, ‘Home Decor’), (‘Mobile’, ‘Mobiles’)]

which are also my table names in like class Electronic, class Fashion and so on and every class in that list have same fields so with only one form I want to add these products to different classes selected dynamically from cat_choice.

so in class Meta the model attribute would get the class name of that particular table dynamically from the drop down of cat_choice value and add object to that particular table.

also thank you for this, I tried and it’s working.

cat_choice = Category.objects.all().values_list(‘category’, ‘category_name’)

You can do it in one form, but it’s not going to be a Model form. An instance of a ModelForm is created from a Model - and that decision is made before any submitted data is available.

You would need to create a regular (not-model) form, and then decide during your post handling which type of Model to create and save.

(Although, I find myself questioning why you would have 4 different tables all with exactly the same fields. My initial gut-reaction to that statement is that there’s a better way of handling that situation.)

Okay, Also answer to this

(Although, I find myself questioning why you would have 4 different tables all with exactly the same fields. My initial gut-reaction to that statement is that there’s a better way of handling that situation.)

I know that I can create a single class say Products and in this I could have give the field named category and with that I can filter out my desired results but I am exploring django and doing this simple tasks with more complex problems like different tables with same field and adding data in those tables dynamically, etc.

class ProductDetilView(DetailView):
    template_name = 'ecommerce/product-detail.html'
    context_object_name = 'product'

    def get_queryset(self):
         model = self.kwargs['category']
         return getattr(models, model).objects.all()

As you can see in this class I have fetched data from the different tables with category and this category is fetched from urlconfs and trying to do more such weirdo things so that i could learn more different approaches.

Cool! That’s always a worthwhile endeavor.

And if that’s the case, I might have one or two really off-the-wall ideas that I would never recommend someone actually use - but could do what you’re looking for. Let me think about that for a bit.

1 Like

Ok, so given the docs I found at Creating forms from models | Django documentation | Django and Model Form Functions | Django documentation | Django, I’m not too far off-the-wall.

Again, this isn’t something I would generally recommend in the routine case, but it is available.

Assume an app named my_app, with the models you’ve specified earlier as identified by “category” being passed in as a kwarg to the view, you can dynamically create a model form using the modelform_factory function:

import my_app
from django.forms import modelform_factory

form_class =  getattr(my_app.models, self.kwargs['category']), # Get the reference to the class

excludes = ('slug', 'seller_name') # Taken from your first example in the OP

MyNewModelForm = modelform_factory(form_class, exclude=excludes)

new_form = MyNewModelForm() # Create the instance of the form

Note that that last line works as if you’re creating an instance of any ModelForm with all the appropriate parameters available, including things like request.POST or instance.

1 Like