How can I get custom form field value from within Django Admin's response_change? - django

I've added a custom functionality to a model by overriding change_form.html. Basically, I'm letting users change the objects of a model if these changes were approved by the admin. I added two buttons, named accept-suggestion and decline-suggestion and I intend to handle the custom functionality through response_change method:
def response_change(self, request, obj):
if "decline-suggestion" in request.POST:
# do stuff...
if "accept-suggestion" in request.POST:
# do stuff...
Both buttons will send an e-mail to the user saying if the suggestion was declined or approaved. So far so good. The problem is that I want to add the possibility to the admin write a brief justification explaining why the suggestion was declined. So I changed change_form.html again.
<div class="submit-row">
<div class="float-left">
<a class="decline-button-outlined accordion" type="button" href="#">DECLINE SUGGESTION</a>
</div>
<div class="float-right">
<input class="accept-button" type="submit" name="accept-suggestion" value="ACEITAR SUGESTÃO">
</div>
</div>
<div class="additional-infos">
<fieldset class="module aligned">
<div class="form-row">
<label for="decline-reasons">Reasons for rejection:</label>
<textarea
placeholder="If you find necessary, provide information on the reasons that led to the rejection of the suggestion"
id="decline-reasons" class="vLargeTextField" rows="5"></textarea>
</div>
<div class="submit-row">
<div class="float-right">
<input class="decline-button" type="submit" name="decline-suggestion" value="DECLINE">
</div>
</div>
</fieldset>
</div>
Is this the best approach? If so, how can I get the value of the <textarea> above from within response_change? If not, what would you suggest?
Thank you very much!

If you add a name to your <textarea> you will be able to retrieve the contents on the server side. Without a name, the data is not being sent to the server (Django).
So something like this:
<textarea
placeholder="If you find necessary, provide information on the reasons that led to the rejection of the suggestion"
id="decline-reasons" name="decline-reasons" class="vLargeTextField" rows="5"></textarea>
Should allow you to retrieve the text on the Django side with request.POST["decline-reasons"].

Related

How do I make my livewire store method send data using POST, seems it is using a GET method

public function storeProject()
{
$this->validate();
$fileName = $this->files->store('uploads');
Project::create([
'title' => $this->title,
'description' => $this->description,
'files' => $fileName,
'skills' => $this->skills,
]);
session()->flash('message', 'Your Project has been posted Successfully!');
}
My View
#section('title', 'Post a job')
<div>
<div class="py-12 font-sans">
<div class="max-w-5xl mx-auto sm:px-6 lg:px-8">
<div class="m-4 p-4 bg-gradient-to-r from-blue-800 via-blue-700 to-blue-600 text-white rounded-md">
<h2 class="text-4xl">Tell us what you need done!</h2>
<p class="break-words mt-5">Within minutes, get in touch with knowledgeable independent contractors. View
their profiles, give them feedback, look at their portfolios, and talk with them. Only pay the
freelancer once you are completely satisfied with their job.
</p>
</div>
<div>
{{-- Form is located here --}}
<form enctype="multipart/form-data">
<div class="mb-6">
<label for="title">Choose a Title for your Project</label>
<input type="title" id="title" name="title" wire:model.lazy="title"
placeholder="e.g. Build me a website">
</div>
<div class="mb-6">
<label for="message">Tells more about your project</label>
<textarea id="description" name="description" rows="4" wire:model.lazy="description"
placeholder="Describe your project here..." maxlength="4000"></textarea>
</div>
<div class="mb-6">
<label for="user_avatar">Upload file</label>
<input wire:model="files" aria-describedby="user_avatar_help" id="user_avatar" name="files"
type="file">
</div>
<div class="mb-6">
<label for="skills">
What skills are required</label>
<p class="break-words mt-2">Enter up to 5 skills that best describe your project. Freelancers
will use these skills to find projects they are most interested and experienced in.</p>
<input type="text" id="skills" name="skills" data-role="tags-input"
wire:model.lazy="skills" placeholder="Enter skills here separated by commas...">
</div>
<button type="submit" wire:click="storeProject">
Submit
</button>
</form>
</div>
</div>
</div>
</div>
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. This is my blade code.
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
After clicking on submit, this is my url http://127.0.0.1:8000/post-project?title=Iphone+XR+Mini+Updated&description=I+need+it&files=Gilles+Ashley%27s+CV.pdf&skills=Mysql%2C+C%2B%2B+etc. What is wrong with my codes please? Any help?
You need to change the form tag and the submit button:
<form wire:submit.prevent="storeProject">
<button type="submit">
Submit
</button>
This will take care of the page refresh and the GET call. You do not need enctype="multipart/form-data" when using Livewire.
I think that you have created a controller function storeProject() and a blade view with your <form enctype="multipart/form-data"> which is completely wrong. Check here how livewire should work https://laracasts.com/

django python form to submit, delete row from database and refresh page

I am newbie in Django and I would appreciate if someone can help me about this problem.
I have a database in backend with 100 rows of users information.
Name, surname, phone number.
The database is visible on Home page template and if you choose one of this names you can donate something to this person.
When you click on submit button will lead you to new ajax window where you input your data and then submit.
Then I got your message on email.
My questions is how to do at the same time to confirm (submit) and delete row from database (person from database) and then to refresh page ?
Meaning, when you submit form then function should delete person from Home page at once and have to refresh page so you can see another person ?
Here is the code.
I would appreciate any help.
Thanks to all.
views.py
def about(request):
context = {
'num_toys': '1',
}
return render(request, 'about.html') # , context=context
def couses(request):
db_queryset = Children.objects.all()
context = {'child': db_queryset}
return render(request, 'couses.html', context=context)
class ChildrenListView(ListView):
model = Children
context_object_name = 'child'
class ChildrenCreateView(CreateView):
model = Children
form_class = ChildrenForm
success_url = reverse_lazy('children_changelist')
class ChildrenUpdateView(UpdateView):
model = Children
form_class = ChildrenForm
success_url = reverse_lazy('children_changelist')
class ChildrenDetailView(DetailView):
model = Children
form_class = ChildrenForm
success_url = reverse_lazy('children_detail')
children_detail.html
<!-- Start contact form area -->
<div class="couses">
<section class="contact-form-area pb-60 pt-90">
<div class="couses">
<div class="container">
<div class="row">
<!-- Start section title -->
<div class="col-sm-12">
<div class="section-title text-center">
<h2>Donate <span> {{ children.toy }} </span> to <span>{{ children.name }}</span> who is <span>{{children.date }} old</span></h2>
<img src="static/children/img/title-bottom.png" alt="">
</div>
</div>
<!-- End section title -->
<div class="col-sm-12">
<div class="contact-form">
<form id="contact-form" method="POST" action="mail.php">
<div class="form-fields">
<label for="name">Name</label>
<input id="name" name="name" type="text" placeholder="Your Name" required>
</div>
<div class="form-fields">
<label for="email">Email</label>
<input id="email" name="email" type="text" placeholder="Your Email" required>
</div>
<div class="form-fields last">
<label for="phone">Phone</label>
<input id="phone" name="phone" type="text" placeholder="Your Phone" required>
</div>
<div class="message-fields">
<label for="mess">Message</label>
<textarea name="mess" id="mess" cols="30" rows="10" placeholder="Message"></textarea>
</div>
<div class="form-button">
<button type="submit">Send your message</button>
<button type="reset">Reset</button>
</div>
</form>
<p class="form-messege"></p>
</div>
</div>
</div>
</div>
</div>
</section>
sorry if I'm wrong but I understand that you want to do two actions.
In your code I can see that you have forms and class-based Views. Maybe you need to override the function form_valid to do the operations you need when you submit.
Check this website http://ccbv.co.uk there you will find the details of the views.
On click of submit hit the url & process your message on email part first and then you can delete the person from database by filtering out object of that particular person with whatever primary key you have for that table by writing a query in your view. and then render the remaining data of that table to your template on which you are Redirecting from your on submit click.
From above conversation what i understood that you don't want delete that person from database boolean field would be great option rather you want to save the message that has been sent from email by this way you can do both at the same time. you have the message saved in your database and from empty message data can render those user on template.

Django: how to retrieve a form search parameters in a django generic listView

how to retrieve a form search parameters in a django generic listView. My url is:
url(r'postsearch$', views.PostsList.as_view(), name='postsearch'),
My generic listview is:
class PostsList(generic.ListView):
model = Post
template_name = 'posts/post_list.html'
def get_queryset(self):
localisation = #how to get location
discipline = #how to get discipline
return Post.objects.filter(.......)
and my form is:
<form class="form-inline text-center" action="{% url 'posts:postsearch' %}" id="form-searchLessons" method="get">
<div class="form-group">
<input type="text" class="form-control" id="typeCours" list="matieres" placeholder="Matieres: e.g. Math, Physique,.." name="discipline">
<datalist id="matieres">
<option value="value1">
<option value="value2">
</datalist>
</div>
<div class="form-group">
<input type="text" class="form-control" id="Localisation" placeholder="Lieu: Bousaada, Douaouda,.."
name="localisation" onFocus="geolocate()">
</div>
<button type="submit" class="btn btn-default" id="btn-getLessons">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span> Trouver !
</button>
</form>
I want to get the Posts by applying a filter according to the lacalisation and matieres introduced in the search fields (in the form)
You can add the search terms to your url regular expression.
url(r'postsearch/(?P<localisation>\w+)/(?P<descipline>\w+)/$', views.PostsList.as_view(), name='postsearch'),
(Note, mind the trailing slash)
In your get_queryset method you can use those given url parameters
def get_queryset(self):
localisation = self.kwargs['localisation'] or None
discipline = self.kwargs['discipline'] or None
filters = {}
if localisation:
filters.update(localisation: localisation)
if discipline:
filters.update(discipline: discipline)
return Post.objects.filter(**filters)
Eventually you should relocate getting the parameters outside your get_queryset, but that is up to you.
I'm not sure about the security risks doing it this way. Anyone having more information about the security risks during this operation, please share.
I build a library that can help you to solve this problem, you just have to put in the searchable_fields the attributes you want to filter and it will take care of the rest.
https://github.com/SchroterQuentin/django-search-listview

