0

I've been trying for over a week now to save a new model object that has one ManyToMany field using save(commit=False) but I keep running into the same error. I've tried over 10 different approaches and haven't been able to resolve this. Thanks in advance for your help! See relevant code below:

DatabaseError at /createRezidio/ (1364, "Field 'vquestions' doesn't have a default value")

    ['/Users/matthewbaron/Desktop/Nonsense/Loeb Land/source/commapp',
     '/Library/Python/2.7/site-packages/virtualenv-1.9.1-py2.7.egg',
     '/Library/Python/2.7/site-packages/setuptools-5.4.1-py2.7.egg',
     '/Library/Python/2.7/site-packages/distribute-0.6.28-py2.7.egg',
     '/Library/Python/2.7/site-packages/MySQL_python-1.2.4-py2.7-macosx-10.9-intel.egg',
     '/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
     '/Library/Python/2.7/site-packages',
     '/Library/Python/2.7/site-packages/PIL']

models.py

class Questions(models.Model):
    userId = models.ForeignKey(User)
    question = models.TextField()
    approved = models.BooleanField(default=False)

    def __unicode__(self):
        return "%s" % (self.question)

class Profiles(models.Model):
    userId = models.ForeignKey(User)
    university = models.CharField(max_length = 60)
    universityYear = models.CharField(max_length = 60, choices=GRADE_CHOICES)
    gpa = models.DecimalField(max_digits = 4, decimal_places = 3, validators=   [MinValueValidator(0), MaxValueValidator(5)])
    major = models.CharField(max_length = 60)
    resumeText = models.TextField(help_text = 'Paste text of resume here:')
    vquestions = models.ManyToManyField(Questions, blank = True, null = True, choices = VID_QUESTIONS)
    resumeFile = models.FileField(upload_to = file_name_resume)
    video1 = models.FileField(upload_to = file_name_video1)
    video2 = models.FileField(upload_to = file_name_video2)
    video3 = models.FileField(upload_to = file_name_video3)
    video4 = models.FileField(upload_to = file_name_video4)
    userPhoto = models.ImageField(upload_to = file_name_photo)

    def __unicode__(self):
        return "%s, %s, %s, %s, %s, %s, 

views.py

def createRezidio(request):

    if request.method == 'POST':
        form = AutoRezidioForm(request.POST, request.FILES)
        if form.is_valid():
            newprof = form.save(commit=False)
            newprof.userId = request.user
            newprof.save()

            return HttpResponseRedirect("/viewRezidio/")
    else:
        form = AutoRezidioForm() # A empty, unbound form

    if request.user.groups.filter(name="recruiter").count() > 0:
        return render_to_response(
            "users/base_rezidio.html",
            {'form': form, 'type' : 'recruiter'},
            context_instance=RequestContext(request)
        )

        return render_to_response(
            "users/base_rezidio.html",
            {'form': form, 'type' : 'student'},
            context_instance=RequestContext(request)
        )

forms.py

class AutoRezidioForm(ModelForm):   
    class Meta:
        model = Profiles
        exclude = ['userId']
    vquestions = forms.ModelMultipleChoiceField(queryset = Questions.objects.all().filter(approved = True), widget=SelectMultiple)

1 Answers1

1

On this:

vquestions = models.ManyToManyField(Questions, blank = True, null = True, choices = VID_QUESTIONS)

Try using limit_choices_to (docs) instead of defining a set of choices with choices =. This can be done on the model and will impact the available choices on all modelforms where that model is used. That also means you don't have to define a queryset in forms.py; you can pass an additional parameter to limit_choices_to to only allow associations with approved questions.

Since you are using commit = False with a form that touches a many-to-many field, I believe you will also need to use save_m2m (docs) in order to get things to save properly.

souldeux
  • 3,615
  • 3
  • 23
  • 35
  • Thanks for your help! I will try this out and get back to you on how it works. Then it's just as simple as saying: limit_choices_to = {'approved': True} in models.py on that ManyToManyField and that'll hopefully alleviate the issue? Thanks! – Matthew Baron Aug 08 '14 at 18:19
  • I believe so, but I'll admit that I didn't test this. Use both that and the save m2m thing I mentioned, and please let me know if it keeps throwing any trouble at you. – souldeux Aug 08 '14 at 19:42
  • So I got rid of the manual vquestions form field in forms.py, added the limit_choices_to in models.py, and added form.save_m2m() to my views.py function but I still get "DatabaseError at /createRezidio/ (1364, "Field 'vquestions' doesn't have a default value")". Any thoughts? Thanks again for your help! – Matthew Baron Aug 09 '14 at 02:40
  • Clarifying: Is the error popping when the page loads or you try to save (I assume the latter)? Has your DB been synced since you put null=True in vquestions' model definition? This thread may help as well: http://stackoverflow.com/questions/8073734/saving-a-model-in-django-gives-me-warning-field-id-doesnt-have-a-default-va I am sorry that my original answer didn't solve the problem. – souldeux Aug 09 '14 at 04:47
  • Yep, it was popping up on newprof.save(). I now added a default value for vquestions in PhpMyAdmin (NULL) and got past newprof.save()! But now, on form.save_m2m(), it's saying "DatabaseError at /createRezidio/ (1146, "Table 'commappfin.rezidio_profiles_vquestions' doesn't exist")", so I'm trying to get past that now. commappFin is the Database Name denoted in settings.py. Occasionally, my django app just stops interacting with the database though, and I have to create a new one for some reason. – Matthew Baron Aug 09 '14 at 18:24
  • Try doing an `inspectdb` and see if you can find the table. If it really doesn't exist, then your DB hasn't been synched properly and you need to either `syncdb` or migrate in the new tables you want. Make sure the app is registered in your `settings.py` before you do. If it DOES exist and just isn't being found for some reason, then the only cause I can think of is a migration gone awry like here: http://stackoverflow.com/questions/4840102/why-dont-my-south-migrations-work. Very sorry, but we're at the limits of my knowledge on the topic; I apologize for not providing a full working solution. – souldeux Aug 09 '14 at 23:09
  • The table doesn't exist in my db after all. Is that just a type of JOIN table? And it has to be manually created (is that what you mean by "migrate")? Nothing seemed to change when I did syncdb. Thanks again! – Matthew Baron Aug 10 '14 at 03:14
  • And figured it all out, just created the table manually with the right fields. Thanks again! – Matthew Baron Aug 10 '14 at 04:03