form.html
{% for fields in form %}
<div class="control-group">
<label class="control-label" for="{{ field.id_for_label }}">
{{fields.label}}</label>
<div class="controls">
{{fields}}
{% if fields.label == 'Photo' %}
<br>
<p></p>
<button type="button" class="btn btn-primary success"
id="add_new_file">+ Add Another File</button>
{% endif %}
</div>
</div>
<script>
$("#add_new_file").click(function(){
$("p").append('<input type="file"><br>');
});
</script>
For every click in + Add Another File button, another input file option added. Here i use model form to insert into the database.The first one is adder into the db, but how can i add multiple photo or other types files at the same time.
views.py
if request.method == 'POST':
form_values = Registration_Form(request.POST, request.FILES)
multiple_files = request.POST
print(multiple_files)
for file in multiple_files:
print(file)
if form_values.is_valid():
data = form_values.save(commit=False)
password = data.password.encode('utf-8')
password = hashlib.sha256(password).hexdigest()
data.password = password
activation_code = str(random.randrange(0, 999999))
data.activation_code = activation_code
data.save()
Assuming that you need to save the files blindly to storage ( project directory) and there are no model relationships.
def my_view(request):
if request.method == 'POST':
for data in request.FILES.values():
with open(data.name, 'wb') as file:
file.write(data.read())
# do other stuff
This will write/create new files to your project directory from `request.FILES
Related
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>
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>
I am looking for some assistance in two areas for django forms processing.
I have a class view that overrides post and checks the name of the form in request.POST to determine which form has been submitted. based on the form submitted, I perform the appropriate actions for that form and save to the model. That part works correctly. I am not using a model form, just a custom html form created in the template with input fields. See the below view and html for reference. Is this the correct way to handle this or is there a best practice I should be following that makes use of model forms? Code seems a bit heavy to me and non-standardized, like there should be a better way...
Being that I am not using model forms, the error processing has me a little confused. How do you handle error processing on a normal html form that does not make use of django model forms? See below in the view where notated # ERROR HANDLING FOR FORM NEEDED in code, specifically on the username field which is unique and validated on the model level.
views.py
class ProfileView(View):
def get(self, request, *args, **kwargs):
if request.method == "GET":
# load profile data...
def post(self, request, *args, **kwargs):
if request.method == "POST":
# check if profile_form submitted
if 'profile_form' in request.POST:
# get user form data
profile_data = request.POST.dict()
# get current user profile
user_profile = Profile.objects.get(my_user=request.user)
# check username entry against current
if user_profile.username == profile_data['username']:
user_profile.country = profile_data['country']
user_profile.display_location = profile_data['display_location']
user_profile.organization_name = profile_data['organization']
user_profile.save(update_fields=['country', 'display_location','organization_name'])
#send success message to page
messages.success(request, "Success: Profile was updated.")
else:
try:
user_profile.username = profile_data['username']
user_profile.country = profile_data['country']
user_profile.display_location = profile_data['display_location']
user_profile.organization_name = profile_data['organization']
user_profile.save(update_fields=['username', 'country', 'display_location','organization_name'])
#send success message to page
messages.success(request, "Success: Profile was updated.")
except:
# unique constraint error on username
# ERROR HANDLING FOR FORM NEEDED
# check if user_name_form submitted
if 'user_name_form' in request.POST:
# get user form data
user_data = request.POST.dict()
# get current user
user = MyUser.objects.get(email=request.user)
user.first_name = user_data['first_name']
user.last_name = user_data['last_name']
user.save(update_fields=['first_name', 'last_name'])
# send success message to page
messages.success(request, "Success: Name was updated.")
# Return Profile page view with updated data
return HttpResponseRedirect(reverse('profile'))
html
<!--form-->
<form id="profile" class="small" method="POST" action="{% url 'profile' %}">
{% csrf_token %}
<!--Username-->
<label for="username">Username <span style="font-style: italic;">(create a unique display name that will appear to other users on the site)</span></label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="username">#</span>
</div>
<input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="username" name="username" value="{% if profile and profile.username is not None %}{{ profile.username }}{% endif %}">
</div>
<hr>
<p>Tell us where you are from!</p>
<!--Country State/Province City Select-->
<div class="form-group">
<select name="country" class="form-control mb-3" id="country">
<option value="">Select Country...</option>
{% for country in countries %}
{% if profile.country == country.name %}
<option value="{{ country.name }}" id="{{ country.code }}" selected>{{ country.name }}</option>
{% else %}
<option value="{{ country.name }}" id="{{ country.code }}">{{ country.name }}</option>
{% endif %}
{% endfor %}
</select>
</div>
<hr>
<p>Enter your profile display location <i>(ie. City, State, Province, Region...)</i></p>
<input type="text" class="form-control" id="display_location" name="display_location" placeholder="Based in..." value="{% if profile and profile.display_location is not None %}{{ profile.display_location }}{% endif %}">
<hr>
<p>Do you belong to an organization?</p>
<input type="text" class="form-control" id="organization" name="organization" placeholder="Organization Name" value="{% if profile and profile.organization_name is not None %}{{ profile.organization_name }}{% endif %}">
<hr>
<button type="submit" class="btn btn-primary" name="profile_form" value="profile_form">Save</button>
</form>
This can be tricky to do, so at DjangoCon a few years ago, we built a Django app to help. Have a look:
https://github.com/kennethlove/django-shapeshifter
As a solution to this problem I was able to get to, see the post here for a way to do this without a 3rd party app.
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',)
I have a problem with my Django Code.I'm trying to render a form from views to template and i'm just seeing the submit button. I noticed that we can use forms dynamically by introducing it like this {{ form }}, but when I use it, I just see the "submit" button on the page(Sorry I don't know how to upload a local image here). I join my four files: views.py, home.html, forms.py and urls.py
Thank you in advance
home.html
<form method="POST" novalidate action="/config">
{% csrf_token %}
<fieldset>
<legend class="border-bottom mb-4">Home</legend>
{{ form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
views.py
def inputHome(request):
form = InputHomeForm()
if request.method == 'POST':
form = InputHomeForm(request.POST)
if form.is_valid():
mk = form.cleaned_data['mk']
return HttpResponseRedirect('blog-config')
else:
form = InputHomeForm()
return render(request, 'blog/home.html', {'form': form})
forms.py
class InputHomeForm(forms.Form):
mk = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
urls.py
urlpatterns = [
path('home/', blog_views.home, name='blog-home'),
]
I don't have an error message so i don't have an idea of the problem.
You are missing form tag in html.
HTML should be,
<form method='post'>
{% csrf_token %}
<fieldset>
<legend class="border-bottom mb-4">Home</legend>
{{ form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
Slightly unrelated (cf Nishant's answer for the main issue), but here:
if request.method == 'POST':
form = InputHomeForm(request.POST)
if form.is_valid():
mk = form.cleaned_data['mk']
return HttpResponseRedirect('blog-config')
else:
form = InputHomeForm()
In the else clause, you're replacing the bound invalid form (which carries the validation errors) with an unbound form, so you'll never get the error messages. Just remove the whole else clause.