0

The project_list() view lists all the projects that already exist and gives you the option to add a new one. new_project() handles the creation of that new project then redirects to either the project() view or back to the project_list() including the form so it can display errors.

I keep thinking I should somehow be using the same render function. The reason is that for about a week I didn't realize that after a form.is_valid() == False the page loaded properly but did not list the projects (I had forgotten to include the projects variable in the second render).

@login_required
def project_list(request):
    projects = request.user.project_set.all()
    return render(request, 'projects/project_list.html', 
                  {'form': ProjectForm(),'projects': projects})

@login_required
def new_project(request):
    form = ProjectForm()
    if request.method == 'POST':
        form = ProjectForm(data=request.POST)
        if form.is_valid():
            project = form.save(commit=False)  #must specify user before commit
            project.owner = request.user
            project.save()
            return redirect(project)

    return render(request, 'projects/project_list.html', 
                  {"form": form, 'projects': request.user.project_set.all()})


def project(request, project_id):
    ....

How do I keep this logic separate but use the same render call?

Also, hypothetically if I needed to render a third time this one with another additional variable, how should I account for that?

pompousPanda
  • 105
  • 2
  • 10
  • Welcome to stackoverflow. Opinion-based questions are considered off-topic here. That said, if the views have different business logic but share the template, use class based views and share the same template among views. BTW, class based views are a great way to share boilerplate code among views. – Paulo Scardine Sep 11 '14 at 18:39
  • Updated the question too exclude opinions. Thanks for pointing me towards class based views, I will research them – pompousPanda Sep 11 '14 at 18:45

1 Answers1

1

Class based views are a pretty good option, but there is no reason you can't do something like;

def _render(request, form):
    return render(request, 'projects/project_list.html', 
                  {"form": form, 'projects': request.user.project_set.all()})

@login_required
def project_list(request):
    projects = request.user.project_set.all()
    form = ProjectForm()
    return _render(request, form)

@login_required
def new_project(request):
    form = ProjectForm()
    if request.method == 'POST':
        form = ProjectForm(data=request.POST)
        if form.is_valid():
            project = form.save(commit=False)  #must specify user before commit
            project.owner = request.user
            project.save()
            return redirect(project)

    return _render(request, form)
Stuart Leigh
  • 826
  • 4
  • 6