Brandon Closson
Brandon Closson

Reputation: 3

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

I am working with sensitive code and I am not able to share specifics based on rules at my job. However, I have a pretty specific issue that should be easy to help with without code. I am new to Django and I am using legacy code. My issue is that I need to build a form that will update an instance of the model if it already exists and if it does not exist, then the form will create and save a new instance of the model. Any suggestions or examples of what it might look like?

Upvotes: 0

Views: 74

Answers (1)

Artur Barseghyan
Artur Barseghyan

Reputation: 14172

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))

Upvotes: 1

Related Questions