django mutiupload not working - python

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'))

Related

Multi select checkbox doesnt work creating object in django

I have a app where people can declare things, within a decla they can say who was present so they have to pay, only its not working. The edit function works but the fileDecla doesn't.
The part that doensn't work is the present people. When i print the people present (via print(request.POST))before i save the decla it gives all the people selected but then it doesnt save them, and when i print(decla.present) i get --> None.(it should be all the people present.
Does someone know a solution to this?
models.py
class Decla(models.Model):
owner = models.ForeignKey(Lid, on_delete=models.CASCADE)
event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True, blank=True)
content = models.TextField(max_length=50)
total = models.FloatField()
present = models.ManyToManyField(Lid, related_name="present_leden")
receipt = models.ImageField(
upload_to="declas/", null=True, blank=True
) ## this will need to be put back to nothing when it ends
verwerkt = models.BooleanField(default=False)
views.py
#login_required(login_url="login")
def fileDecla(request):
form = DeclaForm()
if request.method == "POST":
print(1, request.POST)
form = DeclaForm(request.POST, request.FILES)
if form.is_valid():
# print(form)
decla = form.save(commit=False)
decla.owner = request.user.lid
# i tried this line bellow but it didnt work
# decla.present.set(request.POST["present"])
decla.save()
messages.info(request, "Decla was created")
return redirect("agenda")
context = {
"form": form,
"stand": Stand.objects.get(owner_id=request.user.lid.id).amount,
}
return render(request, "finance/decla_form.html", context)
#login_required(login_url="login")
def editDecla(request, pk):
decla = Decla.objects.get(id=pk)
form = DeclaForm(instance=decla)
if request.method == "POST":
print(request.POST)
form = DeclaForm(request.POST, request.FILES, instance=decla)
if form.is_valid():
decla = form.save()
messages.info(request, "Decla was edited")
return redirect(request.GET["next"] if "next" in request.GET else "agenda")
context = {
"form": form,
"stand": Stand.objects.get(owner_id=request.user.lid.id).amount,
}
return render(request, "finance/decla_form.html", context)
forms.py
from django import forms
from django.forms import ModelForm
from django.forms.widgets import NumberInput, CheckboxSelectMultiple
from .models import Decla
class DeclaForm(ModelForm):
class Meta:
model = Decla
fields = "__all__"
exclude = ["owner", "id"]
widgets = {
"present": CheckboxSelectMultiple(),
}
def __init__(self, *args, **kwargs):
super(DeclaForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
if not name in ["verwerkt", "present"]:
field.widget.attrs.update({"class": "input"})
# also tried this
# elif name == "present":
# field.widget.attrs.update({"class": "CheckboxSelectMultiple"})
else:
field.widget.attrs.update({"class": "checkbox"})
Here is something from the docs:
Another side effect of using commit=False is seen when your model has
a many-to-many relation with another model. If your model has a
many-to-many relation and you specify commit=False when you save a
form, Django cannot immediately save the form data for the
many-to-many relation. This is because it isn’t possible to save
many-to-many data for an instance until the instance exists in the
database.
To work around this problem, every time you save a form using
commit=False, Django adds a save_m2m() method to your ModelForm
subclass. After you’ve manually saved the instance produced by the
form, you can invoke save_m2m() to save the many-to-many form data.
According to this, adding save_m2m() after calling decla.save() would resolve your issue:
#login_required(login_url="login")
def fileDecla(request):
form = DeclaForm()
if request.method == "POST":
print(1, request.POST)
form = DeclaForm(request.POST, request.FILES)
if form.is_valid():
# print(form)
decla = form.save(commit=False)
decla.owner = request.user.lid
# i tried this line bellow but it didnt work
# decla.present.set(request.POST["present"])
decla.save()
form.save_m2m()
messages.info(request, "Decla was created")
return redirect("agenda")
context = {
"form": form,
"stand": Stand.objects.get(owner_id=request.user.lid.id).amount,
}
return render(request, "finance/decla_form.html", context)
However, this seems like a messy solution. See this antipattern for more info.
My suggestion is to do this:
#login_required(login_url="login")
def fileDecla(request):
form = DeclaForm()
if request.method == "POST":
print(1, request.POST)
form = DeclaForm(request.POST, request.FILES)
if form.is_valid():
# This seems like a much cleaner solution and it should resolve your problem
form.instance.owner = request.user.lid
decla = form.save()
messages.info(request, "Decla was created")
return redirect("agenda")
context = {
"form": form,
"stand": Stand.objects.get(owner_id=request.user.lid.id).amount,
}
return render(request, "finance/decla_form.html", context)
Disclaimer: the code is untested. Let me know if you have any bugs.

rendered form isnt saving any input into database, why isnt it working?

I tryed to add validation to ContactModel, by doing Forms.py but I went too far away with it and now dont know to fix it. Can someone help ?
def addContact(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# form = Contact(
# full_name = request.POST ('fullname'),
# relationship = request.POST ('relationship'),
# email = request.POST ('email'),
# phone_number = request.POST ('phone-number'),
# address = request.POST ('address'),
# )
form.save()
return redirect('/contact')
context = {'form': form}
return render(request, 'contact/new.html', context)
def contactProfile(request,pk):
contact = Contact.objects.get(id=pk)
return render(request, 'contact/contact-profile.html', {'contact': contact})
In my opinion in Views I have big mess.. When I fill up all fields data isn't sending to database.
forms.py:
from django.forms import ModelForm
from .models import Contact
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
models.py:
from django.db import models
# Create your models here.
class Contact(models.Model):
full_name = models.CharField(max_length=500)
relationship = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
phone_number =models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __str__(self):
return self.full_name
It seems that your form is not valid and it redirects always to contact.
You should to use redirect only if the form is valid. Otherwise you will never see which errors your form contains.
Try the following code:
def addContact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contact')
else:
form = ContactForm()
context = {'form': form}
return render(request, 'contact/new.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.

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.

List uploaded files in django

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

Categories

Resources