serializer.save() not saving data to admin database - django

So, i was making a simple Web app in which i would get in data from user using React JS Front-end Interface and Forms. Django stays in the background where i have made CRUD functions.
My app lets user to create, edit, delete and view the data inputted.
Edit and View work perfectly fine but create has been making a problem for me. There is no error in the browser console or django terminal but the React JS front-end change does not reflect in the Django Admin.
Now, handleChange simply listens to the change made in the HTML form. Active Record is my current form in which new data is being added:
handleChange(e){
var value = e.target.value;
this.setState({
activeRecord:{
...this.state.activeRecord,
[e.target.name]:value
} }) }
handleSubmit() just connects my frontend submit button to Django's CRUD'S Create url. Finally, i set the current object state back to default.
handleSubmit(e){
e.preventDefault()
console.log('Item',this.state.activeRecord)
var csrftoken = this.getCookie('csrftoken')
var url = 'http://127.0.0.1:8080/DataCollection/create/'
fetch(url,{
method:'POST',
headers: {
'Content-type':'application/json',
'X-CSRFToken': csrftoken,
},
body:JSON.stringify(this.state.activeRecord)
}) .then((response)=>{
this.fetchTasks()
this.setState({
activeRecord:{
id: "",
full_name:"",
age:"",
gender:"",
weight:"",
height:"",
salary: "",
project_count: "",
job_domain: "",
experience: "",
no_of_jobs:"",
}
})
}).catch(function(error){
console.log('ERROR',error)
})
}
handleSubmit() just connects my frontend submit button to Django's CRUD'S Create url.
Please note that there is no error shown when i run it but 2nd line console.log in the handlSubmit() function shows the inputted values implying that my added data is reaching react js at least.
Thus, this makes me think there is some issue with the Django part and hence, i have posted this question in this subreddit.
Note: I am an aspiring data scientist who is to start his Master Studies in September 2020. Just wanted to add some Web App Development skills to my resume.
Any suggestion would be appreciated....
Create View:
#api_view(['POST'])
def createRecord(request):
serializer = InputValuesSerializers(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
b.) Serializer: serializers.ModelSerializer had to be this way. Got a gruesome error when i tried to use serializers.Serializer
class InputValuesSerializers(serializers.ModelSerializer):
class Meta:
model = InputValues
fields = 'all'
I've tried all the online resources and discussions but cannot find the solution. This is really frustrating as i can that the data is going where it's supposed to go, but only a single statement might me screwing things up.
I would really appreciate any help over this.

Related

How to stop page refresh on each task addition in my Django To-do app?

I am quite new to the web development world and have just built a Todo app using Django. I have used Django ModelForm for adding tasks to my TaskModel.
Now my problem is that each time I add a task, the whole page refreshes as the added task goes to the database. It is not a very good user experience, as it is refreshing the page on each task addition and also it is taking time for reloading the page. What should I do to stop page refresh but still add the task to the database?
my views.py looks something like this:
def index(request):
if request.method == 'POST':
form = TaskForm(request.POST or None)
if form.is_valid():
form.save()
all_tasks = TaskModel.objects.all()
return HttpResponseRedirect(reverse("index"))
else:
all_tasks = TaskModel.objects.all()
return render(request, "todo_list/index.html", {"all_tasks": all_tasks})
Note: I have used authentication in my todo app so that the tasks can be accessed from any device, so I don't think storing my task merely in the browser cache will work. But I am open to any suggestions.
Back-end
Use django-rest-framework so that you can handle the server traffic manually.
Front-end
You can use a DOM API called XMLHttpRequest, but also you can use more easy to use APIs such as fetch.
When the form event is emitted we have to e.preventDefault().
form.addEventListener("submit", (e)=>{
e.preventDefault();
// use the same URL in form's action <form action="{{url}}"></form>
fetch(url, {
method: "POST",
data: new FormData(form),
})
.then((response)=>{
return response.json()
})
.then((json)=>{
return console.log(json);
})
.catch((err)=>{
console.err(err); // an error occured
});
});
The Django server can respond with a different type of data, plain/text or application/json are suitable in this situation.
BTW, fetch is a function that returns a Promise, so you can use async and await to make you code look better. You can use axios, or JQuery.ajax to make XMLHttpRequest more easy to handle.
Use django-restframework to create the API and then use frontend frameworks like react, vue and etc, to send post request to your Django server, So this way it wouldn't have to reload the page everytime

