another django question. I have a edit form like this. Look at current_status in the code.
It has been updated:
def edit_item(request, client_id = 0, item_id = 0):
client = None
item = None
status = None
contact = None
status_id = request.POST.get('status_id', None)
contact_id = request.POST.get('contact_id', None)
save_item = request.POST.get('save_item', None)
save_status = request.POST.get('save_status', None)
try:
client = models.Client.objects.get(pk = client_id)
item = models.StorageItem.objects.get(pk = item_id)
except:
return HttpResponseNotFound()
try:
status = models.Status.objects.get(pk = status_id)
contact = models.Contact.objects.get(pk = contact_id)
except:
pass
if request.method == 'POST':
form = forms.ItemForm(request.POST, instance = item)
if form.is_valid() and save_item is not None:
form.save(True)
request.user.message_set.create(message = "Item {0} has been updated successfully.".format(item.tiptop_id))
return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")
if status is not None and contact is not None and save_status is not None:
current_status = models.ItemStatusHistory(item = item, contact = contact, status = status,
user = request.user)
item.current_item_status_date = date.today()
item.save()
current_status.save()
request.user.message_set.create(message = "Item status has been updated successfully.")
else:
form = forms.ItemForm(instance = item)
title = str(client) + ' : Edit Item'
status_list = models.Status.objects.all()
return render_to_response('edit_item.html', {'form':form, 'title':title, 'status_list':status_list, 'item':item}, context_instance = RequestContext(request))
current_status save's the latest date of when the form is edited. What I ALSO want to do is to save this value into this models field.
class StorageItem(models.Model):
current_item_status_date = models.DateField()
Is ItemForm a ModelForm (see Django Model Forms)?
If so form.save() will return a model instance. Then you can edit its fields if you need to. For example.
my_obj = form.save()
my_obj.current_item_status_date = datetime.date.today()
my_obj.save()
If not, then simply create a new instance of your model and save the field value.
my_obj = StorageItem(current_item_status_date=datetime.date.today())
my_obj.save()
Related
I have this view that creates a form with groups and exercises.
How can I do to be able to create more groups and exercises in the template?
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
schedaName = form.cleaned_data['nome_scheda']
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
gruppi = DatiGruppi(
giorni_settimana = form.cleaned_data['giorni_settimana'],
dati_gruppo = form.cleaned_data['dati_gruppo'],
gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
)
gruppi.save()
esercizi = DatiEsercizi(
serie = form.cleaned_data['serie'],
ripetizione = form.cleaned_data['ripetizione'],
peso = form.cleaned_data['peso'],
gruppo_single = DatiGruppi.objects.get(gruppi_scheda = scheda.id),
dati_esercizio = form.cleaned_data['dati_esercizio']
)
esercizi.save()
return redirect('/backoffice')
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)
A solution to this would be using the bulk_create method on the object manager with an array/list of the objects to be created
example
ModelName.objects.bulk_create([
ModelName(title="Model1"),
ModelName(title="Model2"),
ModelName(title="Model3"),
])
where ModelName refers to the Name of Your Model, and ModelName within the list refers to the different instances/records of the ModelName class/database to be create in a bulk
I have a problem with a submit form when I want to save the profile ID the form have an error, i dont understand why because in the console all is ok but the form_valis is false, so think because the ModelChoiseField send a pk in sting format so how can i convert the string pk to int pk ?
My Form
class UsuarioForm(forms.ModelForm):
id_perfil = forms.ModelChoiceField(queryset=Perfil.objects.filter(status='1'), label="Perfil" ,empty_label="Seleciona perfil", widget=forms.Select(attrs={'class':'form-control'}))
My Models
class Usuario(models.Model):
id_usuario = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=255)
id_perfil = models.IntegerField()
status = models.CharField(max_length=50)
class Perfil(models.Model):
id_perfil = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=255)
status = models.CharField(max_length=50)
The save method
def save_usuario_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
usuario = form.save(commit=False)
if usuario.status == '':
usuario.status = '1'
usuario.id_usuario_alt = '1'
elif usuario.status == '1':
usuario.status = '2'
form.save()
data['form_is_valid']= True
usuarios = Usuario.objects.filter(status='1').order_by('id_usuario')[:5]
data['html_usuario_list'] = render_to_string('back/Modulo_usuarios/usuarios_list.html',{
'usuarios':usuarios
})
else:
data['form_is_valid']= False
context = {'form':form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
The error
All fields are fill and post method is OK
views.py
#app.route('/new', methods = ['POST', 'GET'])
#login_required
def new():
form = StudentForm()
if request.method == 'POST':
if form.validate_on_submit():
flash('All fields are required.')
return render_template('form.html', action = 'new', form = form)
else:
student = students(
request.form['first_name'], request.form['last_name'], \
request.form['date_of_birth'], \
request.form['date_of_join'], request.form['address']
db.session.add(student)
db.session.commit()
return redirect(url_for('show_all'))
return render_template('form.html', action = url_for('new'), form = form)
#app.route('/edit/<int:id>', methods = ['POST', 'GET'])
#login_required
def edit(id):
item = students.query.get(id)
form = StudentForm(obj=item)
if request.method == 'POST':
if form.validate_on_submit():
item = students.query.get(id)
form = StudentForm(obj=item)
return render_template('form.html', action = url_for('edit',id = id), form = form)
else:
form.populate_obj(item)
db.session.add(item)
db.session.commit()
return redirect(url_for('show_all'))
return render_template('form.html', action = url_for('edit',id = id), form = form)
models.py
class students(db.Model):
__tablename__ = "students"
id = db.Column('id', db.Integer, primary_key = True)
first_name = db.Column(db.String(25))
last_name = db.Column(db.String(25))
date_of_birth = db.Column(db.Date)
date_of_join = db.Column(db.Date)
address = db.Column(db.String(200))
forms.py
class StudentForm(Form):
first_name = TextField("First Name:")
last_name = TextField("Last Name:")
date_of_birth = DateField("Date of Birth:", format='%m/%d/%Y')
date_of_join = DateField("Date of Joining:", format='%m/%d-%Y')
address = TextAreaField("Address:")
submit = SubmitField("Submit")
All other fields are added to the database while adding new item, but the date is not stored. I cant find what the problem actually is. The date field is stored during edit if i use form.validate() for form validation. And if i use form.validate_on_submit() the date field is not stored while adding or editing...
I was trying to dynamically generate fields as shown in http://jacobian.org/writing/dynamic-form-generation/. My case slightly differs in that I am looking to use multiplechoicefield that is dynamically created. This is what I came up with...
views.py
def browseget(request):
success = False
if request.method == 'POST':
list_form = ListForm(request.POST)
if list_form.is_valid():
success = True
path = list_form.cleaned_data['path']
minimum_size = list_form.cleaned_data['minimum_size']
follow_link = list_form.cleaned_data['follow_link']
checkboxes = list_form.cleaned_data['checkboxes']
....do something
else:
list_form = ListForm(name_list)
ctx = {'success': success, 'list_form': list_form, 'path': path, 'minimum_size': minimum_size}
return render_to_response('photoget/browseget.html', ctx, context_instance=RequestContext(request))
forms.py
class ListForm(forms.Form):
path = forms.CharField(required=False)
minimum_size = forms.ChoiceField(choices=size_choices)
follow_link = forms.BooleanField(required=False, initial=True)
def __init__(self, *args, **kwargs):
name_list = kwargs.pop('name_list', None)
super(ListForm, self).__init__(*args, **kwargs)
print 'Received data:', self.data
if name_list:
name_choices = [(u, u) for u in name_list]
self.fields['checkboxes'] = forms.MultipleChoiceField(required=False, label='Select Name(s):', widget=forms.CheckboxSelectMultiple(), choices=name_choices)
def clean_path(self):
cd = self.cleaned_data
path = cd.get('path')
if path == '': path = None
return path
def clean_minimum_size(self):
cd = self.cleaned_data
minimum_size = cd.get('minimum_size')
if minimum_size is None: minimum_size = 0
return int(minimum_size)
The form generates and displays perfectly... until I post some data. The 'checkboxes' field doesn't show up in list_form.cleaned_data.items() while it shows in self.data. As it is the form breaks with a KeyError exception. So Im asking, how do i access the checkboxes data?
You're not passing in the name_list parameter when you re-instantiate the form on POST, so the field is not created because if name_list is False.
Ok, so I'm fairly new to Django, but have been reading both the online django book and the djangoproject documentation, but I can't seem to figure this error out:
I've got an 'Orders' model:
class Orders(models.Model):
client_id = models.ForeignKey(Client)
order_date = models.DateField(auto_now_add = True)
due_date = models.DateField()
completion_date = models.DateField(blank=True, null=True)
rush_order = models.BooleanField(default=False)
billing_option = models.ForeignKey(Billing)
patient_first_name = models.CharField(max_length=30)
patient_middle_name = models.CharField(max_length=30, blank=True)
patient_last_name = models.CharField(max_length=30)
client_patient_id = models.CharField(max_length=30, blank=True)
emodel_patient_id = models.CharField(max_length=30)
special_instructions = models.TextField(blank=True)
order_items = models.ManyToManyField(Order_Items)
def __unicode__(self):
return '%s : %s %s O: %s F: %s' % (self.client_id, self.patient_first_name, self.patient_last_name, self.order_date, self.completion_date)
class Meta:
ordering = ['client_id']
I've got a 'SearchOrderForm' modelform:
class SearchOrderForm(ModelForm):
class Meta:
model = Orders
exclude = ('rush_order', 'billing_option', 'client_patient_id', 'special_instructions', 'order_items',)
and I've got an 'order_status' function:
def order_status(request):
error = False
error_searching = False
if request.method == 'POST':
OrderFormSet = SearchOrderForm()
formset = OrderFormSet()
if formset.is_valid():
cd = formset.cleaned_data()
emodels_results = cd()
emodels_results = cd(queryset = Order.objects.filter(Q(patient_first_name=search)|Q(patient_last_name=search)|Q(client_id=search)))
patient_first_name = request.POST('patient_first_name', None)
if patient_first_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_first_name=patient_first_name))
patient_last_name = request.POST('patient_last_name', None)
if patient_last_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_last_name=patient_last_name))
client_id = request.POST('client_id', None)
if client_id:
emodels_results = emodels_results(queryset = Order.objects.filter(client_id=client_id))
return render_to_response('search_results.html', {'models': emodels_results})
else:
emodels_results = "Still messed up!"
return render_to_response('search_results.html', {'models': emodels_results})
else:
error_searching = True
form = SearchOrderForm()
return render_to_response('order_status.html', {'form': form, 'error': error, 'error_searching': error_searching})
I can fill out my form with no problems, but when I submit the form I get back the following error message:
Traceback:
File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "C:\emodel_tracking..\emodel_tracking\tracker\views.py" in order_status
105. formset = OrderFormSet()
Exception Type: TypeError at /accounts/profile/orderstatus/
Exception Value: 'SearchOrderForm' object is not callable
Does anyone know what I'm doing wrong with my SearchOrderForm that's causing Django to say that it is not callable?
I think you want either of these:
OrderFormSet = SearchOrderForm()
if OrderFormSet.is_valid():
formset = SearchOrderForm()
if formset.is_valid()
With the second way being the preferred syntax style. As a matter of nitpicking, Django offers a FormSet type which is different than the Form type so it is convention to refer to instances of Forms as "form":
form = SearchOrderForm()
if form.is_valid():
You are going to have some other problems with your code:
def order_status(request):
error = False
error_searching = False
if request.method == 'POST':
#instead of:
#OrderFormSet = SearchOrderForm()
#formset = OrderFormSet()
#instantiate an instance of your ModelForm
#(I'd normally name it "form")
formset = SearchOrderForm()
if formset.is_valid():
cd = formset.cleaned_data()
#cd is now a Python dictionary
#these next 2 lines don't make sense, what is your intention?
emodels_results = cd()
emodels_results = cd(queryset = Order.objects.filter(Q(patient_first_name=search)|Q(patient_last_name=search)|Q(client_id=search)))
#you've already used your form to process and clean
#the incoming POST data. use the cleaned data instead
#patient_first_name = request.POST('patient_first_name', None)
patient_first_name = cd.get('patient_first_name','')
#use data from the form's cleaned_data as in the line above
#I'm not sure what your intention is with how the emodels_results
#is but you'll need to rework that for it all to work
if patient_first_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_first_name=patient_first_name))
patient_last_name = request.POST('patient_last_name', None)
if patient_last_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_last_name=patient_last_name))
client_id = request.POST('client_id', None)
if client_id:
emodels_results = emodels_results(queryset = Order.objects.filter(client_id=client_id))
return render_to_response('search_results.html', {'models': emodels_results})
else:
emodels_results = "Still messed up!"
return render_to_response('search_results.html', {'models': emodels_results})
else:
error_searching = True
form = SearchOrderForm()
return render_to_response('order_status.html', {'form': form, 'error': error, 'error_searching': error_searching})