Image uploading from Django-template to model is not working - django

I am trying to upload profile image of user from userprofile.html template but it is not uploading to that model on admin panel. I already configured the static and media settings correctly. I am able to upload from admin panel.But uploading from template isn't working please help..
#forms.py
class ImageUploadForm(forms.ModelForm):
class Meta:
model = accountUser
fields = ['profile_photo',]
#views.py
def upload_pic(request):
if request.method == 'POST':
form = ImageUploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('success')
else:
form = ImageUploadForm()
return HttpResponseForbidden('allowed only via POST')
#user.html
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
<p>
<input id="id_image" type="file" class="" name="image">
</p>
<button type="submit">Choose Picture</button>
</form>

Related

Django I need upload file button only remove choose file and don't need refresh page when upload

I want to upload only button and don't need refresh when upload how to fix this
model_form_upload.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" >Upload</button>
</form>
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = DocumentFile
fields = ['document']
views.py
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = DocumentForm()
print(form)
return render(request, 'model_form_upload.html', {'form': form})

Update ImageField without forms in django

I am trying to update an image field in django model from an html form. Update goes fine except for the image field. Originally I successfully uploaded this image within a django form which means the settings are fine.
Please, tell me what's wrong in my code.
That's my views.py file:
'''
def update_product(request, product_id):
if request.method=="POST"
model_name=request.POST['model_name']
image = request.FILES ['image']
Product.objects.filter(id=product_id).update(model_name=model_name, image=image)
return redirect ('listing)
'''
That's my html file:
'''
<form action={% url update_product product.id %} method ="POST enctype='multipart/form-data'>
{% csrf_token %}
<input type='text' name='model_name'>
<input type='file' name='image'>
<button type='submit'> Update </button>
</form>
Update() method doesn’t run save().
Do something like this:
def update_product(request, product_id):
if request.method == "POST":
product = get_object_or_404(Product, id=product_id)
product.model_name = request.POST['model_name']
product.image = request.FILES['image']
product.save()
return redirect('listing')

Django - save multiple input parameters to database

I'm using the below custom form in my Django app:
forms.py
class UpdateURLForm(forms.ModelForm):
VideoURL = forms.URLField()
MainDescription = forms.CharField(max_length=100)
class Meta:
model = Listing
fields = ('VideoURL', 'MainDescription',)
Then, in views.py I import the form and then I render the fields into my HTML template:
def edit_info(request):
if request.method == 'POST':
form = UpdateURLForm(request.POST)
if form.is_valid():
VideoURL = form.cleaned_data['VideoURL']
MainDescription = form.cleaned_data['MainDescription']
else:
form = UpdateURLForm()
return render(request, 'myapp/updateinfo.html', {'form': form})
HTML:
<form action="#" method='post' class="card shadow-soft border p-4 mb-4">{% csrf_token %}
<div class="form-group">
<label for="video">Video URL:</label>
{{form.VideoURL|add_class:"form-control shadow-soft"}}
</div>
<div class="form-group">
<label for="video">Video URL:</label>
{{form.MainDescription|add_class:"form-control shadow-soft"}}
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right"
type="submit">Update</button>
</div>
</div>
</form>
Now, my question is: how can I render the field MainDescription in the template in order to save both information into the database? The way I rendered the second field (MainDescription) doesn't work. Thanks!
Edit
So, I have two fields in my custom form which (VideoURL and MainDescription) which I would like to use to update some info in the DB. When I try to render in the HTML template both are getting the same ID whereas I was expecting that each field of the form to be rendered:
<input type="text" name="VideoURL" value="https://videourl.com" maxlength="100" class="form-control shadow-soft" required="" id="id_VideoURL">
I do not figure out what I am missing.
Every ModelForm has a save() method. This method creates and saves a database object from the data bound to the form. A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it’s not supplied, save() will create a new instance of the specified model:
EXAMPLE 1 with forms.ModelForm
forms.py
class UpdateURLForm(forms.ModelForm):
class Meta:
model = Listing
fields = ['video_url', 'main_description']
So you can ease save your form.
views.py
def edit_info(request):
if request.method == 'POST':
form = UpdateURLForm(request.POST)
if form.is_valid():
instance = form.save()
else:
form = UpdateURLForm()
return render(request, 'myapp/updateinfo.html', {'form': form})
EXAMPLE 2 with forms.Form
forms.py
class UpdateURLForm(forms.Form):
video_url = forms.URLField(label="Video Url")
main_description = forms.CharField(label="Description", max_length=100)
You can also import your model and create an object.
views.py
from models import Listing
def edit_info(request):
if request.method == 'POST':
form = UpdateURLForm(request.POST)
if form.is_valid():
listing = Listing(video_url=form.cleaned_data.get('video_url'), main_description=form.cleaned_data.get('main_description'))
listing.save()
else:
form = UpdateURLForm()
return render(request, 'myapp/updateinfo.html', {'form': form})

Load the csv data using html view into django database

I am trying to load a simple csv file into django model named as class Team
class Team(models.Model):
Team = models.CharField(max_length=255,primary_key=True)
Description = models.CharField(max_length=255)
def __str__(self):
return self.Team
Views.py
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = DocumentForm()
return render(request, 'core/model_form_upload.html', {
'form': form
})
HTML
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<p>Return to home</p>
{% endblock %}
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('description', 'document', )
I have create a simple html page to load the file into the following location MEDIA_ROOT=os.path.join(BASE_DIR,"media")
I am able to load my file into that location but I need some help with passing on the data to the actual database and load the values into the table "Team". Any suggestiond on this?

Django form.is_valid() is always False while uploading images

views.py
I am trying to upload an image but form.is_valid always return false
def upload(request):
if request.method=="POST":
form=uploadform(request.POST,request.FILES)
if form.is_valid():
cd=cleaned_data
form.save(commit=True)
return render(request,"success.html")
else:
form=uploadform()
return render(request,'pico.html',{'form':form})
here is the form
<form action="" method="post">
{{form.as_p}}
{% csrf_token %}
<input type="submit" value="Submit" />
</form>
forms.py
class uploadform(ModelForm):
class Meta:
model=examplemodel
fields=['pic']
models.py
class examplemodel(models.Model):
pic=models.ImageField()
Did you set enctype="multipart/form-data" in the html form tag?