Ho un modello come segue.Django imposta i valori predefiniti del modulo
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()
Ho anche un modello per il modello di cui sopra come segue.
class JournalForm(ModelForm):
tank = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = TankJournal
exclude = ('user','ts')
voglio sapere come impostare il valore predefinito per il campo nascosto serbatoio .. Ecco la mia funzione per mostrare/salvare il modulo finora
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))
Grazie.
E come è che variabile 'initial' passata alla forma attuale? Nel modello di modulo attuale, dobbiamo scrivere come parametro/argomento? – mgPePe
sì, * iniziale * è un parametro denominato –
wait, wut? Wut significa? Intendi dire che, da qualche parte nel _init_ del modulo avrei bisogno di qualcosa come: tank = initial.tank? O qualcosa? O sarebbe semplicemente accaduto magicamente? – bharal