Django 错误/类型字符变化的值太长(1)

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

我正在尝试向我的 model/forms 添加新的表单集字段,但是当我想保存它时,我收到错误消息“值太长,类型字符不同 (1)”。

有人可以帮我吗?我是 django 的初学者。 当我添加 "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))

这是我的代码:

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)

和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>

感谢您的帮助! :)

您已将 study_1 声明为最大长度为 1 个字符的字符字段,但您将其设置为代表年份的四位数字符串。

study_1 的 max_length 更改为 4 或更多,然后通过 python manage.py makemigrations 迁移您的更改。最后通过 python manage.py migrate.

应用更改