Search code examples
djangodjango-modelsdjango-model-field

CharField not saving


I'm a relative django newbie, but I haven't been able to find that this is somewhere else. I setup django in accordance with the djangogirls tutorial and created a model that looks something like this:

class Grimmage(models.Model):
    gStart = models.CharField(max_length=100, default='Not set'),
    gStartLat = models.FloatField(default=0.0)
    gStartLong = models.FloatField(default=0.0)
    # [...]
    gUpdateDate = models.DateField(default=timezone.now)
    gUser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

I've done the database migration thing, and I try creating objects with Grimmage.objects.create(gUser=request.user). (I've tried other methods of creating objects with the same results.)

This is what I have in the respective view now (Why I'm not manually setting the default values again will be clear in a moment):

grim = Grimmage.objects.create(gUser=user)
grim.gStart = 'Not set'
grim.gFinish = 'Not set'
grim.save()

Ultimately, the views I'm making should check if the values have been changed from 'Not set' to move through getting values from the user. So, the object also has a method called 'whatsNext()' to return which value needs to be filled in next:

def whatsNext(self):
    ''' Returns a sting to indicate what value is needed next '''
    # Assumes the Grimmage has been checked for completeness and failed
    if self.gStart == 'Not set':
        return 'gStart'
    elif self.gFinish == 'Not set':
        return 'gFinish'
    else:
        return 'gTotalDistance'

Weirdly, it never returns the 'gStart' value because it's not equal to 'Not set.' If the view prints out the string of it, this is what I get:

((django.db.models.fields.CharField), )

If I manually set it again and print out the value, it works (temporarily). However, it quickly reverts to the ...CharField value.

For a while, I thought that none of the fields were saving, but the other (non-CharField) fields all display their default settings without me screwing with them. Further, I seem to be able to save values to them such that they persist.

Screwing around in the shell, I got this result: screengrab from interactive shell

I'm at my wits' end. I've created other, simple django projects before and this was supposed to be the easy part. Naturally, I assume I've made a ridiculous mistake... but what?


Solution

  • You should remove comma after CharField in your model. With comma Python considers gStart attribute as tuple, not as model field.

    gStart = models.CharField(max_length=100, default='Not set') # without ,