0

I'am new to Python programming and Django Framework.

I have this app named Devices with multiple tables related with each other (Brand, Version, Location etc) and has crud. What I would like to do is to reuse my functions(list,create,detail etc.) instead of creating individual functions for each table.

Right now I'am unable to change BrandForm dynamically to example VersionForm. Is this possible? and am I doing the right thing?

urls.py

from django.urls import path
from .views import *

app_name = 'devices'
urlpatterns = [
    # BRAND
    path('brand/create', create_view, name='brand-create'),
    # VERSION
    path('version/create', create_view, name='version-create'),
]   

views.py

from .models import *
from .forms import BrandForm, VersionForm   

# GET PAGE NAME TO GET MODEL NAME
def get_page_name(request):
    currentUrl = request.get_full_path()
    page = currentUrl.split('/')[-2].split('.')[0] # Example /devices/brand/list; Get 2nd URL
    return page

def create_view(request):
    page = get_page_name(request) # GET PAGE MODEL NAME
    page_title = 'Create ' + page.capitalize()
    model = apps.get_model('devices', page.capitalize())
    status = "created"

    if request.method == 'POST':
        form = BrandForm(request.POST)
    else:
        form = BrandForm()
    return save_brand_form(request, form, 'devices/brand/create.html', page_title, status)

1 Answer 1

2

While it's possible to fix your solution, it will be non-standard, very hard to read and probably full of bugs. Luckily, django provide very good solution to implement CRUD - class-based views.

So, in your case:
urls.py

from .views import BrandCreateView, VersionCreateView


urlpatterns = [
    path('brand/create', BrandCreateView.as_view()),
    path('version/create', VersionCreateView.as_view()),
]

views.py

from django.views.generic.edit import CreateView
from .models import Brand, Version
from .forms import BrandForm, VersionForm  


class BrandCreateView(CreateView):
    model = Brand
    form_class = BrandForm
    template_name = 'devices/brand/create.html'


class VersionCreateView(CreateView):
    model = Version
    form_class = VersionForm
    template_name = 'devices/version/create.html'
Sign up to request clarification or add additional context in comments.

2 Comments

Note: you don't need to specify the model if you specify the form_class (it's not used).
Thank you, class based views is what i needed. I have changed my urls into something like this: path('version/list', List_view.as_view(model=Version, form_class=VersionForm), name='version-list'),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.