Django File upload looping - django

How would I best loop a form like this (there is other code in the form but this is an example for image uploading)
<form action="{% url "upload" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="image_file">
<input type="file" name="image_file2">
<input type="file" name="image_file3">
<input type="file" name="image_file4">
<input type="file" name="image_file5">
<input type="submit" value="submit" />
</form>
for single file uploading but need it multifile uploading:
def image_upload(request):
if request.method == "POST" and request.FILES["image_file"]:
image_file = request.FILES["image_file"]
fs = FileSystemStorage()
filename = fs.save(image_file.name, image_file)
image_url = fs.url(filename)
print(image_url)
return render(request, "upload.html", {
"image_url": image_url
})
return render(request, "upload.html")
Just not sure how to loop it so images are stored along with filename in a var for the db (at a later point) also just a thought, might not always be uploading all five files could be three or none

Related

Uploading image is not creating media file

Guys I'm new to django I tried uploading images in the imagefield but it's not creating media folder and the database image column is also blank.
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
class Profile(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(upload_to='images/')
image.html
<form method="POST" enctype="multipart/form-data>
{% csrf_token %}
<input type="file" class="form-control" id="customFile" name="image"/></div>
<input type="text" class="form-control" name="name" placeholder="">
</div>
</form>
views.py
def hotel:
if request.method == "POST" :
post=Profile()
post.image= request.POST.get('image')
post.name = request.POST.get('name')
post.save()
return redirect('/vendor_dashboard/profile_pic')
return render(request,'profile.html')
Even tried manually creating the media file Django.
Still nothing!!
Any help Will be appreciated
Uploaded files are in request.FILES instead of request.POST. So your file handling should look like this:
# post.image= request.POST.get('image')
post.image = request.FILES['image']
I'd recommend to read the Django docs about file uploads
use request.FILES:
def hotel:
if request.method == "POST" :
post=Profile()
post.image= request.FILES['image']
post.name = request.POST.get('name')
post.save()
return redirect('/vendor_dashboard/profile_pic')
return render(request,'profile.html')
You have to include {{form.media}} to the django form template if you want to post any type of media to django
<form method="POST" enctype="multipart/form-
data>
{% csrf_token %}
{{form.media}}
<input type="file" class="form-control"
idd="customFile" name="image"/></div>
<input type="text" class="form-control"
name="name" placeholder="">
</div>
</form>
edit:
and in views.py you have to use request.FILES to get any media file(forgot to mention this)
request.FILES.get('image')
and to get the image from media use .url
{% Profileobject.image.url %}

How to get the value of a specific field in a form in Django view function?

I am trying to achieve a load-up process in my system where the user will input the load amount and add it to a user's current load.
How can I get the amount entered in my view function?
Here's my function in my views.py
def LoadWallet(request, pk):
user = get_object_or_404(User, id=request.POST.get('user_id'))
user_wallet = user.wallet
if request.method == 'POST':
form = LoadForm(request.POST)
if form.is_valid():
user_wallet = user_wallet+form.instance.load_amount
User.objects.filter(id=pk).update(wallet=user_wallet)
return HttpResponseRedirect(reverse('user-details', args=[str(pk)]))
and the form in my template file
<form action="{% url 'load-wallet' user.pk %}" method="POST">
{% csrf_token %}
<label for="load_amount">Load amount</label>
<input type="text" class="form-control" id="load_amount" onkeyup="replaceNoneNumeric('load_amount')">
<button type="submit" name="user_id" value="{{ user.id }}" class="btn btn-md btn-success" style="float: right; margin: 10px 5px;">Load</button>
</form>
Right now I tried this but it's returning "name 'LoadForm' is not defined". Should I declare the LoadForm first?
Is there a better way to implement this? Thank you!
You might have an easier time using something like this, than LoadForm:
def LoadWallet(request, pk):
user = get_object_or_404(User, id=request.POST.get('user_id'))
user_wallet = user.wallet
if request.method == "POST":
user_id = request.POST["user_id"]
# Other logic here
return ...
And in template
<form class="load-wallet" action="" method="POST">
{% csrf_token %}
<input type="text" name="user_id" placeholder="What is the user id?">
<button type="submit" class="submit-btn"> Submit </button>
</form>

How to check request.FILES is black or not in Djnago?

I am using Djnago.i Have html Form such as below,
<form method="POST" action="{% url 'someaction' %}" enctype="multipart/form-data">
<input type="file" name="image" id="image">
</form>
How to check request.FILES['image'] is Selected or not in djnago view file?
Do:
image = request.FILES.get('image')
if image is None:
# request.FILES['image'] is not posted

Access GET request in another method django

I have a form elements in my html.
<form action="" method="GET">
<input type="text" name="start_date" placeholder="From" value="{{ request.GET.start_date }}">
<input type="text" name="end_date" placeholder="To" value="{{ request.GET.end_date }}">
</form>
I want to access to the start_date and end_date inside one of my view.py methods, but Im getting None all the time.
So far I have tried:
temp = request.GET.get('start_date', None)
temp = request.GET['start_date']
What might be the problem? How can I access start_date and end_date?
EDIT: Im tring to access it in this method:
def download_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s' % 'invoice.pdf'
books = books.objects.all()
date = request.GET.get('start_date', None)
books.filter(order__date = temp)
c = canvas.Canvas(response)
c.drawText(date)
c.showPage()
c.save()
return response
You can get the start_date and end_date once you submit that form. Like POST method GET form also expect you to submit from the frontend.
<form action="." method="GET">
<input type="text" name="start_date" placeholder="From" value="{{ request.GET.start_date }}">
<input type="text" name="end_date" placeholder="To" value="{{ request.GET.end_date }}">
<input type="submit" value="submit">
</form>
Or forget the form method just append the parameter in the url is enough. Like this...
http://localhost:8000/?start_date=test_start_date&end_date=test_end_date
Edit:
You have to check the GET dictionary before accessing. Because start_date will be not be present in the every GET request. Once the user submitted the GET request then we can access the GET parameter....
start_date = request.GET.get('start_date')
if start_date:
print(start_date)
Edit 2:
# Create your views here.
def index(request):
start_date = request.GET.get('start_date')
if start_date:
print(start_date)
return render(request, 'base.html')
# base.html
<form action="." method="GET">
<input type="text" name="start_date" placeholder="From" value="testing">
<input type="text" name="end_date" placeholder="To" value="testing">
<input type="submit" value="submit">
</form>

Using <form> to update BooleanField in Django

Using Django 1.6 with Python 2.7.
My model has a BooleanField variable, and I want the user to be able to change this via POST by clicking a button to change it from False to True, or vice versa. Having issues rendering the template.
Model currently:
class Pic(models.Model):
Name = models.CharField(max_length=100)
Good = models.BooleanField()
Image = models.FileField(upload_to="images/")
def __unicode__(self):
return self.Name
App urls is:
url(r'^(?P<Pic_id>\d+)/$', views.single_picture, name='single_picture'),
In the template I have:
<form action="{% url 'single_picture' Pic.Good %}" method="post">
{% csrf_token %}
{% if Pic.Good %}
<input type="checkbox" name="choice" id="{{ Pic.Good }}" value="False" />
<label for="{{ Pic.Good }}">False</label><br />
{% else %}
<input type="checkbox" name="choice" id="{{ Pic.Good }}" value="True" />
<label for="{{ Pic.Good }}">True</label><br />
{% endif %}
<input type="submit" value="good" />
</form>
And for my view I have:
def single_picture(request, Pic_id):
if request.method == 'GET':
pic = get_object_or_404(Pic, pk=Pic_id)
latest_pictures_list = Pic.objects.all()
return render(request, 'pictures/single_picture.html', {'Pic': pic, 'latest_pictures_list': latest_pictures_list})
elif request.method == 'POST':
pic = get_object_or_404(Pic, pk=Pic_id)
latest_pictures_list = Pic.objects.all()
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Pic.DoesNotExist):
return render(request, 'pictures/single_picture.html', {'Pic': pic, 'error_message': 'uhhhh...',
})
else:
selected_choice.save()
return HttpResponseRedirect(reverse('pictures/single_picture.html', {'Pic': pic}))
I'm not sure if there are multiple errors at this point or not. Currently when trying to view the template, I get
Reverse for 'single_picture' with arguments '(True,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
for the '< form >' line. I'm guessing it's to do with my View?
I think the issue is in your template, in the line
<form action="{% url 'single_picture' Pic.Good %}" method="post">
Your regex in urls.py is r'^(?P<Pic_id>\d+)/$', I'm guessing that it's expecting the id of the Picobject you return in the GET request and not a boolean, in which case the line should be
<form action="{% url 'single_picture' Pic.id %}" method="post">
Likewise, in the lines underneath, there isid="{{ Pic.Good }}" which will display as HTML as id=True or id=False, which I suppose you don't want. You need to replace that bit by id="{{Pic.id}}"