如何在django 2.1中将变量选择分配给表单字段

时间:2018-11-11 11:43:10

标签: python django django-forms

我在应该更新表单的formModel类上遇到问题,问题是我希望根据另一个字段(level)(ara_book)选择字段可变< / strong>(这是一个值列表),然后从json文件中生成选择,然后将选择元组填充并根据字段(级别)

EX :如果用户级别字段设置为 ['01','02'] ,则表单应生成两个选择元素,第一个将具有 json_file ['ara_book'] ['01'] ,另一个带有 json_file ['ara_book'] ['02']

这是班上

class BooksUpdateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
    FILE_PATH = os.path.join(BASE_DIR, "dashboard/static/json/books.json")
    BOOKS = ()
    with open(FILE_PATH, 'r', encoding='utf-8') as f:
        JSON_FILE = json.load(f)
    user_level = kwargs['instance'].level
    for item in user_level:
        for key in JSON_FILE[item]['ara_book']:
            BOOKS.append(JSON_FILE[item]['ara_book'][key])
    super(BooksUpdateForm, self).__init__(*args, **kwargs)
ara_book = forms.ChoiceField(choices=BOOKS)
class Meta:
    model = Profile
    fields = ['ara_book']

这是视图

def books(request):
if request.user.profile.level == '':
    messages.warning(request, f'يجب تحديث المستوى المُدَرَّسْ قبل تحديث الكتب المقررة')
    return redirect('level')
if request.method == 'POST':
    books_form = BooksUpdateForm(request.POST, instance=request.user.profile)
    if books_form.is_valid():
        books_form.save()
        messages.success(request, f'لقد تم تحديث المستوى المُدَرَّسْ بنجاح')
        return redirect('profile')
else:
    books_form = BooksUpdateForm(instance=request.user.profile)
context = {
    'books_form': books_form,
    'title': request.user.profile.name
}
return render(request, 'users/books.html', context);

这是模特

class Profile(models.Model):
LANG = (
    ('', 'اختر لغة التدريس'),
    ('BI', 'مزدوج'),
    ('AR', 'عربية'),
    ('FR', 'فرنسية'),
    ('AZ', 'أمازيغية')
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='avatar.png',upload_to=get_upload_path)
name = models.CharField(default='',max_length=100)
doti = models.PositiveIntegerField(default=0)
t_lang = models.CharField(default='', choices=LANG, max_length=2)
level = models.CharField(default='', max_length=200)
academie = models.CharField(default='', max_length=100)
delegation = models.CharField(default='',max_length=100)
school = models.CharField(default='',max_length=200)
ara_book = models.CharField(default='', max_length=200)

def __unicode__(self):
    return self.user.id

def __str__(self):
    return f'{self.user.username} Profile'

0 个答案:

没有答案