Как я могу создать модель Django для формы, в которой пользователи могут добавлять дополнительные поля? - PullRequest
0 голосов
/ 02 августа 2020

Я новичок в Django и пытаюсь создать сайт-резюме. Я использую Django WizardForms, чтобы пользователи могли поэтапно составлять свое резюме. В форме обучения пользователи могут добавить до 5 различных школ, в которых они учились. (Используя кнопку + Добавить поля, которую я реализовал с помощью JavaScript)

Это правильный способ записать все поля в models.py и forms.py ? Я уверен, что должен быть более чистый способ сделать это, а не отдельно перечислять все поля и различать их числом в конце.

Я просмотрел Django FormSets, но не уверен, как я будет использовать это с Django WizardForms.

Спасибо

models.py

class Profile(models.Model):
    education_school            = models.CharField(max_length=500, null=True, blank=True)
    education_degree            = models.CharField(max_length=500, null=True, blank=True)
    education_field             = models.CharField(max_length=100, null=True, blank=True)
    education_start             = models.CharField(max_length=100, null=True, blank=True)
    education_end               = models.CharField(max_length=100, null=True, blank=True)
    education_grade             = models.TextField(null=True, blank=True)
    education_description       = models.TextField(null=True, blank=True)

    education_school2           = models.CharField(max_length=500, null=True, blank=True)
    education_degree2           = models.CharField(max_length=500, null=True, blank=True)
    education_field2            = models.CharField(max_length=100, null=True, blank=True)
    education_start2            = models.CharField(max_length=100, null=True, blank=True)
    education_end2              = models.CharField(max_length=100, null=True, blank=True)
    education_grade2            = models.TextField(null=True, blank=True)
    education_description2      = models.TextField(null=True, blank=True)

    education_school3           = models.CharField(max_length=500, null=True, blank=True)
    education_degree3           = models.CharField(max_length=500, null=True, blank=True)
    education_field3            = models.CharField(max_length=100, null=True, blank=True)
    education_start3            = models.CharField(max_length=100, null=True, blank=True)
    education_end3              = models.CharField(max_length=100, null=True, blank=True)
    education_grade3            = models.TextField(null=True, blank=True)
    education_description3      = models.TextField(null=True, blank=True)

    education_school4           = models.CharField(max_length=500, null=True, blank=True)
    education_degree4           = models.CharField(max_length=500, null=True, blank=True)
    education_field4            = models.CharField(max_length=100, null=True, blank=True)
    education_start4            = models.CharField(max_length=100, null=True, blank=True)
    education_end4              = models.CharField(max_length=100, null=True, blank=True)
    education_grade4            = models.TextField(null=True, blank=True)
    education_description4      = models.TextField(null=True, blank=True)

    education_school5           = models.CharField(max_length=500, null=True, blank=True)
    education_degree5           = models.CharField(max_length=500, null=True, blank=True)
    education_field5            = models.CharField(max_length=100, null=True, blank=True)
    education_start5            = models.CharField(max_length=100, null=True, blank=True)
    education_end5              = models.CharField(max_length=100, null=True, blank=True)
    education_grade5            = models.TextField(null=True, blank=True)
    education_description5      = models.TextField(null=True, blank=True)

forms.py

class ProfileFour(forms.Form):
    education_school        = forms.CharField()
    education_degree        = forms.CharField()
    education_field         = forms.CharField()
    education_start         = forms.ChoiceField(choices=years)
    education_end           = forms.ChoiceField(choices=years)    
    education_grade         = forms.CharField(widget=forms.Textarea)
    education_description   = forms.CharField(widget=forms.Textarea)

    education_school2       = forms.CharField()
    education_degree2       = forms.CharField()
    education_field2        = forms.CharField()
    education_start2        = forms.ChoiceField(choices=years)
    education_end2          = forms.ChoiceField(choices=years)    
    education_grade2        = forms.CharField(widget=forms.Textarea)
    education_description2  = forms.CharField(widget=forms.Textarea)

    education_school3       = forms.CharField()
    education_degree3       = forms.CharField()
    education_field3        = forms.CharField()
    education_start3        = forms.ChoiceField(choices=years)
    education_end3          = forms.ChoiceField(choices=years)    
    education_grade3        = forms.CharField(widget=forms.Textarea)
    education_description3  = forms.CharField(widget=forms.Textarea)

    education_school4       = forms.CharField()
    education_degree4       = forms.CharField()
    education_field4        = forms.CharField()
    education_start4        = forms.ChoiceField(choices=years)
    education_end4          = forms.ChoiceField(choices=years)    
    education_grade4        = forms.CharField(widget=forms.Textarea)
    education_description4  = forms.CharField(widget=forms.Textarea)

    education_school5       = forms.CharField()
    education_degree5       = forms.CharField()
    education_field5        = forms.CharField()
    education_start5        = forms.ChoiceField(choices=years)
    education_end5          = forms.ChoiceField(choices=years)    
    education_grade5        = forms.CharField(widget=forms.Textarea)
    education_description5  = forms.CharField(widget=forms.Textarea)

Ответы [ 3 ]

0 голосов
/ 02 августа 2020

Вместо того, чтобы писать один и тот же код 5 раз, вы можете просто использовать поле ManyToMany.

class Profile(models.Model):
    education_school            = models.ManyToManyField( blank=True)
    education_degree            = models.ManyToManyField( blank=True)
    education_field             = models.ManyToManyField( blank=True)
    education_start             = models.ManyToManyField( blank=True)
    education_end               = models.ManyToManyField( blank=True)
    education_grade             = models.ManyToManyField( blank=True)
    education_description       = models.ManyToManyField( blank=True)

  • , а затем вы можете определить каждое поле отдельно
class education_school(models.Model):
    education_school = models.CharField(max_length=500, null=True, blank=True)

и так далее с другими полями

0 голосов
/ 28 августа 2020

Вы неправильно смотрите на это. Во-первых, ваша модель должна быть обновлена, чтобы отразить ваш вариант использования. Если вы не знаете поля заранее, вы можете использовать JSONField, содержащееся в ArrayField, например,

education = ArrayField(models.JSONField(default=dict), size=10, default=list)

Теперь, когда мы получили это из Кстати, лучший способ сделать то, что вы хотите, - иметь Education в качестве модели, а затем модель Profile будет иметь внешний ключ для Education. ie

class Education(models.Model):
  school = models.CharField(max_length=50)
  degree = models.CharField(max_length=50)
  ...rest of fields

Тогда ваша модель Profile будет иметь: education = models.ForeignKey(Education, related_name="profile")

Чтобы получить различное количество форм обучения, вы должны воспользоваться modelformset . Создайте свой EducationForm как обычный экземпляр modelForm, затем:

EducationFormSet = modelformset_factory(Education, form=EducationForm, max_num=10, extra=1)
0 голосов
/ 02 августа 2020

у вас есть ModelForm в django

class ProfileFour(form.ModelForm)
    class Meta:
       model = Profile
       fields = '__all__'  # you wand all field
       # or 
       fields = ['education_school', 'education_degree' ..] # name the field you want

do c django действительно хорошо, прочтите.

https://docs.djangoproject.com/fr/3.0/topics/forms/modelforms/

edit : для завершения ответа @ Countour-Integral

class Profil(models.Model)
   username = models.charField()
   ...

class Education(models.Model)
    profil = models.ForeignKey(Profil)
    school = models.CharField()
    degree = models.IntegerField()
    field = models.CharField()
    start = models.DateField()
    end = models.DateField()
    grade = models.CharField()
    description = models.textField()
...