Good evening,
I am new to Django and am working on a sort of ticketing app. My app has three models, Ticket, Status, & Notes.
When displaying the ticket details, I have a form to add a Note. What I want to do is to add to the form a drop down that is set to the current status value of the ticket. When creating the form, how do I pass in the current status value to the form and use it as the default value?
Thanks.
You can set it when calling the form constructor in your view:
form = NoteForm(initial={'status': ticket.status})
Related
My django app connects to a sql server database. On my template I have an editable datatable/formset. Whenever a user edits a field and hits enter, I want only the edited field to be saved. As far as I know AJAX is the only approach to do this, especially if you want the value of the edited field to be the only one transfered to the server. Let's put this case aside for now and accept transferring all data of the formset at once.
Also, the formset is based on a sql server view that includes calculated values. Hence, executing formset.save() will raise an error. Instead I have to use the underlying table to save the modified value. What would be best practice to identify the changed field and save only this one?
Let's say the underlying table is costsperdiem that corresponds to a model in my django app and 'costs' is the name of the editable field I want to save then my approach is as follows:
check if the formset is valid
loop through the forms of the formset using changed_data to seek for the modified field
using a model instance to filter for the modified record
pass the modified value to the model
save the model
which looks like this in code:
formset = FormSet_CostsPerDiem(request.POST)
if formset.is_valid():
for f in formset.forms:
if 'costs' in f.changed_data:
val2save=f.cleaned_data['costs']
id=f.cleaned_data['id_costsperdiem']
rec2save=costsperdiem.objects.filter(pk=id)
rec2save.costs=val2save
rec2save.save()
What is best practice to do something like this?
I'm new to the flask-admin library so please forgive me if this is trivial. When I click 'Save' to create a new row for a model, I also want to do some custom things. In my case, I'll create a table dynamically whose name is the string entered in the form. This will be in addition to what flask-admin does for me i.e. add a new row to the model table. So where will I put the custom logic to do what I want to do? I saw this post on so: Customize (override) Flask-Admin's Submit method from edit view with Joe's answer about overriding on_model_change but I'll like some more explanation. From the docs, it says that on_model_change is called from update_model and create_model. When I click on the source link to the right, I get to: http://flask-admin.readthedocs.org/en/latest/_modules/flask_admin/model/base/#BaseModelView.create_model . It doesn't show the code. So I don't know how it is implemented.
Can someone please illustrate what I'm trying to in a simple sample code? Thanks.
The right way of doing this (as you have mentioned) is through after_model_change function. Quoting Flask-Admin source code
def after_model_change(self, form, model, is_created):
"""
Perform some actions after a model was created or updated and
committed to the database.
Called from create_model after successful database commit.
By default does nothing.
:param form:
Form used to create/update model
:param model:
Model that was created/updated
:param is_created:
True if model was created, False if model was updated
"""
pass
So basically, in your case, you need to perform the table creation inside this function on your model. Namely
class MyModelView(BaseModelView):
column_list = ('fieldX', 'fieldY')
def after_model_change(self, form, model, is_created):
tablename = form.tablename
if is_created: # create the table just once
perform_dynamic_table_creation(conn,tablename)
Is there a way that i can access the values in my form fields before submitting the form.
I need to store the value of one of my fields in request.session[] so as to access it later ( in the same view). I tried doing it using request.GET but it always none.
request.GET.get('name')
where name is the field in a model.
Update
I want to store the value of the form field which is random value generated every time the form is displayed. My models.py contains a random() method which is the default value of the field.
I want to store the field value in sessions, so that i can get the same field value after i return to the page after navigating a few more pages from that page
This is what i was doing:
Django request.session does not resolve
First of all careful when using random in models:
Random/non-constant default value for model field?
Once this is clear I suppose you initialise the form in the view, is there that you need to access the form and get the value for put it in session.
For example
form = MyModelForm();
request.session['your_session_key'] = form.data['field_name']
As far as I understand in some cases you want to set this value in the form from the session instead, for do that you can use the initial data as described here.
https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
Hope this helps
Is here any way to store formset to a session ?
My Scenario is like this . I have a form to fill user data and upload user certificates, and in the next page(form by clicking next) there is a form to enter Professional details .
Is it possible to limit Maximum number of forms generated using a formset?
If I understand your question correctly - how to save a state of the from in a session, then starting with Django 1.4, it actually comes with a way on how to do that out of the box.
https://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-wizard/
It allows you to split a form into multiple section, which then user can fill separately. Once user fills any one section, he/she go to the next page, at which point the state of the form will be saved in a session. Once all the pages are filled, then everything can be saved to a database.
In addition, while going from one page to the other, you add logic of what should be on the next page.
Image that you have a wizard where on the first page it asks what type of content user wants to upload. Then upon going to the second page, then depending on the answer from the first page, appropriate upload fields can be present - field for video, music, or graphics.
I would have answered FormWizard but if you don't want to use it, you can simply create two forms. when the user submit the first one, you pickle it into a session and then you generate the second form. When he clicks on back link, you unPickle saved data and you prefill the form.
def submitFirstForm(request):
data = request.POST['data']
import cPickle
request.session['data'] = cPickle.dumps(data)
...
def backBtn(request):
import cPickle
data = cPickle.loads(request.session['page'])
form = DataForm(data)
...
I built a form in django and I'm having trouble debugging my Tours Choices. It is a ChoiceField and I use the CheckboxMultipleSelect Widget. I don't know what I'm doing wrong to get the error in the screenshot below. Any thoughts? Do I need to facilitate more information? I'm a django newbie.
Picture of the Form Error
A form.ChoiceField lets you input exactly one choice for a form (out of a selection of several choices). If you saved it to a database in a model there would be one value stored in the database. Your CheckboxMultipleSelect widget is for a form.MultipleChoiceField where you can input multiple values. So change your ChoiceField to a MultipleChoiceField in your form and you should be fine. If you save this data to a model, that model would have to be an appropriate field, like a ManyToManyField if they are Foreign Keys.