[Answer]-What is the appropriate way to set up a form and view in Django to accommodate both creating and updating a model

1👍

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

The only difference would be to pass the form an instance argument for existing objects.

myapp/models.py

from django.db import models

class Article(models.Model):
    # Define fields here

myapp/forms.py

from django.forms import ModelForm
from myapp.models import Article

# Create the form class.
class ArticleForm(ModelForm):
     class Meta:
         model = Article
         fields = ['pub_date', 'headline', 'content', 'reporter']

myapp/views.py

from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext

from myapp.models import Article
from myapp.forms improt ArticleForm

def create_entry(request):
    if 'POST' == request.method:
        form = ArticleForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            obj = form.save()
            return redirect('your-view')
    else:
        form = ArticleForm()
    context = {'form': form}
    render_to_response('myapp/create_entry.html', context, context_instance=RequestContext(request))

def edit_entry(request, article_id):
    article = get_object_or_404(Article, pk=article_id)

    if 'POST' == request.method:
        form = ArticleForm(data=request.POST, files=request.FILES, instance=article)
        if form.is_valid():
            obj = form.save()
            return redirect('your-view')
    else:
        form = ArticleForm(instance=article)
    context = {'form': form}
    render_to_response('myapp/edit_entry.html', context, context_instance=RequestContext(request))

Leave a comment