I am a beginner in Django. I want to send an email on button click. Button is delete button. when press on delete button, i want to send an email to receiver#gmail.com.
As per the below code, email send when the page loaded. And also there was an internal server error. could you please help me to change the as email send on button click.
views.py
class delete_profile(View):
print("nothing")
def post(self, request, *args, **kwargs):
print("nothing")
template = loader.get_template("frontend/subscription-start.html")
email_content = "deletion confirmation"
send_mail(
'No Dowry Marriage - Subscription',
email_content,
'sender#gmail.com',
['reciever#gmail.com'],
html_message=email_content,
fail_silently=False
)
urls.py
path('delete_profile', csrf_exempt(delete_profile.as_view()), name='delete_profile')
user_profile.html
<script>
function delete_profile1() {
var csrftoken = getCookie('csrftoken');
console.log("rhgrjhrj")
$.ajax({
type: 'POST',
url: '{% url "delete_profile" %}',
data: {
csrfmiddlewaretoken: csrftoken
},
success: function () {
toastr.info('Preference Updated Successfully')
}
});
}
</script>
THANKS IN ADVANCE!!!!
first you import JsonResponse and render in your views.py:
from django.http import JsonResponse
from django.shortcuts import render
After change your Class:
class delete_profile(View):
def get(self, request, *args, **kwargs):
# handle the get request
return render(request, 'frontend/subscription-start.html')
def post(self, request, *args, **kwargs):
email_content = "deletion confirmation"
send_mail(
'No Dowry Marriage - Subscription',
email_content,
'sender#gmail.com',
['reciever#gmail.com'],
html_message=email_content,
fail_silently=False
)
return JsonResponse({'some_text': some_text})
# or
# return render(request, 'some_location/some_html_file')
Maybe change your ajax POST request headers:
headers: {
'X-CSRFToken': csrftoken
}
Related
Csrf token missing problem in my flask route i mention my error please review my code and find solution because i am new to flask
My app.py file:
#app.route('/register', methods=['GET', 'POST'])
#csrf.exempt
def register():
if request.method == 'POST':
form = RegisterForm()
if form.validate_on_submit():
name = request.form['name']
email = request.form['email']
gender = request.form['gender']
username = request.form['username']
password = sha256_crypt.encrypt(str(request.form['password']))
user = User(name=name, email=email, gender=gender, username=username, password=password)
db.session.add(user)
db.session.commit()
response = {"succcess":"User registered successfully and now you can login"}
return jsonify(response)
elif not form.validate_on_submit():
response = {"errors":form.errors}
return jsonify(response)
My error in response:
{
"errors": {
"csrf_token": [
"The CSRF token is missing."
]
}
}
How i solve this issue I am new to flask web framework
Csrf token missing problem in my flask route i mention my error please review my code and find solution because i am new to flask
I am making some API calls from an external source but would like to make it dynamic instead of manually putting the reference number in my views in the DRF UI provided.
What I want is that in my DRF UI, I should have a field whereby when I enter a reference number, I should get the response from from the API, I am successfully doing this manually but I want to make it dynamic from the DRF UI.
I would also like to get a better formatted JSON Response in my DRF UI. An image is below to better explain what I meant
Views.py
class Paystack(APIView):
def get(self, request):
url = "https://api.paystack.co/transaction/verify/{{REFERENCE_NO}}"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
response = requests.request("GET", url, headers=headers, data= payload, files=files)
return Response(response)
def post(self, request):
url = "https://api.paystack.co/transaction/verify/{{REFERENCE_NO}}"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
response = requests.request("GET", url, headers=headers, data= payload, files=files)
return Response(response)
urls.py
from django.urls import path, include
from .views import *
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('paystack', Paystack, basename='paystack')
urlpatterns = [
path('paystack/', Paystack.as_view(), name='paystack'),
]
Presently, my DRF UI looks likes this,
If you want to be able to get reference_id in your DRF UI, you must either define a serializer and catch the value from that, or, you can define a URL pattern which asks for a reference ID.
You can do this
In urls.py
urlpatterns = [
path('paystack/<str:reference_id>', Paystack.as_view(), name='paystack'),
]
In your views.py
class Paystack(APIView):
def get(self, request, reference_id):
url = f"https://api.paystack.co/transaction/verify/{reference_id}"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
response = requests.request("GET", url, headers=headers, data= payload, files=files)
return Response(response)
I have those input fields, and I want them to clear out once the user hits Send.
The code below lets the user input data into multiple fields:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
But, after the user hit Send, the fields won't get refreshed. The user will have to remove all the text manually. How can I clear the fields so that the user can continue inputting and submitting data?
views.py:
from django.shortcuts import render
from .forms import ContactForm
def contact(request):
template = "contact.html"
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
else:
form = ContactForm()
context = {
'form': form
}
return render(request, template, context)
In case of a succesful POST request, you can create a new form:
from django.shortcuts import render
from .forms import ContactForm
def contact(request):
template = "contact.html"
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
form = ContactForm()
else:
form = ContactForm()
context = {
'form': form
}
return render(request, template, context)
However in the case of a succesful POST request, it is common to make a redirect, this is the Post/Redirect/Get pattern [wiki]:
from django.shortcuts import render, redirect
from .forms import ContactForm
def contact(request):
template = "contact.html"
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect(contact)
else:
form = ContactForm()
context = {
'form': form
}
return render(request, template, context)
I want to incorporate a drag-and-drop to upload files using Django and HTML. I am able to upload the file and save it to the model "Document". After that, I want to be redirected to 'user:datapreparation', which will display the dataframe in a new page. However, I am not redirected and I stay on the same page ("user:userform").
Do you perhaps know why I am not redirected to datapreparation'?
Hereby the code.
Thank you for your help!
View:
class FileUploadView(View):
form_class = DocumentForm
template_name = 'user/model_form_upload.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
document_name = str(request.FILES['file'])
if request.FILES['file'].size < 31457280: # max 30 mbs allowed
form = self.form_class(request.POST, request.FILES)
document_type = str(document_name.rsplit(".", 1)[1])
valid_document_types = ["txt", "csv", "xlsx"]
if document_type in valid_document_types:
a = Document.objects.all()[0]
a.file = request.FILES['file']
a.description = document_name
a.save()
return redirect('user:datapreparation')
Models:
class Document(models.Model):
description = models.CharField(max_length=255,blank=True)
file = models.FileField(upload_to='documents/')
URL:
from django.conf.urls import url
from . import views
app_name = 'user'
urlpatterns = [
# upload
url(r'^upload/$', views.FileUploadView.as_view(), name='userform'),
# data preparation - dataframe creation
url(r'^datapreparation/$', views.DataPreparation.as_view(), name='datapreparation'),
]
HTML:
<div id="upload"></div>
<form class="dropzone" action="{% url 'user:datapreparation' %}" method="post" enctype="multipart/form-data" id="dropzone">{% csrf_token %}
<div>
Drop files here
</div>
</form>
<script>
(function() {
var form = document.querySelector('form');
var dropzone = document.getElementById('dropzone');
dropzone.ondrop=function(ev){
ev.preventDefault();
this.className='dropzone';
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var file = ev.dataTransfer.files[0]
console.log(file)
xhr.open('POST', "/user/upload/")
data.append('file', file)
xhr.send(data)
};
dropzone.ondragover = function () {
this.className = "dropzone dragover";
return false;
};
dropzone.ondragleave = function () {
this.className = 'dropzone';
return false;
};
}());
The response from django is being handled by the javascript, so you you could return the URL in the django view (using for example the reverse method) and then window.location.href in the javascript.
You can check how to add a callback to XMLHttpRequest here
I believe you're missing the reverse mechanism on your redirect.
from django.urls import reverse
return redirect(reverse('user:datapreparation'))
Edit: I'm using Django dev version so I do have access to JsonResponse (as seen below).
I'm messing around with Django and trying to make it work with AngularJS. Currently I'm attempting to query 4 rows from a database at a time and send the results as a JSON object to an Angular script. I just keep running into issues though - it won't work.
Here's where my code is at right now after a bunch of searching on StackOverflow to try and help myself out:
# views.py
class AJAXListMixin(object):
def dispatch(self, request, *args, **kwargs):
if not request.is_ajax():
raise Http404("Improper access.")
return super(object, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
return Project.objects.filter(added__lte=timezone.now())
def get(self, request, *args, **kwargs):
return JsonResponse(self.get_queryset(), safe=False)
class PageApi(AJAXListMixin, generic.ListView):
paginate_by = 4 # 4 results per page
ordering = '-added' # Most recent to oldest
----------------------
# models.py
class Project(models.Model):
title = models.CharField(max_length=100)
desc = models.TextField()
link = models.URLField(default=None, blank=True, null=True)
slug = models.SlugField(null=True)
added = models.DateField(_("Date Added"), default=datetime.today)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Project, self).save(*args, **kwargs)
def as_dict(self):
return {
"title": self.title,
"description": self.desc,
"link": self.link,
"slug": self.slug,
"date": self.added,
"previews": {
preview.as_dict() for preview in self.preview_set.all()
}
}
class Preview(models.Model):
project = models.ForeignKey(Project)
file = models.FileField(upload_to='project/preview/')
def __str__(self):
return "{project} Preview {id}".format(
project=self.project.title, id=self.id
)
def as_dict(self):
return {
"url": self.file.url
}
And here is the angular code I'm starting off with:
projects = angular.module("Projects", []);
projects.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
}]);
projects.controller("ProjectList", ['$scope', '$http', function ($scope, $http) {
$scope.projects = {};
$scope.page = 1;
$http.get('api/page/' + $scope.page)
.success(function (response) {
console.log(response)
})
.error(function (status) {
alert("Error. Check network logs.");
});
}]);
I want to store the response in the projects $scope variable so that I can do things with the data in my angular template.
I'd recommend taking a look the following post:
http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html or this one https://thinkster.io/django-angularjs-tutorial/
It walks through setting up a REST API in Django to serialize your models, and specifying which fields are to serialized and returning JSON data using the Django Rest Framework.
Note that the example uses CoffeeScript and compiles it into JavaScript using GruntJS.
Instead your Angular controller should look more like the following (assuming you have a URL '/api/projects/', that routes to an API view that returns a JSON object containing multiple projects):
$scope.projects = [];
$http.get('/api/projects/').success(function(data) {
$scope.projects = data;
console.log($scope.projects);
});
Not sure how this would work with the additional pagination, but you can read more about it on the Django Rest Framework docs:
http://www.django-rest-framework.org/api-guide/pagination/
Hope this helps!