How to prevent upload the file on submit the form - django

I uploading the file in django with progress bar, and when i choose the file the progress start and when the finish that's mean the file uploaded but when I click in submit form the file upload again and this mean the progress bar is useless, so I want to make something like when I click in submit button the file save with the form but not upload again how I can do this?
my form
class Video_form(forms.ModelForm,):
class Meta:
model = Video
fields = ('video', 'video_poster', 'title',)
the view
def VideosUploadView(request, *args, **kwargs):
V_form = Video_form()
video_added = False
if not request.user.is_active:
# any error you want
return render('account/login.html')
try:
account = Account.objects.get(username=request.user.username)
except:
# any error you want
return HttpResponse('User does not exits.')
if 'submit_v_form' in request.POST:
print(request.POST)
V_form = Video_form(request.POST, request.FILES)
if V_form.is_valid():
instance = V_form.save(commit=False)
video = request.FILES['video']
clip = VideoFileClip(video.temporary_file_path())
instance.video_duration = clip.duration
instance.author = account
instance.save()
V_form.save_m2m()
V_form = Video_form()
video_added = True
if instance.save:
return redirect('home')
contex = {
'account': account,
'V_form': V_form,
'video_added': video_added,
}
return render(request, "video/upload_videos.html", contex)
the template
<form id="upload-form" action="." method="post" enctype="multipart/form-data">
{% csrf_token %}
<div id="progress-box" class="d-none">progress</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="formGroupExampleInput2" required value="{{V_form.video}}">
<label class="custom-file-label" for="formGroupExampleInput2">Choose Video...</label>
</div>
<div class="custom-file mt-5 mb-4">
<input type="file" class="custom-file-input" id="file2" required value="{{V_form.video_poster}}">
<label class="custom-file-label" for="formGroupExampleInput2">Choose Poster For Your Video...</label>
</div>
<div class="d-flex justify-content-center my-3 px-3" > <button class="btn-block btnn-color" name="submit_v_form"> Upload</button></div>
</form>

Related

Python/Django - radiobutton with submit button instead of buttons

I have a Django application where I want to have a setting: if the email is sent automatically or manually. What I have works, but not in the style that I want it.
At the moment I have 2 buttons where you can click them and the setting is set to what you want. But what I would want is radio buttons, that are also already checked or unchecked, depending on the setting.
What I have now is:
model.py
class AutoSendMail(models.Model):
auto = models.BooleanField(default=False)
manual = models.BooleanField(default=True)
send_type = (
('manual', 'MANUAL'),
('auto', 'AUTO')
)
type = models.CharField(max_length=6, choices=send_type, default="manual")
forms.py
CHOICES = [('manual', 'MANUAL'),
('auto', 'AUTO')]
class SendMailSetting(ModelForm):
class Meta:
model = AutoSendMail
fields = ['auto', 'manual', 'type']
widgets = {
"manual": forms.RadioSelect(attrs={'class': 'form-control'}),
"auto": forms.RadioSelect(attrs={'class': 'form-control'}),
'type': forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect)
}
views.py
class AutoSendView(generic.TemplateView):
template_name = 'core/mailbox/autoSendMail.html'
context_object_name = 'autosend'
extra_context = {"mailbox_page": "active"}
form_class = SendMailSetting
def post(self, request, *args, **kwargs):
if request.POST.get('manual'):
logger.info("Set to: manual email send")
AutoSendMail.objects.filter(pk=1).update(auto=True,
manual=False,
type="manual")
elif request.POST.get('auto'):
logger.info("Set to auto email send")
AutoSendMail.objects.filter(pk=1).update(auto=True,
manual=False,
type="auto")
return HttpResponseRedirect(self.request.path_info)
autoSendMail.html
<form class="card" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="card-body">
<h3 class="card-title">Update Mail Settings</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="form-label">Send E-mail</label>
<button type="radio" name="manual" value="manual" class="btn btn-primary">Manual</button>
<button type="radio" name="auto" value="auto" class="btn btn-primary">Automated</button>
</div>
</div>
</div>
</div>
</form>
Currently it looks like this:
And I would like it to look more like this:
At the moment I'm only using a POST request, and I guess, to inform the user I also need to use a GET request, but I can't get it to work. Also I'm now not using the form, I tried to use it in different ways but I can't get the result I want..
Can someone help me?
You had created a modelForm but you are not using it here. Anyway for basic method you can try below method
<input type="radio" name="update_type" value="manual">Manual</input>
<input type="radio" name="update_type" value="auto">Automated</input>
<button type="submit" class="btn btn-primary">Submit</button>
views.py
def post(self, request, *args, **kwargs):
update_type = request.POST.get('update_type'):
if update_type == 'manual':
"update db with manual to true"
else:
"update the db with auto to true"

