Как автоматически назначить поля Django ModelForm на CustomUser?
Я размещаю форму на фронтенде моего сайта, и я не могу понять, как автоматически назначить определенное поле ModelForm текущему вошедшему пользователю. Я создал пользовательского пользователя с email в качестве уникального ID. Я могу загрузить страницу & отправить форму, но она не сохраняется для зарегистрированного пользователя, и я не могу увидеть сохраненную информацию в админке. Я использую отдельную модель, на которой основана ModelForm, и одно из полей является внешним ключом, который ссылается на email CustomUser. Я включил мою модель CustomUser, отдельную модель для ModelForm, саму ModelForm и представление.
Любая помощь или предложение будут оценены по достоинству! Смотрите мой код ниже:
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length = 100, unique = True)
first_name = models.CharField(max_length = 50, verbose_name='first name')
last_name = models.CharField(max_length = 50, verbose_name='last name')
date_joined = models.DateTimeField(auto_now_add = True, verbose_name='joined')
last_login = models.DateTimeField(auto_now = True, verbose_name='last login')
is_active = models.BooleanField(default = True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default = False)
is_superuser = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQIURED_FIELDS = []
def get_user_email(self):
return self.email
def get_user_name(self):
return str(self.first_name) + str(self.last_name)
def has_perm(self, perm, obj = None):
return self.is_admin
def has_module_perms(self, app_label):
return True
Модель для ModelForm:
class FacilityInfo(models.Model):
email = models.ForeignKey(CustomUser, on_delete = models.CASCADE)
num_facilities = models.PositiveBigIntegerField()
num_one = models.URLField(null = False)
num_two = models.URLField(null = True)
num_three = models.URLField(null = True)
num_four = models.URLField(null = True)
num_five = models.URLField(null = True)
num_six = models.URLField(null = True)
num_seven = models.URLField(null = True)
num_eight = models.URLField(null = True)
num_nine = models.URLField(null = True)
num_ten = models.URLField(null = True)
num_one_name = models.CharField(max_length = 50, null = False)
num_two_name = models.CharField(max_length = 50, null = True)
num_three_name = models.CharField(max_length = 50, null = True)
num_four_name = models.CharField(max_length = 50, null = True)
num_five_name = models.CharField(max_length = 50, null = True)
num_six_name = models.CharField(max_length = 50, null = True)
num_seven_name = models.CharField(max_length = 50, null = True)
num_eight_name = models.CharField(max_length = 50, null = True)
num_nine_name = models.CharField(max_length = 50, null = True)
num_ten_name = models.CharField(max_length = 50, null = True)
ess_login = models.CharField(max_length= 200, null = False)
ess_pw = models.CharField(max_length= 200, null = False)
ModelForm:
class FacilitySetup(forms.ModelForm):
class Meta:
model = FacilityInfo
fields = ('email','ess_login','ess_pw','num_one','num_one_name','num_two','num_two_name')
ess_login = forms.CharField(widget=forms.TextInput(
attrs={
"placeholder":"Easy Storage Username",
"class" : "form-control"
}
))
ess_pw = forms.CharField(widget=forms.TextInput(
attrs={
"placeholder":"Easy Storage Password",
"class" : "form-control"
}
))
num_facilities = forms.IntegerField(help_text = "# of Facilities")
num_one = forms.URLField(widget = forms.URLInput(
attrs={
"placeholder":'Facility 1 URL',
'class': "form-control"
}
))
num_one_name = forms.CharField(widget=forms.TextInput(
attrs={
"placeholder":"Facility 1 Name",
"class" : "form-control"
}
))
num_two = forms.URLField(widget = forms.URLInput(
attrs={
"placeholder":'Facility 2 URL',
'class': "form-control"
}
))
num_two_name = forms.CharField(widget=forms.TextInput(
attrs={
"placeholder":"Facility 2 Name",
"class" : "form-control"
}
))
def clean_user(self):
if not self.cleaned_data['email']:
return CustomUser()
return self.cleaned_data['email']
Вид:
@loginrequired(login_url="/login/")
def facility_info(request):
msg = None
success = False
if request.method == 'POST':
form = FacilitySetup(request.CustomUser, request.POST)
if form.is_valid():
obj = form.save(commit=False) # Return an object without saving to the DB
obj.email = request.CustomUser # Add an author field which will contain current user's id
obj.save()
msg = 'Facility Info Succesfully Saved'
success = True
else:
msg = "Fields are not valid"
else:
form = FacilitySetup()
return render(request, "facilities/settings.html",{"form": form, "msg":msg, "success":success})