i've seen a way to do what I want in the views.py file, but as I'm probably going to use the form in several different places, and because I believe it belongs more in forms.py, I was wondering if and how I could pre-fill my form with the datas already stored in the database for one particular user without modifying the views. Seeing what I tried will speak for itself :
models.py :
class Customers(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='details')
city = models.CharField(max_length=50, blank=True, null=True)
dpt = models.IntegerField(blank=True, null=True)
adress = models.CharField(max_length=100, blank=True, null=True)
cplt_add = models.CharField(max_length=100, blank=True, null=True)
phone = models.CharField(max_length=14, blank=True, null=True)
forms.py :
class CustomerForm(ModelForm):
def __init__(self):
for field in self.fields:
user_infos = Customers.objects.get(pk=request.user.details.id)
initial_value = user_infos.field
field(initial=initial_value)
def clean_form(self):
...
class Meta:
model = Customers
fields = ['city', 'adress', 'dpt', 'cplt_add', 'phone']
widgets = {
'city': TextInput(attrs={
'class': 'form_input',
'placeholder': 'Ville'}),
'dpt': TextInput(attrs={
'class': 'form_input',
'placeholder': 'Département'}),
'adress': TextInput(attrs={
'class': 'form_input',
'placeholder': 'Adresse'}),
'cplt_add': TextInput(attrs={
'class': 'form_input',
'placeholder': "Complément d'adresse"}),
'phone': TextInput(attrs={
'class': 'form_input',
'placeholder': 'Téléphone'}),
}
This code, sadly but without big surprise, returns :
'CustomerForm' object has no attribute 'fields'
Any advice on how to do this with good practice methodology ?