User form foreignkeyfield form not valid

I was creating a post based website i want to show the author's name to show up in the post it works in the admin site when adding posts but when i try uploading a post from the site the form is not getting validated therefore it is not getting saved please help
model :
from django.conf import settings
class MemeImg(models.Model):
Title = models.CharField(max_length=500)
op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
Post_Img = CloudinaryField('Post')
forms :
class PostImg(forms.ModelForm):
class Meta:
model = MemeImg
fields = ['Title', 'op', 'Post_Img']
view :
#login_required(login_url='/login')
def post(request):
func = data(request)
if request.method == 'POST':
form = PostImg(request.POST, request.FILES, instance=request.user)
form.op = request.user
if form.is_valid():
print('success')
posts = form.save(commit=False)
posts.op = request.user
form.save()
return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ')
else:
print("fail")
form = PostImg(request)
ctx = {
'form': form,
'url': func[0],
'name': func[1],
'date': func[2],
}
return render(request, 'Post.html', ctx)
and finally the post page template :
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
{{ form.Title|materializecss }}
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file">
</div>
<div class="file-path-wrapper">
{{ form.Post_Img }}
<input class="file-path validate" type="text">
</div>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
If anymore code is required please comment it
Thanks a lot
I think your problem come from the form instance which is instance=request.user, actually the instance is supposed to be the MemeImg object instance and not the user, that's making it not to save the image. So i have deleted the instance and also i don't know what you are using those extra context variable for 'url': func[0],'name': func[1], 'date': func[2] ?, so i deleted them too keep things simple. Now i think you should be able to save without any Issues.
#login_required(login_url='/login')
def post(request):
if request.method == 'POST':
form = PostImg(request.POST, request.FILES)
if form.is_valid():
print('success')
data = form.save(commit=False)
data.op = request.user
form.save()
return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ')
else:
print("fail")
form = PostImg(request.POST)
ctx = {
'form': form,
}
return render(request, 'Post.html', ctx)
Also your form had in it {{ form.Post_Img }} which i don't no what you are looking to accomplish with that variables?, the right way is doing {{ form.as_p }} or simply just calling the form like this {{ form }} so i have made the correction in you HTML
too.
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
{{ form.Title|materializecss }}
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file">
</div>
<div class="file-path-wrapper">
{{ form }}
<input class="file-path validate" type="text">
</div>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>

Django Image upload not POSTing

I am trying to let a user upload and change their picture.
Currently the form displays the current picture for the user without any issues, but I seem to have messed something when it comes to the upload part since the upload is not working (no error messages).
Also, is it possible to create a custom image form? Currently, this makes use of Djangos default one which is not that style-friendly.
Views.py
#login_required
def edit(request):
if request.method == "POST":
FormImage= UserProfileForm(request.POST, request.FILES, instance=request.user)
if FormImage.is_valid():
FormImage.account_id = request.user.id
FormImage.save()
return HttpResponseRedirect(request.path_info)
else:
imageForm = UserProfileForm(instance=request.user)
return render(request, 'accounts/info.html', {
"FormImage": FormImage,
})
Forms.py
class UserProfileForm(UserChangeForm):
FRUIT_CHOICES = (
('Banana', 'Banana'),
('Orange', 'Orange'),
('Apple', 'Apple'),
)
fruits = forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES))
class Meta:
model = Account
fields = (
'fruits',
'profile_picture',
)
Template
<form method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
<label class="col-lg-3 col-form-label form-coantrol-label">Change picture</label>
<div class="col-lg-9">
{{ FormImage.profile_picture }}
</div>
<div class="form-group row">
<div class="container"><input class="btn btn-primary" type="submit" value="Save profile"></div>
</div>
</form>
My model field for profile pic
profile_picture = models.ImageField(default="default.png", null=True, blank=True)

