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:UsersUSEROneDriveDocumentsGitHubotcmyvenvlibsite-packagesdjangocorehandlersexception.py", line 47, in inner
response = get_response(request)
File "C:UsersUSEROneDriveDocumentsGitHubotcmyvenvlibsite-packagesdjangocorehandlersase.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersUSEROneDriveDocumentsGitHubotcmyvenvlibsite-packagesdjangocontribauthdecorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:UsersUSEROneDriveDocumentsGitHubotcapprovalsviews.py", line 29, in create_doa_table
newDoaElement.comp_name = companyName
File "C:UsersUSEROneDriveDocumentsGitHubotcmyvenvlibsite-packagesdjangodbmodelsfields
elated_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.
question from:
https://stackoverflow.com/questions/65950559/how-to-solve-value-error-assign-error-in-django