How to save with a newform into the DB with missing parameters

As django auto forms seem to not do anything except ‘many to many’ relationships yet (yeck) and, with foreign keys you probably don’t want the visitor just setting those anyway, you are left to use an autoform but ‘fill in’ bits and pieces of this ‘partial’ autoform for the user before saving it.

One way to do it is this (uses ‘editable=false’) to not display certain (necessary) things for the user


class ResponseToEvaluation(models.Model):
originating_evaluation = models.ForeignKey(Evaluation,editable=False) # lodo umm...foreginkey then just doesn't work with these things?
personal_comments = models.CharField(maxlength=2000)
pub_date = models.DateTimeField(editable=False)

ResponseToEvaluationAutoForm = form_for_model(ResponseToEvaluation)

Then in the view thus:

from django.newforms.models import * # save_instance
def comment_reply_view(request, id):
        if request.method == 'POST':
            form = ResponseToEvaluationAutoForm(request.POST)
            rNew = ResponseToEvaluation()
            rNew.originating_evaluation_id = id # muhaha
            rNew.pub_date = datetime.now() # we want that one, too
            if form.is_valid():
                save_instance(form, rNew) # stolen from modeltests/model_forms/models.py yeck
                return returnUserHomePage(request, extraHash = {'display_message': 'Response written'})
            else:
                return returnUserHomePage(request, extraHash = {'error_message': 'Trouble writing response'})
        else:
            form = ResponseToEvaluationAutoForm()
        originalEvaluation = Evaluation.objects.get(pk=id)
        repliesToIt = originalEvaluation.responsetoevaluation_set.order_by('pub_date')
        return render_to_response('user/comment_reply_to.html', {'form': form, 'originalEvaluation': originalEvaluation, 'replies': repliesToIt})

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>