List uploaded files in django - python

How can I list files after they have been uploaded? I want to display them so they can be viewed and downloaded later.
Here is my code.
models.py
class UploadFile(models.Model):
file = models.FileField(upload_to='files/%Y/%m/%d')
forms.py
class UploadFileForm(forms.ModelForm): pass
class Meta:
model = UploadFile
views.py
#login_required(login_url='/accounts/login/')
def home(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
new_file = UploadFile(file = request.FILES['file'])
new_file.save()
return HttpResponseRedirect(reverse('main:home'))
else:
form = UploadFileForm()
data = {'form': form}
return render_to_response('upload.html', data,
context_instance=RequestContext(request))

No need to get file back from form and save it - just save it using your model. View have to be something like this:
#login_required(login_url='/accounts/login/')
def home(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save() # saving model instance
return HttpResponseRedirect(reverse('main:home'))
else:
form = UploadFileForm()
data = {'form': form}
return render_to_response('upload.html', data, context_instance=RequestContext(request))
and after this you can take all uploaded files from your model:
files = [upload_file.file for upload_file in UploadFile.objects.all()]
and show them to user

Related

how do I save form data from a different url template

how do I not save the form data until the transaction is done which is in a different URL, if the shipping form and the payment options were to be in the same URL then there wouldn't be this problem but it's not so how do I go about this? thx!
views.py
def checkout(request):
if request.method == 'POST':
form = ShippingForm(request.POST)
if form.is_valid():
new_shipping = form.save(commit=False)
new_shipping.customer = customer
new_shipping.order = order
#how do I not save the data until the transaction is successful
new_shipping.save()
return redirect('store:checkout_shipping')
else:
form = ShippingForm()
else:
form = ShippingForm()
context = {"form": form}
return render(request, 'shop/checkout.html', context)
def checkout_payment(request):
return render(request, 'shop/checkout_payment.html', context)
urls.py
path('checkout', views.checkout, name="checkout"),
path('checkout_payment', views.checkout_payment, name="checkout_payment"),
forms.py
class ShippingForm(forms.ModelForm):
address_one = forms.CharField(max_length=200)
address_two = forms.CharField(max_length=200)
I think what might help is to use sessions. Django will store this temporary data using session cookies. Here's the idea:
from django.forms.models import model_to_dict
def checkout(request):
form = ShippingForm(request.POST or None)
if form.is_valid():
new_shipping = form.save(commit=False)
new_shipping.customer = customer
new_shipping.order = order
request.session['partial-data'] = model_to_dict(new_shipping)
return redirect('store:checkout_shipping')
context = {"form": form}
return render(request, 'shop/checkout.html', context)
def checkout_payment(request):
# I'm guessing here is where the rest of the data
# is to be filled in. The data of the previous view
# is already here stored in the cookie
full-form-data = request.session['partial-data']
full-form-data['extra-field-1'] = 'something'
full-form-data['extra-field-2'} = 'something else'
form = ShippingForm(full-form-data or None)
if form.is_valid():
form.save()
context = {
'form': form
}
return render(request, 'shop/checkout_payment.html', context)

Getiing this error-__init__() got an unexpected keyword argument 'instance'

im using a non-model based form django.
once i get the data,i create a model object.
but when im trying to edit my post(a blog/quote based app),im not able to create a form object using the model object for a specific post.
these are my codes:
views.py:
def quote_form(request):
if request.method=='POST':
form=Quote(request.POST)
if form.is_valid():
quote=form.cleaned_data['quote']
author=form.cleaned_data['author']
popularity=form.cleaned_data['popularity']
category=form.cleaned_data['category']
p=Quote1(quote=quote, author=author, popularity=popularity, category=category)
p.save()
return redirect("quote_list")
else:
form=Quote()
return render(request,'quote/form.html',{'form':form})
def quote_edit(request, pk):
q = get_object_or_404(Quote1, pk=pk)
if request.method == "POST":
form = Quote(request.POST,instance=q)
if form.is_valid():
q = form.save(commit=False)
q.author = request.user
q.save()
return redirect('quote_detail', pk=q.pk)
#return render(request,"blog/post_detail.html",{'post':post})
else:
form = Quote(instance=q)
return render(request, 'quote/quote_edit.html', {'form': form})
models.py:
class Quote1(models.Model):
quote=models.CharField(max_length=200)
author=models.CharField(max_length=200)
popularity=models.IntegerField()
category=models.CharField(max_length=40)
forms.py:
class Quote(forms.Form):
quote=forms.CharField()
author=forms.CharField()
popularity=forms.IntegerField()
category=forms.ChoiceField(choices=[('life','life'),('happiness','happiness'),('love','love'),('truth','truth'),
('inspiration','inspiration'),('humor','humor'),('philosophy','philosophy'),('science','science')])
Try this:
def quote_edit(request, pk):
q = get_object_or_404(Quote1, pk=pk)
if request.method == "POST":
form = Quote(request.POST)
if form.is_valid():
quote=form.cleaned_data['quote']
author=form.cleaned_data['author']
popularity=form.cleaned_data['popularity']
category=form.cleaned_data['category']
q.quote=quote
q.author=author
q.popularity=popularity
q.category=category
q.save()
else:
form = Quote(initial=reauest.POST.copy())
return render(request, 'quote/quote_edit.html', {'form': form})
P.S:
Using ModelForm would have been better approach. If you can switch to ModelForm i can help there as well.

How to make the appearance of form in django?

I am trying to make a form but it is not showing me. Instead it is giving me error UnboundLocalError at /withdraw/ local variable 'form' referenced before assignment How to resolve this issue?
views.py
#login_required
def withdraw(request):
if request.method == 'POST':
form = Withdrawapayment(request.POST)
if form.is_valid():
form.save()
messages.success(request, f'Your request has been submitted.')
return redirect('balance')
context = {'form': form}
return render(request, 'nextone/withdraw.html', context)
models.py
class WithdrawPayment(models.Model):
payment = models.DecimalField(max_digits=100, decimal_places=2)
class Meta:
verbose_name_plural = 'Withdraw Payment'
forms.py
class Withdrawpayment(forms.ModelForm):
class Meta:
model = WithdrawPayment
fields = ['payment']
You are handling for POST request only so change your view like this:
#login_required
def withdraw(request):
if request.method == 'POST':
form = Withdrawapayment(request.POST)
if form.is_valid():
form.save()
messages.success(request, f'Your request has been submitted.')
return redirect('balance')
else:
form = Withdrawpayemnt()
context = {'form': form}
return render(request, 'nextone/withdraw.html', context)

Django form passing key to next form

I want to pass a pk from one form to another so that it can be used as the foreign key for the second form. Here are the model:
models.py
class CompanyDetails(models.Model):
name = models.CharField(max_length=100)
class CompanyDetailsForm(forms.ModelForm):
class Meta:
model = CompanyDetails
class DataRequest(models.Model):
company = models.ForeignKey(CompanyDetails, default="0")
agency_name = models.CharField(max_length=100)
class DataRequestForm(forms.ModelForm):
class Meta:
model = DataRequest
exclude = ['company']
And here is the view for the first form:
views.py
def index(request):
if request.method == 'POST':
form = CompanyDetailsForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.save()
return HttpResponseRedirect(reverse('canareeform:datarequest', data.id))
else:
form = CompanyDetailsForm()
return render(request, 'canareeform/index.html', {'form': form})
How should I set up my second view so that the form will save an object that has the foreign key for the object created by the first form in it?
I got it to work by passing the primary key of the first object through the url. It goes abc.com/form -> abc.com/form/16/datarequest. Not super ideal since by changing the number in the url the second object will use some other foreign key.
views.py
def index(request):
if request.method == 'POST':
form = CompanyDetailsForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.save()
return HttpResponseRedirect(reverse('canareeform:datarequest', args=(data.id,)))
else:
form = CompanyDetailsForm()
return render(request, 'canareeform/index.html', {'form': form})
def datarequest(request, company_id):
if request.method == 'POST':
form = DataRequestForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.company = CompanyDetails.objects.get(pk=company_id)
data.save()
return HttpResponse("Thanks")
else:
form = DataRequestForm()
return render(request, 'canareeform/datarequest.html', {'form': form})
If anyone has a better solution I'd love to hear it.

django mutiupload not working

what im trying to do is upload multiply files at once
the code is pretty old and wondering if any one can help or is there a better way on doing this
here is my code
model.py
class Document(models.Model):
docfile = models.FileField(upload_to=only_filename)
def __unicode__(self):
return self.docfile.name
#models.permalink
def get_absolute_url(self):
return ('upload-delete', )
forms.py
class MyUploadForm(forms.Form):
docfile = MultiFileField(max_num=3, min_num=1, max_file_size=1024*1024*5)
def save(self, commit=True):
super(MyUploadForm, self).save(commit=commit)
for each in self.cleaned_data['docfile']:
att = Attachment(parent=self.instance, file=each)
att.save()
return self.instance
and view.py
#login_required
def list(request):
if request.method == 'POST':
form = MyUploadForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.user = request.user
newdoc.save()
return HttpResponseRedirect(reverse('multiupload.views.list'))
else:
form = MyUploadForm() # A empty, unbound form
documents = Document.objects.all
return render_to_response(
'sample/index.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
I will suggest you use pl-upload jQuery plugin, I personally use this plugin and this is pretty easy and uploading is very fast.
Here are some of example :
Read a blog here
Code example you look here
Maybe it's not a correct way...
Don't override save in forms.py and put create each new object in views after valid() like...
def list(request):
if request.method == 'POST':
form = MyUploadForm(request.POST, request.FILES)
if form.is_valid():
newdoc = form.cleaned_data['docfile']
for file_obj in request.FILES.getlist('docfile'):
Document.objects.create(docfile=file_obj)
return HttpResponseRedirect(reverse('multiupload.views.list'))

Categories

Resources