Django ustawia domyślne wartości formularzy
Mam następujący Model.
class TankJournal(models.Model):
user = models.ForeignKey(User)
tank = models.ForeignKey(TankProfile)
ts = models.IntegerField(max_length=15)
title = models.CharField(max_length=50)
body = models.TextField()
Mam również wzór formularza dla powyższego modelu w następujący sposób.
class JournalForm(ModelForm):
tank = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = TankJournal
exclude = ('user','ts')
Chcę wiedzieć, jak ustawić domyślną wartość dla tego ukrytego pola czołgu.. Oto moja funkcja, aby pokazać / zapisać formularz do tej pory
def addJournal(request, id=0):
if not request.user.is_authenticated():
return HttpResponseRedirect('/')
#
# checking if they own the tank
#
from django.contrib.auth.models import User
user = User.objects.get(pk=request.session['id'])
if request.method == 'POST':
form = JournalForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
#
# setting the user and ts
#
from time import time
obj.ts = int(time())
obj.user = user
obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank_id'])
#
# saving the test
#
obj.save()
else:
form = JournalForm()
try:
tank = TankProfile.objects.get(user=user, id=id)
except TankProfile.DoesNotExist:
return HttpResponseRedirect('/error/')
form.tank = id
return render_to_response('ajax/tank_addJournal.html', {'form': form}, context_instance=RequestContext(request))
Dzięki. 4 answers
Możesz użyć initial co jest wyjaśnione tutaj
Masz dwie opcje wypełniania wartości podczas wywoływania konstruktora formularza:
form = JournalForm(initial={'tank': 123})
Lub ustaw wartość w definicji postaci:
tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-11 21:29:51
Jeśli tworzysz modelform z post wartości początkowe można przypisać w ten sposób:
form = SomeModelForm(request.POST or None, initial={"option": "10"})
Https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-05 11:33:27
Inne rozwiązanie: Ustaw inicjał po utworzeniu formularza:
form.fields['tank'].initial = 123
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-30 13:39:42
Miałem inne rozwiązanie (zamieszczam je na wypadek, gdyby ktoś inny jak ja stosował następującą metodę z modelu):
class onlyUserIsActiveField(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(onlyUserIsActiveField, self).__init__(*args, **kwargs)
self.fields['is_active'].initial = False
class Meta:
model = User
fields = ['is_active']
labels = {'is_active': 'Is Active'}
widgets = {
'is_active': forms.CheckboxInput( attrs={
'class': 'form-control bootstrap-switch',
'data-size': 'mini',
'data-on-color': 'success',
'data-on-text': 'Active',
'data-off-color': 'danger',
'data-off-text': 'Inactive',
'name': 'is_active',
})
}
Inicjał jest definiowany na funkcji __init__
jako self.fields['is_active'].initial = False
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-03 00:17:03