Django form gets image data but not text

I have Django form that displays information about the property and the idea of this form is to allow users to amend information about their properties. When displaying the form only image data is displayed, everything else is blank. From if request.user.landlord_profile.landlord_id == project.landlord_id: is the code for the form.
views.py
def project_detail(request, pk):
project = Properties.objects.get(pk=pk)
applyButton = Property_Applications.objects.filter(listing=project)
propertyReview = Property_Reviews.objects.filter(property=project)
# getting the urls
property_images = Property_Images.objects.filter(property=project)
context = {
'project': project,
'propertyReview': propertyReview,
'property_images' : property_images,
}
if request.user.is_authenticated:
if request.user.last_name == 'False': # allows to tenant to view ads and apply for them if they meet the requirements
tenant_profile = Tenant_Profile.objects.get(tenant=request.user.tenant_profile.tenant_id)
if request.method == "POST":
applyButton = Property_Applications(
user=request.user,
listing=project,)
applyButton.save()
context['applyButton'] = applyButton
context['tenant_profile']= tenant_profile
if request.user.landlord_profile.landlord_id == project.landlord_id: # if the landlord owns this ad, this let's him edit the ad
change_listing_form = ManageListingForm(request.POST, request.FILES, instance=project)
if request.method == 'POST':
if change_listing_form.is_valid():
change_listing_form.landlord = request.user.landlord_profile
change_listing_form.save()
messages.success(request, f'Your account has been updated!')
else:
change_listing_form = ManageListingForm()
context['change_listing_form'] = change_listing_form
return render(request, 'project_detail.html', context)
forms.py - ManageListingForm
class ManageListingForm(forms.ModelForm):
class Meta:
model = Properties
fields = ['description','rentPrice','tenantSalary','referenceRequired','image']
project_detail.html - this is what displays the form
{% elif request.user.landlord_profile.landlord_id == project.landlord_id%}
<p></p>
<div style="text-align: center">
<button class="open-button" onclick="openForm()">Manage your Spot</button>
</div>
<div class="form-popup" id="myForm">
<form class="form-container text-dark" method="POST" enctype="multipart/form-data">
<label for="Viewing Date " class="text-white">Enter a time that suits you to host a viewing with {{ portal.tenant }}</label>
<fieldset class="form-group col-md-12 bg-white border border-dark" style="margin: auto;padding: 10px">
{% csrf_token %}
{{change_listing_form | crispy}}
<div class="text-center">
<button type="submit" class="btn bg-dark text-white">Update your listing</button>
</div>
</fieldset>
<p></p>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
<!-- Manage Listing function if the user is the owner-->
</div>
{% endif %}
Image of the the form only display image data
test install !!(pillow for images )
pip install pillow
default = just to look images at save it or another problem !
upload_to = destination file to load your images
in Model.py
image = models.ImageField(upload_to='put Your folder her ', default='default.png',)

django images cannot be updated from defaults

I have an image upload function in django. However, images cannot be uploaded. The page is redirected to successURL. I don't understand the cause.
The view is current because it uses multiple forms.
#view
def UserEdit(request):
if request.method == 'POST':
form = forms.UserUpdateForm(request.POST, instance=request.user)
subform = forms.ProfileUpdateForm(request.POST, instance=request.user.profile)
if all([form.is_valid(), subform.is_valid()]):
user = form.save()
profile = subform.save()
return redirect('person:myaccount', username=request.user)
else:
form = forms.UserUpdateForm(instance=request.user)
subform = forms.ProfileUpdateForm(instance=request.user.profile)
return render(request, 'accounts/accounts_edit.html', {
'form': form,
'subform': subform,
})
#form
class UserUpdateForm(forms.ModelForm):
#...
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = profile
fields = ('first_name','last_name','birthday','image',)
#model
class profile(models.Model):
image = models.ImageField(upload_to='profile/',default='profile/default.jpg')
#html
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="text-center col-lg-6 col-md-6 col-sm-10 mx-auto">
<div class="form-group">
{{ form }}
</div>
<div class="form-group">
{{ subform }}
</div>
<button type="submit" class="fadeIn fourth btn btn-light">Submit</button>
</div>
</form>