Django: call REST API through a view instead of Postman

I have a working python code on my desktop that prints and makes PDFs perfectly. All I want to do is use that code and use Django to allow users to enter a value.
My code uses docusign API to call data. I use postman which needs a key and other parameters to use the API. The value entered by my user will determine what data they get.
What I think I have to do is rewrite my code, put it somewhere, then turn it into a view. The view will be sent to template.
Edit -
My code:
# Get Envelope Data- use account ID from above
# Get Todays Date, Daily Setting
day = datetime.datetime.today().strftime('%Y-%m-%d')
url = "https://demo.docusign.net/restapi/v2/accounts/" + accountId + "/envelopes"
# if Envelope is completed
querystring = {"from_date": Date, "status": "completed"}
headers = {
'X-DocuSign-Authentication': "{\"Username\":\""+ email +"\",\"Password\":\""+Password+"\",\"IntegratorKey\": \""+IntegratorKey+"\"}",
'Content-Type': "application/json",
'Cache-Control': "no-cache",
'Postman-Token': "e53ceaba-512d-467b-9f95-1b89f6f65211"
}
response = requests.request("GET", url, headers=headers, params=querystring)
envelopes = response.text
Sorry, let me try again. I currently have a python3 program on my desktop. I run it with idle and everything is how I want it.
What I want to do with Django is use this code to print its outputs on a webpage and have the user download it’s additional csv file output. I have managed to make a Django localhost and I am stuck at that point. I do not know how to use my python3 code to run to webpage.
The code is made up of API calls, I use postman to help me with sending the right parameters. I will add a picture of code. All I want is for user to enter value such as accountID so that the API can complete the request and give them data for their own request.
I'll try to give you a overview of how this could work with Django.
You could have a form to obtain the users account_id.
class AccountForm(forms.Form):
account_id = forms.IntegerField()
You could display this form through a generic FormView (see also this):
class AccountView(views.FormView):
form_class = AccountForm
template_name = 'account.html'
def form_valid(self, form):
# here you make your request to the external API
account_id = form.cleaned_data['account_id']
url = "https://demo.docusign.net/restapi/v2/accounts/" + account_id + "/envelopes"
headers = ...
querystring = ...
resp = requests.request("GET", url, headers=headers, params=querystring)
ctx = {
'result': resp.text,
}
return render(self.request, 'result.html', ctx)
I don't show the template account.html here. You will have to figure that one out yourself; the links I provided should point you in the right direction.
Now, what remains to be determined is what exactly the method form_valid should return. The code I showed renders a template with the API call response in the context, so in your template result.html you could display the result data any way you like.
You mentioned downloading a CSV file as well. That could be a different view, probably triggered by a link or button in result.html.

Django - How to stay on the same page without refreshing page?

I am using Boostrap modal fade window which renders Django form to update my database records. And what I fail to do is not to reload the page if the user has opened the Update window and did not change anything. It will be easier to get my idea if you look at the code below:
def updateTask(request, task_id):
#cur_usr_sale_point = PersonUnique.objects.filter(employees__employeeuser__auth_user = request.user.id).values_list('agreementemployees__agreement_unique__sale_point_id',flat=True)
selected_task = Tasks.objects.get(id=task_id)
task_form = TaskForm(instance=selected_task )
taskTable = Tasks.objects.all()
if request.method == 'POST':
task_form = TaskForm(request.POST,instance=selected_task)
if task_form.has_changed():
if task_form.is_valid():
# inside your model instance add each field with the wanted value for it
task_form.save();
return HttpResponseRedirect('/task_list/')
else: # The user did not change any data but I still tell Django to
#reload my page, thus wasting my time.
return HttpResponseRedirect('/task_list/')
return render_to_response('task_management/task_list.html',{'createTask_form':task_form, 'task_id': task_id, 'taskTable': taskTable},context_instance=RequestContext(request))
The question is, is there any way to tell Django to change the url (like it happens after redirecting) but not to load the same page with same data for the second time?
It's not trivial, but the basic steps you need are:
Write some javascript to usurp the form submit button click
Call your ajax function which sends data to "checking" view
Write a "checking" view that will check if form data has changed
If data have changed, submit the form
If not, just stay on page
This blog post is a nice walkthrough of the entire process (though targeted towards a different end result, you'll need to modify the view).
And here are some SO answers that will help with the steps above:
Basically:
$('#your-form-id').on('submit', function(event){
event.preventDefault();
your_ajax_function();
});
Call ajax function on form submit
Gotta do yourself!
Submit form after checking

Is there a way for angular to get the current user when using basic login from django

All is in my title. I would like to get the current user information because i need it in my view to display action (delete/edit) depending of the user's rights.
I use the basic authentification make by Django (/login /logout), i didn't change anything. Is there a way to listen to this login/logout action and retrieve this information in the Angular context?
Pretty new in angular, i'm searching some informations that would help me to go in one or other direction.
Actually i don't have a REST API for authenticated my users.
I find some interesting article Best place/way to store 'global' data such as 'current logged in user' / How do I store a current user context in Angular? but for now as i said i don't have AuthService just the basic login/logout from Django.
I used Django Rest framework for some action on my project (like post/delete/read/update for some of my models) and it works fine with angularjs. But i'm happy with the basic authentification provided by Django, so i don't want to rewrite it. But i don't know how to listen on it and if it's possible.
I know that is a broad question and for now i dont't have code to show because afters hours of research i don't know where i need to begin.
If it's to broad i will remove it.
Thanks,
OK, you can do something like that
Example (someUrl is url to your function in view.py):
In angular controller add $http
$http({method: 'POST', url: '/someUrl'}).
success(function(data){
//process aswer
});
In djnago view.py:
from django.shortcuts import HttpResponse
import json
def check_login(request):
if request.user.is_authenticated():
return HttpResponse(json.dumps({'result': {'logged': True}, 'user': request.user.username}),
content_type="application/json")
else:
return HttpResponse(json.dumps({'result': {'logged': False}}),
content_type="application/json")

Django- Redirect to same view without reloading

I have a view (views.loaditems) which runs some algorithm and passes items to a template(product.html) where the items are loaded, and with each item, I have a "add_to_shortlist" link. On clicking this link, the item is added in the user's shortlist (for which I have a function). I want that on click, the page is not reloaded and has its items, but simply add that item to the user's shortlist. Also, where should I define this shortlist function?
I'm new to Django, and any help would be much appreciated. Thanks.
Update: Here's my code:
views.py
def loaditems(request):
#some code
ourdeals = SDeals.objects.filter(**{agestring3:0})
sorteddeals = ourdeals.order_by('-total_score')
user = request.user
context = {'deals': sorteddeals, 'sl_products':sl_products, 'user':user,}
template='index.html'
return render_to_response(template, context, context_instance=RequestContext(request))
def usersl(request, id, id2):
userslt = User_Shortlist.objects.filter(id__iexact=id)
products = SDeals.objects.filter(id__iexact=id2)
product = products[0]
if userslt:
userslt[0].sdeals.add(product)
sl = userslt[0].sdeals.all()
return render_to_response('slnew.html', {'sl':sl}, context_instance=RequestContext(request))
in my index.html I have:
<div class="slist"></div>
which in urls.py takes me to views.usersl:
url(r'^usersl/(?P<id>\d+)/(?P<id2>\d+)/$', views.usersl),
I don't want to go to slnew.html, instead be on index.html without reloading it, and on click 'slist', just run the function to add to shortlist.
In order to make changes on the server and in a page without navigating with the browser you need to look at JavaScript solutions. Read up about Ajax. In essence you need to use some JavaScript to send the update to the server, and to change the HTML.
JQuery is one popular library that will help you to do this. A more sophisticated example is AngularJS. On the Django side you'll write some views that handle these small update tasks used in the page. Libraries like Django REST framework or Django Slumber will help you with that.