urlpatterns=[
path('login/',views.LoginUser,name='login'),
path('logout/',views.LogoutUser,name='logout'),
path('register/',views.RegisterUser,name='register'),
path('delete/<str:pk>',views.DeleteUser,name='delete'),
path('',views.home,name='home'),
#path('usersSettings/',views.UserSettings,name='userSettings'),
path('users/<str:pk>/',views.users,name='users'),
path('parameters/',views.parameters,name='parameters'),
path('EbotManual/',views.EbotManual,name='EbotManual'),
path('LedManual/',views.LedManual,name='LedManual'),
path('TestRutins/',views.TestRutins,name='TestRutins')
]
I am designing a website based on django. I want to update the user information and delete the user if wanted in the same page. I created updating and it works properly. But when I address the delete user function to same html file , the button that I want it to delete user also updates just like the other button. I need both buttons to work for their own purposes. I thought that without changing anything assigning delete function to button might help thats why I wrote the title like that. Thank you!
<div class="login--wrapper">
<form method="POST" class="form">
{% csrf_token %}
<div class="center">
<h1>Kullanıcı Ayarları</h1>
{% csrf_token %}
{% for field in form %}
<div class="mb-3">
<label for="exampleInputPassword1" class="from-label">{{field.label}}</label>
{{field}}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Update Info</button>
<button type="submit" class="btn btn-primary">Delete User </button>
</div>
def DeleteUser(request,pk):
user=DataEbotUser.objects.get(id=pk)
if request.method=='POST':
user.delete()
context={'user':user}
return render(request,'home/UsersPage.html',context)
def users(request,pk):
user=DataEbotUser.objects.get(id=pk)
form=EditUserForm(instance=user)
if request.method=='POST':
form=EditUserForm(request.POST, instance=user)
if form.is_valid():
form.save()
context={'form':form , 'users':users}
return render(request,'home/UsersPage.html',context)
url patterns:
urlpatterns=[
path('login/',views.LoginUser,name='login'),
path('logout/',views.LogoutUser,name='logout'),
path('register/',views.RegisterUser,name='register'),
path('delete/<str:pk>',views.DeleteUser,name='delete'),
path('',views.home,name='home'),
#path('usersSettings/',views.UserSettings,name='userSettings'),
path('users/<str:pk>/',views.users,name='users'),
path('parameters/',views.parameters,name='parameters'),
path('EbotManual/',views.EbotManual,name='EbotManual'),
path('LedManual/',views.LedManual,name='LedManual'),
path('TestRutins/',views.TestRutins,name='TestRutins')
]
The problem is that your two buttons submit the form to the same page that rendered the form. There is no way to tell them apart.
If you want each button to perform a different action, one way to do this would be:
<button type="submit" class="btn btn-primary">Update Info</button>
<a class="btn btn-danger" type="button" href="{% url 'delete' user.pk %}">Delete User</a>
Since the function users is the only one to manage the update of the user's information based on the form data, the button Update Info remains in the form of submit button.
The Delete User button on the other hand is different. It simply calls the function DeleteUser passing it a pk which will be used to delete a user.
Here are some things to consider:
The function DeleteUser must not be called directly. It is the function users which must render the page.
You have to render the user object in the context of your function users, to be able to retrieve the pk of the user who will be used for the button delete
Function DeleteUser must not render the template but redirect to another url like home. Something like return redirect('home')
Hi i am using django + bootstrap4 to render forms. I have 'submit' and 'cancel' buttons on the forms. i am using ModelForm with Validators assigned to most of the form attributes.
template file
<form action="{% url 'actor-create' %}" method="post" class="w-25 mx-auto">
{% csrf_token %}
{% bootstrap_form form layout="horizontal" %}
<button class="btn btn-primary" type="submit"><i class="fas fa-plus"></i> Save</button>
<button class="btn btn-primary" type="submit"><i class="fas fa-times"></i> Cancel</button>
</form>
in the view
def actor_create(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
print(request.POST)
if "cancel" in request.POST:
return HttpResponseRedirect('/')
..... rest of the code
When cancel button is pressed validation of the form attributes prevents the form from submitting. so view functionality never gets executed.
I want to know how to avoid validation when form is cancelled?
Following Q&A has a JavaScript based solution, I preferably don't want to write such code for every form in my website.
How to cancel form submission?
as suggested by Iain Shelvington making it a 'a' worked for me!
<i class="fas fa-times"></i> Cancel
I have the following two models:
class TaskFile(models.Model):
file = models.FileField(upload_to='task-files/')
def __str__(self):
return self.file.name
class Task(models.Model):
lesson = models.ManyToManyField(TaskFile, related_name='task_files')
I have a model form to update the Task object that is already created, but the many to many relationships do not show up in the form. It just shows the option to upload a file and does not show the existing files in that object.
How can I fix this?
Edit:
This is my model form code:
class TutorTaskSelectForm(forms.ModelForm):
lesson = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = Task
fields = ('lesson')
This is my template:
<form action="{{request.path}}" method="POST" enctype="multipart/form-data">
{%csrf_token%}
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Number</label>
<div class="col-sm-10">
{{form.lesson}}
</div>
</div>
</div>
</form>
First, i am not a huge fan of built-in Django Forms. So i am going to suggest you a different way. A way without Django Forms.
Out of context of this question:
There are great, i mean really great, front-end libraries like
React, Vue or Angular. And they are getting more popular every
day, or even every minute. When you decide to choose one of those
fancy libraries, using Django forms doesn't make sense so much.
Anyway, If you want to keep your existing model structure, I think the best thing you can do here is updating the logic inside of your view:
def index(request):
if request.method == 'POST':
print(request.FILES.getlist)
files = request.FILES.getlist('lesson')
# #TODO: check if form is valid or files are proper etc. here
task = Task() # new task instance here
task.save()
for f in files:
task_file = TaskFile()
task_file.file = f
task_file.save() # save uploaded file to the TaskFile
task.lesson.add(task_file) # here add that file to the many to many field of Task Model
return HttpResponse('All files saved!')
else:
ctx = {
'form': TutorTaskSelectForm()
}
return render(request, 'index.html', ctx)
I tested above code. It is working. But you must clarify what you mean by saying uploading multiple files.
Do you want to select multiple files at once? Or do you want different and separate file dialog boxes for each file?
If you want to have multiple selection while picking files from browser dialog box, then above solution should work for you.
But If you want to have multiple files by picking them separately, then you need multiple inputs in your html side. Something like this:
<form action="{{ request.path }}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="lesson" required />
<input type="file" name="lesson" required />
<input type="file" name="lesson" required />
<input type="submit" value="Save"/>
</form>
Note that you don't need Django forms in this case. Just create regular input files then handle them in you view. You can reach files inside a request by calling request.FILES.getlist('lesson').
But again, i wouldn't use django forms for this case. Here is the version of not using django forms:
<form action="{{request.path}}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Number</label>
<div class="col-sm-10">
<input type="file" name="lesson" required multiple />
</div>
</div>
</div>
<input type="submit" value="Save" />
</form>
Put those lines in your html, and use the code above. This is very basic and simple. You can update it according to your requirements.
I have a page that pulls out entries from the database as 'users' and lists them. A typical result looks like this:
John
Marty
Tom
Jane
Chris
Now I would like to click on a specific the name and go to their specific page. For this, I have a form that posts to a view that expects the user that has been "clicked"
So far, I have a form inside a loop that goes through each 'user' in 'users' table. The setup works fine but the major problem is that the form element 'name' is replaced by the last user. No matter, whose name I click it always passes the last user's username.
{% for user in users %}
<h1>{{ user.firstName }} {{ user.lastName }}</h1>
<form action="/friend_profile/" method="post" accept-charset="utf-8">
<input type="hidden" name="selectedFriend" value ={{ user.userName }}>
<button type="submit" value="view profile">
{% endfor %}
I am not using DJango forms and just using request.method == 'POST' for receiving variables.
So my dumb question would be, is there a way to dynamically create 'name' form element and submit its contents specific to the user? Right now, the form always submits the user "Chris" no matter which user I click because its the last one on the list.
Right now, the form always submits the user "Chris" no matter which user I click because its the last one on the list.
That's because you didn't close your <form> tag, so the browser sees one big bunch of nested forms.
Also, you need to quote and escape the value attribute in your hidden input:
<form action="/friend_profile/" method="post" accept-charset="utf-8">
<input type="hidden" name="selectedFriend" value="{{ user.userName|escape }}">
<button type="submit" value="view profile">
</form>
I need to send both a file and some data from input texts.
This is the form I'm working on:
<form method="post" action="{% url catalog_create_ajax_upload %}" enctype="multipart/form-data" id="create-form">
<input type="text" id="new-catalog-name" name="catalog_name" class="large-input" placeholder="catalog title" />
<div id="new-catalog">
<input type="file" name="file">
</div>
</form>
When sent, I excpect request.POST['catalog_name']to have a value, but the whole POST attribute in an empty dictionary.
Any help?
You don't seem to have a submit button in that form. Presumably you've got one elsewhere on the page, but it would only submit the fields in its own form - move it inside that <form>...</form>.
Make sure your view function should post image file like this
def index(request):
image = 'file' in request.FILES and request.FILES['file']
Use request.FILES instead of request.POST