简体   繁体   中英

How to solve Value Error assign error in Django?

I am creating a system with Django. I create a system for limiting. I have several company, and every company has to create their own limit criteria. I think I can use foreign key for that. What I mean is I want to take company name from user's company name. You can understand clearly from my models. But user should not see comp_name field in their page, it should only be seen from the admin page (kind of a hidden field in frontpage.

I tried a model for what I want but I get an error:

ValueError at /add/limit Cannot assign "'Test 1'": "DoaTable.comp_name" must be a "CompanyProfile" instance.

how can I solve it?

views. py

def create_doa_table(request):
    form_class = DoaTableForm
    current_user = request.user
    userP = UserProfile.objects.get_or_create(username=current_user)
    companyName = userP[0].comp_name
    # If this is a POST request then process the Form data
    if request.method == 'POST':
        # Create a form instance and populate it with data from the request (binding):
        form = DoaTableForm(request.POST)
        # Check if the form is valid:
        if form.is_valid():
            newDoaElement = form.save()
            newDoaElement.comp_name = companyName
            newDoaElement.save()

            # redirect to a new URL:
            return render(request, 'doa_table.html')
    else:
        form = form_class()

    return render(request, 'add_doa_element.html', {'form': form})

models.py

class DoaTable(models.Model):
    rank = models.CharField(max_length=20)
    risk = models.CharField(max_length=20)
    limit = models.CharField(max_length=20)
    comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.rank

class UserProfile(AbstractUser):
    
    comp_name = models.CharField(max_length=200, default='', blank=True, null=True)
    user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True)
    username = models.CharField(max_length=500, unique=True)
    ...

    def __str__(self):
        return self.username

forms.py

class DoaTableForm(forms.ModelForm):
    class Meta:
        model = DoaTable
        comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all(), required=False,
                                           widget=forms.HiddenInput())
        fields = ('rank', 'risk', 'limit', )

traceback

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/add/limit

Django Version: 3.1.4
Python Version: 3.8.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'register',
 'customer',
 'financial_analysis',
 'ocr',
 'core',
 'approvals',
 'django_tables2',
 'crispy_forms',
 'ckeditor',
 'rest_framework',
 'requests']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\USER\OneDrive\Documents\GitHub\otc\myvenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\USER\OneDrive\Documents\GitHub\otc\myvenv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\USER\OneDrive\Documents\GitHub\otc\myvenv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\USER\OneDrive\Documents\GitHub\otc\approvals\views.py", line 29, in create_doa_table
    newDoaElement.comp_name = companyName
  File "C:\Users\USER\OneDrive\Documents\GitHub\otc\myvenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__
    raise ValueError(

Exception Type: ValueError at /add/limit
Exception Value: Cannot assign "'Test 1'": "DoaTable.comp_name" must be a "CompanyProfile" instance.

line below is the problem:

form = DoaTableForm(request.POST)

in this model DoaTable you have a foreign key which is CompanyProfile so you must create instance using this model CompanyProfile then pass it to your DoaTableForm .

Maybe you can add a commit = False param at first form.save.Like this:

        if form.is_valid():
            newDoaElement = form.save(commit=False)
            newDoaElement.comp_name = companyName
            newDoaElement.save()

In your views.py change this like:

newDoaElement.comp_name = companyName

to something like this:

newDoaElement.comp_name = CompanyProfile.objects.get(name=companyName) # will give you the CompanyProfile instance

Assuming your CompanyProfile looks like this:

class CompanyProfile(models.Model):
    name = models.CharField(max_length=20)
    # ... other fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM