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

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.

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/

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

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"].

render a individual field in a form-inline using 'as_crispy_field'

I need to render individual fields from my Form so I use the filter |as_crispy_field from crispy-forms and use bootstrap 3 for the style but I need to do it in a form-inline like the first example here bootstrap example page so I tried to do it like this:
template.html
<form class="form-inline">{% csrf_token %}
{{ form.name|as_crispy_field }}
</form>
But the label shows above the TextInput field and not in-line as I need. How can I do this using |as_crispy_field?
EDIT: Here is the HTML after the render with crispy
<form class="form-inline"><input type='hidden' name='csrfmiddlewaretoken' value='****...' />
<div id="div_id_name" class="form-group">
<label for="id_name" class="control-label requiredField">
Name<span class="asteriskField">*</span>
</label>
<div class="controls ">
<input class="form-control textinput textInput form-control" id="id_name" maxlength="100" name="name" type="text" />
</div>
</div>
</form>
The one you linked to, with the labels on the left of the fields, is called "form-horizontal" in Crispy. It is explained here. You need to set these helper properties
helper.form_class = 'form-horizontal'
helper.label_class = 'col-lg-2'
helper.field_class = 'col-lg-8'
Actual inline forms, with the label displayed inside the fields are right below on the same page. You only need to set two helper properties
helper.form_class = 'form-inline'
helper.field_template = 'bootstrap3/layout/inline_field.html'
That should do it, if I understood your question correctly.

BooleanField checkbox not render correctly with crispy_forms using bootstrap

I am using crispy_forms and FormHelper. I have a model field declared as:
active = models.BooleanField(default=True)
And in my ModelForm, I have tried both the following in my Layout:
self.helper.layout = Layout(
...
InlineCheckboxes('active'),
Field('active'),
...
which both not providing the desired result:
Please see image link
While using InlineCheckboxes, I do not see the checkbox and using only Field, it's not formatted correctly.
Please help
Here is the link to the "Bootstrap Layout objects" section of Crispy Forms docs.
InlineCheckboxes: It renders a Django forms.MultipleChoiceField field using inline checkboxes
InlineCheckboxes isn't appropriate for your model's field-type.
A hacky way to achieve what you're looking for is to use PrependedText with an empty string for the text argument.
...
PrependedText('active', ''),
...
Examining the source it appears that a boolean field by default renders the <input> tag inside the <label> tag. Using the hack above, 'Active' stays in the <label> and the <input> is put where you'd expect: in a <div> with "control" css class. Compare the following:
PrependedText('active', ''):
<div id="div_id_active" class="form-group">
<label for="id_active" class="control-label">Active</label>
<div class="controls">
<div class="input-group">
<input type="checkbox" name="active" class="checkboxinput" id="id_active" />
</div>
</div>
</div>
Field('active'):
<div class="form-group">
<div id="div_id_active" class="checkbox">
<div class="controls">
<label for="id_active" class=""><input type="checkbox" name="active" class=
"checkboxinput checkbox" id="id_active" /> Active</label>
</div>
</div>
</div>
Update
I've confirmed that this is fixed in the dev branch of django-crispy-forms.
Reference this commit: 5c3a268
And this github issue: #267

How can I access data sent in a post request in Django?

I have a form that is supposed to create a new 'Quote' record in Django. A 'Quote' requires a BookID for a foreign key.
This is my form
<form method="POST" action="{% url 'quotes:createQuote' %}">
{% csrf_token %}
<section>
<label for="q_text">Quote Text</label>
<input type="text" name="text" id="q_text" placeholder="Enter a Quote" style="padding-left:3px"> <br>
<label for="q_book">Book ID</label>
<input type="text" name="bookID" id="q_book" placeholder="Enter Book ID" style="padding-left:3px"> <br>
<label for="q_disp">Display Quote Now?</label>
<input type="radio" name="display" id="q_disp" value="True"> True
<input type="radio" name="display" value ="False">False <br>
<button value="submit">Submit</button>
</section>
</form>
And this is the method that it is targeting
def createQuote(request):
#b = get_object_or_404(Book, pk=request.bookID)
return HttpResponseRedirect(reverse('quotes:index'))
Somewhere in that request argument I assume there is some sort of field that contains the bookID the user will pass in on the form. How do I get at that information?
Bonus points for anyone who can tell me some way I can visualise data like I might with console.log(some.collection) in Javascript
if request.method == "POST":
book_id = request.POST['book_id']
Assuming you're sure it's in there. Otherwise you'll need to verify/provide a default value like you would for a normal python dictionary.
As for visualising the data, do you mean printing it to the console? In which case if you're running the django runserver you can just do print some_data. If you want it formatted a little nicer, you can use pretty print:
import pprint
pp = pprint.PrettyPrinter()
pp.pprint(some_data)