37π
β
Use the following method (hopefully itβs clear enough):
class BackupForm(ModelForm):
"""Form for adding and editing backups."""
def __init__(self, *args, **kwargs):
systemid = kwargs.pop('systemid')
super(BackupForm, self).__init__(*args, **kwargs)
self.fields['units'] = forms.ModelMultipleChoiceField(
required=False,
queryset=Unit.objects.filter(system__id=systemid),
widget=forms.SelectMultiple(attrs={'title': _("Add unit")}))
class Meta:
model = Backup
exclude = ('system',)
Create forms like this:
form_backup = BackupForm(request.POST,
instance=Backup,
systemid=system.id)
form_backup = BackupForm(initial=form_backup_defaults,
systemid=system.id)
Hope that helps! Let me know if you need me to explain more in depth.
π€lemonad
8π
I ran into this problem as well, and this was my solution:
class ChangeEmailForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
self.user = user
super(ChangeEmailForm, self).__init__(*args, **kwargs)
self.fields['email'].initial = user.email
class Meta:
model = User
fields = ('email',)
def save(self, commit=True):
self.user.email = self.cleaned_data['email']
if commit:
self.user.save()
return self.user
π€Druska
- [Django]-Book for Django + Celery + RabbitMQ?
- [Django]-Django 1.7 β How do I suppress "(1_6.W001) Some project unittests may not execute as expected."?
- [Django]-Where should django manager code live?
2π
Pass the user into the __init__
of the form, and then call super(β¦)
. Then set self.fields['from'].queryset
to user.peers
π€Amandasaurus
- [Django]-Django β SQL bulk get_or_create possible?
- [Django]-Overriding initial value in ModelForm
- [Django]-How overwrite Response class in django rest framework ( DRF )?
Source:stackexchange.com