Insert django form into template dynamically using javascript? - django

I want to add same django form instance on same template. i already add one before and other add dynamically using javascript.
for example 'form" is a django form: newcell.innerHTML = {{ form.firstname }};
The problem is that when i submit the form, in view the request object has only one value (that is not add using javascript). how can i get the values of other form elements values that is added dynamically runtime.
It is something like the "Attach Another File" feature in gmail, where the user is presented with a file upload field and new fields are added to the DOM on the fly as the user clicks to "Attach Another File" plus button

You could always try separating out your FileField into a FileModel.
Take a look at the following pseudo code (as in python based on memory--i've moved over to clojure for now).
models.py
class FileModel(models.Model):
file = models.FileField()
...
class ThingToWhichYoureAttaching(models.Model):
name = models.CharField()
attachments = models.ManyToManyField(FileModel)
...
forms.py
class FileForm(forms.ModelForm):
class Meta:
model=FileModel
class ThingForm(forms.ModelForm):
attachments = forms.MultipleChoiceField()#override the manytomany form field with style field of your choice.
class Meta:
model=ThingToWhichYoureAttaching
When they pop up the window with the PLUS button, show the FileForm but on the main page leave the ThingForm untouched. You can also have an initial FileField on the main page with the ThingForm for people who don't have javascript. Just make sure to process the FileForm BEFORE the ThingForm so that the File is available for the Thing.
When processing the popup form you can use AJAX (i recommend jquery) to submit the FileForm to the server, and return the markup to insert the File in the Attachments field.

Related

read only attribute is safe in django forms?

Setting read only attrs for django forms is safe?. In my django projects I do something like this:
def someUpdateView(request):
form = EmployeeForm(instance=Employeem.objects.get(pk=1))
return render...
class EmployeeForm(forms.ModelForm)
declaring here read only attrs field by widgets dict in Meta class or in init method (i.e. pk fields or other fields like email for keeping inmutable).
But what if an user opens web browser inspector mode and edits html field value or deletes read only attribute? during form.save() django will save the new value even it was read only (from html) and if this happens, there is a way to handle that?.

How to create foreign key linked fields in forms just like in Django Admin?

In django admin, you can add, edit, and even delete objects from another model if there is a relationship between the two.
For instance, if my code looks like this:
class Category(models.Model):
...
class Product(models.Model):
...
category = models.ForeignKey(Category)
When I am editing/adding a product using the django admin site, in the category field, I have 3 buttons to add/edit/delete categories. Adding one takes to a new window, and once I submit the form, the category is added, the window is closed, and I am returned to my product form with the extra category present. Like this:
How can I do this in my normal application (outside the admin) using forms?
If I understand your question correctly, you could do what django admin does, which is to link the add button to this:
/admin/<your_app>/<your_model>/add/?_to_field=id&_popup=1
and then it uses a bit of javascript to get back the new object you just created. If you look into the contrib/admin/static/admin/js/admin/RelatedObjectLookups.js file (in django's code), you'll see a few functions that pass the id of the calling field to the popup (in showRelatedObjectPopup), and then bring back the selected id (in dismissRelatedLookupPopup).
This is for adding a new object, but you can look into the logic for changing/deleting.
You can replicate that logic with your own forms.

How to tell if user changed file in django ModelForm

I have a django ModelForm with an image field. I want to resize the image when the user submits the form, but only if they uploaded a new image. My code looks like this:
class EditProfileForm(forms.ModelForm):
class Meta:
model = Person
fields = ['picture', '...']
def clean_picture(self):
picture = self.cleaned_data['picture']
if picture.file: #This isn't right though
#resize it
return picture
However it seems like picture.file always exists if the model being edited contains a file. I know I can check request.FILES back in the view, but that's very inelegant. Is there a better way?
In general, you can do this with self.changed_data, which returns a list of the names of the fields where the value changed. Whether there's anything special about a FileField that would interfere I don't know offhand.
In js,
In JS, set a global variable file_changed = 0.
HTML input tag < input ng-model="avatar" type="file" onchange="ChangeFile()">
Lets say ChangeFile() will provide a small preview of the file to be uploaded
In function ChangeFile set file_changed=1 once the file is selected.

list of textareas in django forms

I have a cms-like page where users can create their own simple pages, with a title, image and some content. The form I'm using for it is the following:
class PageForm(forms.Form):
"""
Helper form for the cms backoffice page.
"""
title = forms.CharField(max_length=50)
preview_image = forms.ImageField(required=False)
content = forms.CharField(widget=TinyMCE(attrs={'cols': 20, 'rows': 10}))
But now I want to enhance this by adding multiple sections to a page. The thing is these are optional, so user can choose to only leave one section, in which case this form should do it, but then have a button 'add section' or something which can will add an extra TinyMCE and ImageField to the UI, also Delete section will delete one.
Now the way I see it this is a long shot, but is there any way I could model this using django forms? The way I'm thinking now if I limit the number of forms to a given number, I could add content_i and preview_image_i to the form and then check which one were submitted. That should work right? Is there any way to do it without a maximum number of sections? Otherwise how much of an overhead would I be adding if I add 100 CharFields / ImageFields which would be used rarely to a full extent (if at all).
Or should I just abandon django forms for this and do some custom handling?
Thanks

Pagedown(markdown editor) with Django

I trying to use the pagedown(markdown editor), the one that stackoverflow in my django based website. However to get the markdown editor in a textarea it is required to give the text area both id and class as
<textarea id="wmd-input" class="wmd-input"/>
However the form fields generated by django have a default id as id_<field-name>. Is there a way I can assign the same id to this text_area?
you can directly pass id as well in the models.py where your are passing class name. This will override the default behavior.
widgets = {
'<attribute_name>': Textarea(attrs={'class':'wmd-input','id':'wmd-input'}),
}