Adding extra HTML tags and attributes to Django crispy-forms fields

I'm using django-crispy-forms with Bootstrap and I'm wanting to add some extra HTML inside the HTML rendered for the a single field.
For example if my form contains,
recipients = forms.CharField(label='To',widget=forms.TextInput(
attrs={'placeholder': 'Enter phone number, contact or group (add as many as you like)'}))
Then the normal rendering (using the Bootstrap templates) is,
<div id="div_id_recipients" class="control-group">
<label for="id_recipients" class="control-label requiredField">
To<span class="asteriskField">*</span>
</label>
<div class="controls">
<input class="textinput textInput" id="id_recipients" name="recipients" placeholder="Enter phone number, contact or group (add as many as you like)" type="text">
</div>
</div>
What I want to do is have some extra HTML appear just before the final closing div. So it would look like,
<div id="div_id_recipients" class="control-group">
<label for="id_recipients" class="control-label requiredField">
To<span class="asteriskField">*</span>
</label>
<div class="controls">
<input class="textinput textInput" id="id_recipients" name="recipients" placeholder="Enter phone number, contact or group (add as many as you like)" type="text">
</div>
<div class="controls-aside">
<button type="button" class="btn">Address Book</button>
<button type="button" class="btn">Add Contact</button>
</div>
</div>
I know that I can replace the existing template for this field with a custom template but I want to be able to re-use their template without doing a copy/paste since that makes it not very maintainable.
So what is the best way to implement this? I also want to add an extra class to the label if anyone can suggest how to do it?
For completeness, but not for your case: even after layout creation, Layout.wrap('recipients', Div) will work if one only needs to wrap a control into an additional Div.
About adding HTML inside the layout. Last hour I needed a very custom HTML, so did this:
(formatting)
i = self.helper.layout.fields.index('guest_email')
self.helper.layout.insert(
i+1,
HTML('{}'.format(
reverse_lazy('invite_guests'),
_('Invite to a party'))
))
I came here googling for a HTMLWrapper class example for Crispy Forms, so that I could do a prettier thing instead:
self.helper['guest_email'].wrap(HTMLWrapper(
'guest_email',
before='',
after='{}'.format(href, title))
If I end up creating one, I'll get back and post it.
For me it worked that way:
from crispy_forms.layout import Field, HTML
self.helper["some_field_name"].wrap(Field, HTML("<p>Example</p>"))
The benefit of using HTML is that it also gives you the possibility to use context variables.

Django Upload From Template

I am looking into uploading a file from the html template. I've seen a fair amount of documentation including FileFields, ImageFields etc. However, ideally I do not want to rewrite my code.
Currently, I have a simple form on my template and I would like to have an upload function there, where, an image will be uploaded and stored into my applications media folder and if possible added to a database.
I do know that I've probably taken a long and complex route but if anyone can help it'll be great!
html.py:
<div class="row"> <div class="span1 offset5"> </bR>
<form class="form-horizontal" method="get" action="/add/submit" value="add">
<fieldset> <div class="input">
<div class="inline-inputs">
<label>Ride Name:</label><input type="text" name="name">
<label>Type:</label><input type="text" name="type">
<label>Theme:</label><input type="text" name="theme">
<label>Description:</label><textarea rows="5" name ="description"></textarea>
<label>Author:</label><input type="text" name="author">
<label>Date Released:</label>
<div id="datetimepicker" class="input-append date">
<input type="text" name="date"></input>
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
</span>
</div>
<label>Thread:</label><input type="text" name="thread">
<label>Video</label><textarea rows="2" name ="video"></textarea>
<br><br>
<input class="btn btn-primary" type="submit" value="Add" />
</div> </div>
</fieldset>
</form>
</div> </div>
Currently my Views.py just takes the entered data and inserts it into a database. I want to add the ability for a file to be uploaded:
def Ride_Add_Submit(request):
name = request.GET['name']
type = request.GET['type']
theme = request.GET['theme']
description = request.GET['description']
author = request.GET['author']
releasedate=request.GET['date']
video=request.GET['video']
thread=request.GET['thread']
entry = RollerCoaster(name=name, type=type, theme=theme, description=description, releasedate=releasedate, author=author, video=video, thread=thread)
entry.save()
return TemplateResponse(request, 'Ride_Add.html')
I don't understand why you keep talking about the template here, the template has nothing whatsoever to do with anything. The handling of the upload, like all logic, is done in the view.
The file upload overview still has all the information you need. You can ignore the parts about the Django form and checking if it's valid, and simply pass the file object to your upload handling function, which that page also explains.
However you will need to change your template so that the form element uses POST instead of GET (which is almost certainly a good idea anyway), and use enctype="multipart/form-data" as also described on that page.
Finally, I really would advise you to rewrite your code to use ModelForms. Not only would it make your code much simpler, it would also do things like validate the entry to make sure all the required fields are present and are of the right types, and so on - as well as output valid HTML (for instance, you're missing for attributes in your label tags).