0

Just to be clear, I'm asking about accessing the fields in views.py

I want to add extra data into the form before it is validated (because it's a required field), and another answer on stackexchange seems to imply I have to create a new form to do so.

Right now my code look something like this:

if request.method == 'POST':
    # create a form instance and populate it with data from the request:
    form = TestForm(request.POST)
    data = {}
    for ---:
        ---add to data---
    comp = Component.objects.get(name = path)
    data['component'] = comp.id
    form = TestForm(data)
    if form.is_valid():
        test = form.save(commit = 'false')
        test.save()
        return submitTest(request, var)

How could I fill in the parts with dashes?

Community
  • 1
  • 1
Arctic Tern
  • 64
  • 1
  • 1
  • 11

2 Answers2

0

This is the wrong thing to do. There is no reason to add in a required field programmatically; if you know the value of the field already, there is no reason to include it on the form at all.

I don't know what you mean about having to create another form; instead you should explicitly exclude that field, in the form's Meta class, and set the value on the test object before calling test.save().

Edit after comment I still don't really understand why you have data coming from two separate places, but maybe you should combine them before passing to the form:

data = request.POST.copy()
data['myvalue'] = 'myvalue'
form = MyForm(data)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I am passing the data for the field in through a url parameter. This value is a foreign key, so it's quite important that I make it a required field. When I mean creating another form, I mean just creating another formset object, not a form that's visible to the user. – Arctic Tern Jul 22 '16 at 16:02
0

I figured out what I was doing wrong. In my TestForm modelform I didn't include the 'component' field because I didn't want it to show up on the form. As a result, the 'component' data was being cleaned out during form validation even if I inserted it into the form correctly. So to solve this I just added 'component' into the fields to display, and to hide it on the form I added this line

widgets = {'component': HiddenInput()}

to the TestForm class in forms.py.

Arctic Tern
  • 64
  • 1
  • 1
  • 11