'Document' object is not subscriptable Django - python

I am getting this error while uploading the excel file and saving that file.
My model.py file
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
In view i am saving that file to specific location
views.py file is
def excel(request):
print "you in main"
if request.method == 'POST':
print "you in post"
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
path = os.path.join(settings.MEDIA_ROOT, newdoc)
print path
print "you in"
newdoc.save()
wb = xlrd.open_workbook(path)
sh = wb.sheet_by_index(0)
c = 1
while c < len(sh.col(0)):
first = sh.col_values(0)[c]
second = sh.col_values(1)[c]
c=c+1
return HttpResponseRedirect(reverse('upload.views.excel'))
else:
form = UploadFileForm() # A empty, unbound form
documents = Document.objects.all()
return render_to_response('property/list.html',{'documents': documents, 'form': form},context_instance=RequestContext(request))
My html file is
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li>{{ document.docfile.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="/property/excel/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
Error i am getting is
TypeError at /property/excel/
'Document' object is not subscriptable
Request Method: POST
Request URL: http://127.0.0.1:8000/property/excel/
Django Version: 1.5
Exception Type: TypeError
Exception Value:
'Document' object is not subscriptable
Exception Location: C:\Python27\lib\ntpath.py in splitdrive, line 125
Please help me out to solve this problem

your problem is here:
path = os.path.join(settings.MEDIA_ROOT, newdoc)
^ newdoc is a model instance and you don't want the model itself to be a part of your path - you want the uploaded file path there, thus:
path = os.path.join(settings.MEDIA_ROOT, newdoc.docfile)

Related

How can i delete user images/avatar in user profile

if there's anyone who knows how can I delete images user, I made a code to do that but I cannot continue I get some stuck. so if anyone could tell me which way can I make it this method?
also, I need to know about the outputs of (userprofile) in (delete_avatar) if this code is true how can I know it? I tried using print and repr but I didn't find this useful. so, anybody can get me help?
views.py
# Update Avatar
#login_required
def add_avatar(request, user_id):
my_logo = request.user.userprofile
form = AddAvatar(instance=my_logo)
get_userid = UserProfile.objects.filter(user_id=user_id)
context = {'form': form, 'get_userid': get_userid}
if request.method == 'POST':
form = AddAvatar(request.POST, request.FILES, instance=my_logo)
if form.is_valid():
form.save()
return redirect('account:view_profile')
return render(request, 'account/change-image.html', context)
# Remove Avatar
#login_required
def delete_avatar(request, user_id):
my_request = request.POST.get('rm-img')
userprofile = UserProfile(my_request)
pdb.set_trace()
if request.method == "POST":
del_img = UserProfile.objects.get(user_id=user_id).logo.delete() # delete object
return redirect('account:view_profile')
return render(request, 'account/change-image.html')
change-image.html
{% extends 'base.html' %}
{% block title %} Add New Image {% endblock %}
{% block body %}
<!-- Add new image for user-profile -->
<div class="change-image">
<div class="add-image">
<div class="container">
<h1>This Image Is Current, <br>Choose Your Image From Your Personal Computer Or Delete</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<label>{{ user.first_name }} {{ user.last_name }}</label>
{{ form.as_p }}
<button type="submit" class="btn btn-success">Change Now</button>
<input type="submit" name="rm-img" class="btn btn-danger" value="Remove Image">
</form>
</div>
</div>
</div>
{% endblock %}
the file html above where I can make a form to update and delete the user image
urls.py
urlpatterns = [
path('new-image/<int:user_id>/', views.add_avatar, name="add_avatar"),
path('del-image/', views.delete_avatar, name="delete_avatar"),
]
forms.py
class AddAvatar(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['logo']

Django: form as image

I have a simple form in my template, index.html:
{% if stripped_thumbnail_file_list %}
{% for thumbnail_name in stripped_thumbnail_file_list %}
<div class="">
<div class="">
This is my form
<form class="" action="{% url 'index' %}" method="post">
{% csrf_token %}
<input type="image" value="{{ thumbnail_name }}" src="{{ MEDIA_URL}}thumbnails/{{ thumbnail_name }}.jpg">
</form>
</div>
</div>
{% endfor %}
{% else %}
<p>No videos are available.</p>
{% endif %}
I want the index view to pull the {{ thumbnail_name }} value from this form and use it as a variable when the index view redirects to a different view that will use that name to play a matching video.
I have been unsuccessful in trying to pull that value from the form as I have it. I suspect this may because I'm not creating a Django form object. I tried to create that object, but I can't find any examples of a Django form object as an image like I have in my form.
What should that look like? Or, can someone make a recommendation on how to pull the value from the form as is?
EDIT: adding views.py snippet:
def index(request):
# if this is a POST request we need to process the form data
if request.POST:
# get thumbnail_name from form
# redirect to a new URL (hardcode thumbnail name for now):
return HttpResponseRedirect('2017-02-01_04-29-10/video/')
thumbnail_file_list = get_file_list(target_directory, ".jpg")
stripped_thumbnail_file_list = strip_file_extension(thumbnail_file_list)
template = loader.get_template('dash/index.html')
context = {
'stripped_thumbnail_file_list': stripped_thumbnail_file_list,
}
return HttpResponse(template.render(context, request))
def video(request, file_name):
print("this is the file name passed: " + file_name)
template = loader.get_template('dash/video.html')
context = {
'file_name': file_name,
}
return HttpResponse(template.render(context, request))
First: you need to declare the 'name' attribute on your form imput.
<input name="thumbnail_name" type="image" value="{{ thumbnail_name }}" src="{{ MEDIA_URL}}thumbnails/{{ thumbnail_name }}.jpg">
Second: Why don't you just set the 'action' of the form to your 'video' function (when you perform a redirect, you are losing all your POST data).Then, from there you could retrieve the value: something like that
def video(request):
file_name = request.POST.get('thumbnail_name')
print("this is the file name passed: " + file_name)
template = loader.get_template('dash/video.html')
context = {
'file_name': file_name,
}
return HttpResponse(template.render(context, request))
Hope it helps

Django management form missing or tampered with - management form is in the template

I have a template with lots of forms on it, all wrapped in one form element. I have on MultiForm that is comprised of 4 regular forms, and two formsets. The formsets have been overridden to use custom formset classes.
I render the management forms in the templates, and can see the relevant info in the post.
For the formsets, I initialize the page with only one form visible.
When I try to submit the combined form I get the following error:
ManagementForm data is missing or has been tampered with
I have searched everywhere for the answer, and read about 15 posts on stack overflow with the same error, but none of the solutions seem to help.
The error page highlights the following line:
{{ beneficiaries.management_form }}
Template:
<form class='pension_form' id='implementation_form' action="{% url "confirmation_form" %}" method="post">
{% csrf_token %}
<ul>
{{ the_form.user_info.as_ul }}
</ul>
<ul>
{{ the_form.spouse_info.as_ul }}
</ul>
<div class='formset_container'> {{ children.management_form }}
{% for form in children %}
<div class='formset'><ul>{{ form.as_ul }} </ul><a class="glyphicon glyphicon-plus"></a></div>
{% endfor %}
</div>
<ul>
{{ the_form.employer_info.as_ul }}
</ul>
<ul>
<li>{{ the_form.beneficiary_general.WHO_BENEFITS }}</li>
</ul>
<div id='beneficiary_info_container' style='display:none;'>
<div class='formset_container'>
{{ beneficiaries.management_form }}
{% for form in beneficiaries %}
<div class='formset' >
<ul>{{ form.as_ul }}</ul><a class="glyphicon glyphicon-plus"></a></div>
{% endfor %}
</div>
<ul><li id='inheritance_order'>
{{ the_form.beneficiary_general.BENEFICIARIES_DIE.label_tag }}
{{ the_form.beneficiary_general.BENEFICIARIES_DIE }}
</li>
</ul>
</div>
<button class='btn btn-default main-btn'>{% trans "_Continue" %}
</form>
View:
def show_confirmation_form(request):
ChildFormSet = formset_factory(ChildInfo, formset=ChildInfoFormSet,
extra=14, can_delete=True)
BeneficiaryFormSet = formset_factory(BeneficiaryInfo, formset=BeneficiaryInfoFormSet,
extra=10, can_delete=True)
multi_form_prefix = 'main_form'
child_prefix = 'children_info'
beneficiary_prefix = 'beneficiary_info'
if request.method == 'POST':
form = ConfirmationForm(request.POST, prefix=multi_form_prefix)
children_forms = ChildFormSet(request.POST, prefix=child_prefix)
beneficary_forms = BeneficiaryFormSet(request.POST,
prefix=beneficiary_prefix)
if form.is_valid():
#not ready yet
return HttpResponseRedirect('/thanks/')
else:
form = ConfirmationForm(prefix=multi_form_prefix)
children_forms = ChildFormSet(prefix=child_prefix)
beneficary_forms = BeneficiaryFormSet(prefix=beneficiary_prefix)
context = {'the_form' : form, 'children' : children_forms,
'beneficiaries' : beneficary_forms}
return render(request, "confirmation_form.html", context)
Forms.py
class BeneficiaryInfo(forms.Form):
SHEM_PRATI_MUTAV = forms.CharField(label=_("First_Name"))
SHEM_MISHPACHA_MUTAV = forms.CharField(label=_("Last_Name"))
MISPAR_ZEHUT_MUTAV = forms.IntegerField(label=_("Mispar_Zehut"))
ACHUZ_HALUKA = forms.IntegerField(label=_("Percent_Allocate"))
class BeneficiaryInfoFormSet(BaseFormSet):
def clean(self):
"""
Adds validation to check that no two links have the same anchor or URL
and that all links have both an anchor and URL.
"""
if any(self.errors):
return
teudot_zehut = []
distribution_total = 0
for form in self.forms:
if form.cleaned_data:
teudat_zehut = form.cleaned_data['MISPAR_ZEHUT_MUTAV']
#allow empty forms.
if teudat_zehut:
if teudat_zehut in teudot_zehut:
form.add_error(None, 'No mutavim can share teudot_zehut')
distribution_total += int(form.cleaned_data['ACHUZ_HALUKA'])
if distribution_total != 100:
form.add_error(None, 'Distribution Total must be 100')
In case someone runs into a similar problem:
The problem was the I only showed the formsets if a certain checkbox was checked, and the management form was in the hidden area. I moved it out of the div that was hidden and it worked perfectly.

Django upload only csv file

I am trying to import csv file i am able to import without any problem but the present functionality accepts all file types, i want the functionality to accept only csv file. below is the view.py and template file.
myapp/views.py
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
importing_file(request.FILES['docfile'])
myapp/templates/myapp/index.html
<form action="{% url 'ml:list' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload"/></p>
</form>
EDIT
I could find a workaround by adding validate_file_extension as per the
django documentation
myapp/forms.py
def validate_file_extension(value):
if not value.name.endswith('.csv'):
raise forms.ValidationError("Only CSV file is accepted")
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file',validators=[validate_file_extension])
form widget to validate file extension
csv_file = forms.FileField(widget=forms.FileInput(attrs={'accept': ".csv"}))
added code snippet to the forms.py file to validate file extension and now it is working fine.
def validate_file_extension(value):
if not value.name.endswith('.csv'):
raise forms.ValidationError("Only CSV file is accepted")
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file',validators=[validate_file_extension])

Inline formset not rendering form field

I have models:
class MediaInfo(models.Model):
title = models.CharField(max_length=50,blank=True)
description = models.CharField(max_length=255,blank=True)
media_file = models.FileField(upload_to=get_upload_file_name)
def __unicode__(self):
return self.title
class Media(models.Model):
media_files = models.ForeignKey(MediaInfo) # I want ManyToManyField but it gives error saying no ForeignKey relation
Here I used Inline Formset to select multiple file.
What I wanted was I wanted a browser button on template and when I click that I could select multiple file or images with all those title and description informations.
For this I wrote a view:
def MediaAddView(request):
MediaInlineFormset = inlineformset_factory(MediaInfo, Media)
if request.method == "POST":
formset = MediaInlineFormset(request.POST, request.FILES)
if formset.is_valid():
formset.save()
return HttpResponseRedirect("someurl")
else:
return render_to_response("media_add.html", {"formset":formset,})
else:
formset = MediaInlineFormset()
return render_to_response("media_add.html", {"formset":formset,})
and my template media_add.html
{% block content %}
<form method="post" action="" enctype="multipart/form-data">{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{form.id}}
<ul>
<li>{{form.media_file}}</li>
</ul>
{% endfor %}
<input type="submit" value="Submit" />
</form>
{% endblock %}
When I do this in my template I see nothing just 3 dots of list (li).
Like I said I wanted a browse button and when I click it I wanted to select and upload multiple files.
Whats wrong in here ? Can anyone guide me ?

Categories