Initialize Django Form FileField - python

I have a Django form class like;
class FileDefinitionForm(ModelForm):
fileContent = forms.FileField(required=False)
def __init__(self, *args, **kwargs):
super(FileDefinitionForm, self).__init__(*args, **kwargs)
????Initialization of file field which is named "fileContentUpl" ???
I have my file as string which is base64 decoded and I need to put the file to my fileField on initialization to show it in html. I tried someting but i couldn't make it works. Is there a way to do this ?
Thank You.

Related

Django EventLog: Passing in current user

I am trying to add logging to my Django app using EventLog. I followed an example online but not sure how to pass in the user that makes the changes. The example shows it as user=self.user. Obviously this wouldn't work in my case as it doesn't refer to anything in my model
models.py
class Client(models.Model):
name = models.CharField(max_length=50)
....
def save(self, *args, **kwargs):
# Initial Save
if not self.pk:
log(user=self.user, action='ADD_CLIENT',
extra={'id': self.id})
else:
log(user=self.user, action='UPDATED_CLIENT',
extra={'id': self.id})
super(Client, self).save(*args, **kwargs)
The save method will only know what has been passed into it, this will normally not include the request which is where you would get the current user (request.user).
You should instead add logging in the view which is calling the save method.
user = request.user

How to exclude fields from django forms.Form?

I guess this is another simple question on django forms that I am struggling to find an answer for.
Say I have the following
class Form1(forms.Form):
a=forms.CharField( label=_("A"),max_length=40)
b=forms.CharField( label=_("B"),max_length=40)
class Form2(forms.Form):
c=forms.CharField( label=_("C"),max_length=40)
d=forms.CharField( label=_("D"),max_length=40)
class Form3(Form1,Form2):
def __init__(self, *args, **kw):
Form1.__init__(self,*args, **kw)
Form2.__init__(self,*args, **kw)
#Here I don't want to have a from Form1
# how can I exclude it so that validation does not bark??
I tried exclude=(a,) in Meta class defined in Form3 but does not work, form validation keeps failing form me.
Thanks in advance
Have you tried:
def __init__(self, *args, **kwargs):
super(Form3, self).__init__(*args, **kwargs)
del self.fields['a']
You can override the field and set it to None
class Form3(Form1,Form2):
a = None
Below is the reference:
https://code.djangoproject.com/ticket/8620#no1

Django. self.file.path does not include upload_to subdirectory

I'm trying to get some information from a file before the Model is saved to the database.
So basically what i'm doing it is overwriting method save like follow:
class Media(models.Model):
file = models.FileField(upload_to='audio/')
def save(self, *args, **kwargs):
if not self.id:
print self.file.path
super(Media, self).save(*args, **kwargs)
But when I print attribute self.file.path is does not include "audio/" subdirectory.
Instead of this '/Users/me/Dropbox/Public/music/audio/myfile.ext'
I'm getting
'/Users/me/Dropbox/Public/music/myfile.ext'
The file is located where it suppose to be. In
'/Users/me/Dropbox/Public/music/audio/myfile.ext'
My
MEDIA_ROOT = '/Users/me/Dropbox/Public/music'
What I've missed?
UPDATE:
Looks like it add 'audio/' to the path after it save the model.

How do I override this method on a Django Model Field

I'm trying to modify an existing Django Mezzanine setup to allow me to blog in Markdown. Mezzanine has a "Core" model that has content as an HtmlField which is defined like so:
from django.db.models import TextField
class HtmlField(TextField):
"""
TextField that stores HTML.
"""
def formfield(self, **kwargs):
"""
Apply the class to the widget that will render the field as a
TincyMCE Editor.
"""
formfield = super(HtmlField, self).formfield(**kwargs)
formfield.widget.attrs["class"] = "mceEditor"
return formfield
The problem comes from the widget.attrs["class"] of mceEditor. My thoughts were to monkey patch the Content field on the Blog object
class BlogPost(Displayable, Ownable, Content):
def __init__(self, *args, **kwargs):
super(BlogPost, self).__init__(*args, **kwargs)
self._meta.get_field('content').formfield = XXX
My problems are my python skills aren't up to the task of replacing a bound method with a lambda that calls super.
formfield is called by the admin when it wants to create a field for display on the admin pages, so I need to patch that to make the BlogPost widget objects NOT have the class of mceEditor (I'm trying to leave mceEditor on all the other things)
How do you craft the replacement function? I'm pretty sure I attach it with
setattr(self._meta.get_field('content'), 'formfield', method_i_dont_know_how_to_write)
You could change the used formfield in the admin's method formfield_for_dbfield:
class BlogAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
field = super(BlogAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'content':
field.widget = ....
field.widget.attrs['class'] = ...
return field
If you really want to do the monkey-patching, it should be something like that:
class BlogPost(Displayable, Ownable, Content):
def __init__(self, *args, **kwargs):
super(BlogPost, self).__init__(*args, **kwargs)
def formfield_new(self, *args, **kwargs):
# do here what you would like to do
return formfield
instancemethod = type(self._meta.get_field('content').formfield)
self._meta.get_field('content').formfield = instancemethod(formfield_new,
self, BlogPost)
I realize this question was answered several months ago, but just in case anyone else comes across it, Mezzanine now provides the ability to completely modify the WYSIWYG editor field. Take a look a the docs for it here:
http://mezzanine.jupo.org/docs/admin-customization.html#wysiwyg-editor

Django Forms not rendering ModelChoiceField's query set

I have the following ModelForm:
class AttendanceForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
operation_id = kwargs['operation_id']
del kwargs['operation_id']
super(AttendanceForm, self).__init__(*args, **kwargs)
self.fields['deployment'].query_set = \
Deployment.objects.filter(operation__id=operation_id)
class Meta:
model = Attendance
When I manually create the form in the shell (using manage.py shell)
form = AttendanceForm(operation_id=1)
form.fields['deployment'].query_set
it returns the correct query_set, but when I call
form.as_p()
i get extra entries that weren't in the query_set? Does django cache the html output somehow? I looked through the source, but couldn't find any caching. What am I doing wrong?
The parameter is queryset, not query_set. See the documentation.

Categories