I am a beginner in Django and trying to create a web application. In this case I want to assign an employee to a user. In the user form, the call is made to the employees who are active and who do not yet have assigned users. The problem is that when making the call and listing the employees on the screen, it does not bring me the name of the employee, it only brings me: Employee Object(8)
My model(User)
class User(AbstractUser):
active = models.BooleanField(default=True)
employee = models.OneToOneField(Employee,on_delete=models.CASCADE,null=True)
def __str__ (self):
return '{}'.format(self.username,self.groups,self.active,self.employee)
My Form(User)
class UserForm(UserCreationForm):
username = forms.CharField(label="User",
widget=forms.TextInput(attrs{"class":"formcontrol"}))
groups = forms.ModelMultipleChoiceField(label="Rol",queryset=Group.objects.all(),
widget=forms.CheckboxSelectMultiple,required=True)
password1 = forms.PasswordInput(attrs={'class':'form-control'})
password2 = forms.PasswordInput(attrs={'class':'form-control'})
employee = forms.ModelChoiceField(queryset=Employee.objects.filter(user=None,active=True),
widget=forms.Select(attrs={'class':'form-control'}))
class Meta:
model = User
fields = [
"username",
"password1",
"password2",
"groups",
"employee",
#"active",
]
My model (Employee)
class Employee(Person):
name = models.CharField(max_length=100)
active = models.BooleanField(default=True)
def __str__(self):
return'{}'.format(self.doc,self.address,self.email,self.phone,self.name,self.active)
CodePudding user response:
The problem is that when making the call and listing the employees on the screen, it does not bring me the name of the employee, it only brings me: Employee Object(8).
Since you should return name of employee in the __str__()
method of Employee
model itself.
An example here:
class Employee(models.Model):
... # other fields.
...
def __str__(self):
return f"{self.employee_name_field}"
Share your Employee
model, will edit the answer.
CodePudding user response:
queryset=Employee.objects.filter(user=None,active=True).values("name_field_from_table","other_field_if_you_want")