Django - Problems with PDF upload - python

I got another problem with Django. I want to upload an PDF with an Form in the template, when I click upload in my form, this happens:
Cannot assign "<InMemoryUploadedFile: thebook.pdf (application/pdf)>": "Product.book" must be a "File" instance.
This is the line in my model
book = FilerFileField(null=true,blank=true)
This is the line in my form
book = forms.FileField(label=u"Book Upload")

Django's forms.FileField expects an UploadedFile. Whereby the FilerFileField is actually a subclasses of django.db.models.ForeignKey. Therefor you should use a ChoiceField at your form.
book = forms.ModelChoiceField(queryset=filer.models.File.objects.all())
See also django-filer's usage notes and django's docs on the ModelChoiceField:
http://django-filer.readthedocs.org/en/latest/usage.html
https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield

Related

How to get current app when user is in Django admin?

I need to get from which admin page(app) current request is from in django admin.
Currently request.resolver_match.app_name only returns "admin" which is not what I want.
I have noticed that my app name is in 'view_name' and 'url_name' but is it reliable to parse these variables to access current app name?
Django 1.11 LTS
EDIT: For example, when a user enters admin page for my course app with the above method I still only get 'admin' in my request which should be 'course' not 'admin'. My ultimate goal is to hide some of my app model fields in admin page based on user group.
Thanks
From a ModelAdmin you have access to the model via self.model. In a ModelAdmin method you can thus get the app name using self.model._meta.app_label.
I you need to access it from the template rather than the ModelAdmin, self.model._meta is passed to the context as opts. You can thus access it via {% if opts.app_label == "some_app" %}.
you can simply do this by tracking requested.user i.e who is logged in currently.
something like this
if(requested.user=='admin'):
(show all fields)
else:
(show mentioned fields)
here you are restricting access of your's models fields based on currently logged in user

How to edit formset that has multiple forms inside related via generic foreign to the model of the current edit view?

In my recent project I had to create a generic model with a single file field, because the idea was to use multiple file uploads across multiple system models.
For this I created this generic model with generic foreign key and in the add view I create a formset with the extra = 1 field and in the template via jquery I add forms inside my formset.
In addition it works quietly, but I'm not able to adjust my edit view.
In my edit view I try it:
ModelGenericFormset = modelformset_factory(
ModelsFileGeneric,
form=AddModelsGenericForm
)
query_files = ModelsFileGeneric.objects.filter(
object_id=model_related_to_generic_model_with_file_field.id,
)
files = ModelGenericFormset(queryset=query_files)
and in request.post:
files_form_set = ModelGenericFormset(
request.POST,
request.FILES
)
for file_form in files_form_set:
file = file_form.save(commit=False)
setattr(
'upload_destination',
'path_to_upload'
)
file.content_object = model_related_to_generic_model_with_file_field
file.save()
An observation:
As this model where the file field is is an extremely generic model (for this reason the use of the generic foreign key), I also need at runtime (in the save in view after the post) to change the upload_to attribute of the field (this already Was fixed and works ok).
I make this edition of the "upload_to" attribute because depending on the model to which I am sending multiple files, it will vary the path from where the files will be saved.
But in save of the edit view this error occurs:
The ModelsFileGeneric could not be changed because the data didn't validate.
And the error is in:
file = file_form.save(commit=False)
I don't know what to do anymore. Thanks!

Errors using Django Awesome Avatar

Have been trying to solve an issue using Django awesome avatar. I have used the AvatarField() in my models to save the profile pic in the UserProfile model.
avatar = AvatarField(upload_to=upload_profile, width=100, height=100,default = 'profiles/profile.jpg',)
Have also used a ModelForm to render the field to a form that is shown on the templates
avatar = avatar_forms.AvatarField()
When I try to access the user profile in admin and save, it throws an error:
'ImageFieldFile' object has no attribute '__getitem__'
Also, when I select a photo on the form in template, it does not show the crop tool that am supposed to use to resize the image.
Are you trying to access the file name?
You should use something like this:
def __unicode__(self):
return unicode(self.image_location)
source: Django image field throws TypeError

400 error on django filefield model save

I'm using django 1.6.5 on python 2.7, and am trying to upload images with a form. My MEDIA_URL is '/uploads', MEDIA_ROOT='...../projectroot/uploads'.
My model:
class Picture(models.Model):
person = models.ForeignKey(User)
image = models.ImageField(upload_to='/images')
My Form field:
images = forms.ImageField(widget=forms.FileInput(), required=False)
My form saving:
image = self.cleaned_data['images']
picture = Picture(park=model, image=image)
picture.save()
I have tried setting the uploads folder permissions to 777 recursively, so django definitely has write access, but that didn't work. Somebody said the enctype on the form mattered, so I've set that to "multipart/form-data".
If it helps, only the actual saving creates the error (although that may have something to do with django just using lazy functions)

Django registration-profile - next step to a user profile

I have installed the django-registration app to my project. After a successful log in step, I am redirecting the user to localhost:8000/ - this is my default testing host and port. And I am displaying somewhere on the page, the username of the logged in user.
What I want to do now is that when I click the username some options like edit profile or change password will appear. My questions are the following:
Should I create another model (inside another new app) containing fields like profile photo, gender, birthday etc and add a foreign key to the User model from django.contrib.auth.models ? Or should I modify the model from django-registration to add some additional fields but which I do not ask for at registration phase and only update them later?
if I want my profile edit feature to be at /accounts/edit, which would be the best practice to do it? to edit the URLconf of my project and add a line like (r'^accounts/edit$',.....) just before (r'^accounts/', include('registration.backends.default.urls')), ?
I hope I made myself clear. I'm trying to figure out which would be the best approach before coding, as I am new to Django... Thanks
I find it's easier to decouple the profile table from the auth table. Just like you mentioned you can use a foreign key relationship to link that profile to the user. You can also apply a lambda inside of your profile table to automatically create a profile when a new user object is created.
Inside your template you can link to the profile page dynamically based on the current authenticated party by using
{% if request.user.is_authenticated %}
Update Profile
{% endif %}
user_profile being the name of your app which holds your user_profile table. That way when the request is made you use the regular expression for the current user id (similar to the polls example provided by django) to get the id number of the currently logged in user than inside the views you just query the database for that particular user.
views.py
def myView(request, user_id):
userProfile = UserProfile.objects.get(user.pk=user_id)
This is a high level example to give an idea of one way to accomplish it.

Categories