Django error / value too long for type character varying(1)

1.2k views Asked by At

I'm trying to add new formset field to my model/forms, but when i want save it, i gets an error " value too long for type character varying(1)".

Can anyone help me with that? I'm begginer at django. This error is start's show up when i add "study_1" field in views.

                if university and field:
                new_obj.append(UserLink(user=user, university=university, city_1=city_1, grade=grade, field=field, description_1 = description_1, study_1 = study_1))

Here's my code:

views.py:

@login_required
def profile_settings(request):
user = request.user

LinkFormSet = formset_factory(LinkForm, formset=BaseLinkFormSet)

# Get our existing link data for this user.  This is used as initial data.
user_links = UserLink.objects.filter(user=user)


link_data = [{'university': l.university, 'city_1': l.city_1, 'grade': l.grade, 'field': l.field, 'description_1': l.description_1, 'study_1': l.study_1,}
                    for l in user_links]

#lfs = formset_factory(NameForm)

if request.method == 'POST':

    #postedformset = lfs(request.POST)
    #return HttpResponseRedirect('/edit_profile/')

    link_formset = LinkFormSet(request.POST)


    if link_formset.is_valid():

    # Now save the data for each form in the formset
        new_obj = []

        for link_form in link_formset:
            university = link_form.cleaned_data.get('university')
            city_1 = link_form.cleaned_data.get('city_1')
            grade = link_form.cleaned_data.get('grade')
            field = link_form.cleaned_data.get('field')
            description_1 = link_form.cleaned_data.get('description_1')
            study_1 = link_form.cleaned_data.get('study_1')

            if university and field:
                new_obj.append(UserLink(user=user, university=university, city_1=city_1, grade=grade, field=field, description_1 = description_1, study_1 = study_1))

        try:
            with transaction.atomic():
            #Replace the old with the new
                UserLink.objects.filter(user=user).delete()
                UserLink.objects.bulk_create(new_obj)

                # And notify our users that it worked
                messages.success(request, 'You have updated your profile.')

        except IntegrityError: #If the transaction failed
            messages.error(request, 'There was an error saving your profile.')
            return redirect(reverse('profile_settings'))

else:
    #form = NameForm()
    link_formset = LinkFormSet(initial=link_data)

context = {

    'link_formset': link_formset,
    #'form':lfs,
}

return render(request, 'edit_profile.html', context)    

forms.py:

YEARS_CHOICES = tuple((str(n), str(n)) for n in range(1990, datetime.now().year + 1))

class LinkForm(forms.Form):

university = forms.CharField(
    max_length=100,
    widget = forms.TextInput(attrs = {'placeholder': 'University',}), required = False)

grade = forms.CharField(
    max_length = 50,
    widget = forms.TextInput(attrs = {'placeholder': 'Grade',}), required = False)

field = forms.CharField(
    max_length = 50,
    widget = forms.TextInput(attrs = {'placeholder': 'Field of study',}), required = False)

city_1 = forms.CharField(
    max_length = 50,
    widget = forms.TextInput(attrs = {'placeholder': 'City',}), required = False)

description_1 = forms.CharField(
    max_length = 500,
    widget=forms.Textarea(attrs={'placeholder': ('Add some details about your education...'),'rows': '5', 'cols': '40',}), required=False)


study_1 = forms.ChoiceField(
    choices=YEARS_CHOICES,
    required=False)

models.py:

YEARS_CHOICES = tuple((str(n), str(n)) for n in range(1925, datetime.now().year + 1))

class UserLink(models.Model):

user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=('user'), related_name='links')



university = models.CharField(max_length = 100)
grade = models.CharField(max_length = 50)
field = models.CharField(max_length = 50)
city_1 = models.CharField(max_length=50)
description_1 = models.TextField(max_length=350)
study_1 = models.CharField(max_length=1, default=0)


def __str__(self):
    return self.university

def save(self, *args, **kwargs):

    super(UserLink, self).save(*args, **kwargs)

and edit_profile.html:

    <form  method="post">
        {% csrf_token %}

        {{ link_formset.management_form }}
        {{ form.management_form }}
        <legend style="font-size: 23px;"> Update your education part</legend>
        {% for link_form in link_formset %}
            <div class="link-formset">
              <div style="border-style:groove; border-radius: 8px; padding: 12px 0 0 7px;"> 

                 <p style="font-size:15px">University: 
                    {{ link_form.university }}
                    {% if link_form.university.errors %}
                        {% for error in link_form.university.errors %}
                            {{ error|escape }}
                        {% endfor %}
                    {% endif %}</p>

                <p style="font-size:15px">City: 
                    {{ link_form.city_1 }}
                    {% if link_form.city_1.errors %}
                        {% for error in link_form.city_1.errors %}
                            {{ error|escape }}
                        {% endfor %}
                    {% endif %}</p>

                 <p style="font-size:15px">Grade: 
                    {{ link_form.grade }}
                    {% if link_form.grade.errors %}
                        {% for error in link_form.grade.errors %}
                            {{ error|escape }}
                        {% endfor %}
                    {% endif %}</p>

                 <p style="font-size:15px">Field of study: 
                    {{ link_form.field }}
                    {% if link_form.field.errors %}
                        {% for error in link_form.field.errors %}
                            {{ error|escape }}
                        {% endfor %}
                    {% endif %}</p>

                <p style="font-size:15px">Description: 
                    {{ link_form.description_1 }}
                    {% if link_form.description_1.errors %}
                        {% for error in link_form.description_1.errors %}
                            {{ error|escape }}
                        {% endfor %}
                    {% endif %}</p>

                <p style="font-size:15px">Rok: 
                    {{ link_form.study_1 }}
                    {% if link_form.study_1.errors %}
                        {% for error in link_form.study_1.errors %}
                            {{ error|escape }}
                        {% endfor %}
                    {% endif %}</p>

                {{ form }}

                    </div>
            </div>
        {% endfor %}

        {% if link_formset.non_form_errors %}
            {% for error in link_formset.non_form_errors %}
                {{ error|escape }}
            {% endfor %}
        {% endif %}

        <input type="submit" value="Update Profile" class="button"/>
    </form>

Thanks for any help! :)

2

There are 2 answers

3
Daniel Roseman On BEST ANSWER

You've declared study_1 to be a character field with a maximum length of 1 character, but you're setting it with four-digit strings representing years.

0
Transformer On

change the max_length of study_1 to 4 or more and then make a migration of your changes by python manage.py makemigrations. Finally apply changes by python manage.py migrate.