form throwing a internal server error on submit with ajax, django - django

I have a form that is throwing a internal server error when i submit it with data
it says it is due to an integrity error:
IntegrityError at /cookbook/createrecipe/
(1048, "Column 'original_cookbook_id' cannot be null")
what is weird is that i dont have a column original_cookbook_id - what i do have is an original_cookbook that is a foreign key to a cookbook model
here is the view that is giving the error:
def createrecipe(request):
print "entering createrecipeview"
if request.method == 'POST':
print "form is a post"
form = RecipeForm(request.POST)
print form.errors
if form.is_valid():
print "form is valid"
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})// this is where the error is being thrown
form.save()
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form': form,
})
data = {
'replace': True,
'form': t.render(c),
'success': True,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
else:
print "form is invalid"
form = RecipeForm(request.POST)
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form':form,
})
data ={
'form': t.render(c),
'success': False,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
i think i might be declaring the original_cookbook the wrong way
anyone else have any experience with _id being appended to a foreign key/ have any idea how i might be able to resolve this issue
thanks a lot
katie
update
here is my javascript function
<script type="text/javascript">
$(document).ready(function(){
function hijack() {
var form = $('form#createrecipeform');
form.each (function(){
this.reset();
});
form.submit(function(e) {
e.preventDefault();
console.log('ajax form submission function called successfully.');
//form = $(this);
console.log(form)
var serialized_form = form.serialize();
$.ajax({ type: "POST",
url: $(this).attr('action'),
data: serialized_form,
success: (function(data) {
console.log('ajax success function called successfully.');
data = $.parseJSON(data);
if (data.success) {
console.log('success');
//right now it is logging success to
//console but nothing else is happening
//what else should happen on data success?
} else {
console.log('failure');
var newForm = data.form;
form.replaceWith(newForm);
hijack();
}
})
});
return false;
});
};
hijack();
});
</script>

You do have an original_cookbook_id field. That's where the pk for the foreign key is store in the table. Django automagically appends the _id bit. All the error means is that that field is set to NOT NULL, and you didn't provide a value to original_cookbook to fill it in with.
UPDATE
There's nothing "wrong" per se, but a few things to note. First, initial only sets the initial value that appears in the form (obviously enough). However, if it's later set back to empty by the user or some other action, it's still empty, i.e. initial has no true effect on the eventual posted data.
You didn't post your javascript, so I can't speak to how you're submitting the form, but that too could potentially be an issue. If you're not submitting the field with the rest of the AJAX post, for whatever reason, it doesn't matter what the actual field may or may not be set to.

Related

Using Modelform with ModelChoicefield does not work for me, gives undefined error when submitting the form

I am trying to use a form that adds data to the model RaportProductie using AJAX.
In the form I have 2 dropdown inputs that take data from the ManoperaRaportareBloc model.
These are the attributes from ManoperaRaportareBloc : categorie_lucrare and subcategorie_lucrare
When I submit the form it shows an error with undefined.
Please help.
ty.
forms.py:
class RaportProductieForm(forms.ModelForm):
data = forms.DateField(initial=datetime.date.today)
categorie_lucrare = forms.ModelChoiceField(queryset=ManoperaRaportareBloc.objects.all().values_list('categorie_lucrare', flat=True))
subcategorie_lucrare = forms.ModelChoiceField(queryset=ManoperaRaportareBloc.objects.all().values_list('subcategorie_lucrare', flat=True))
class Meta:
model = RaportProductie
fields = ['lucrare', 'data', 'tip', 'subcontractor', 'obiectiv', 'categorie_lucrare', 'subcategorie_lucrare', 'um', 'cantitate', 'valoare_prod']
views.py:
def raportproductie_create_view(request):
# request should be ajax and method should be POST.
if request.is_ajax and request.method == "POST":
# get the form data
form = RaportProductieForm(request.POST)
# save the data and after fetch the object in instance
if form.is_valid():
instance = form.save()
# serialize in new friend object in json
ser_instance = serializers.serialize('json', [ instance, ])
# send to client side.
return JsonResponse({"instance": ser_instance}, status=200)
else:
# some form errors occured.
data = {
'result': 'error',
'message': 'Form invalid',
'form': 'oops.'
}
return JsonResponse(data, status=400)
# some error occured
return JsonResponse({"error": ""}, status=400)
template.html:
$("#friend-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
// serialize the data for sending the form data.
var serializedData = $(this).serialize();
console.log(serializedData)
// make POST ajax call
$.ajax({
type: 'POST',
url: "{% url 'proiecte:raportprod-create' %}",
data: serializedData,
success: function (response) {
// display the newly friend to table.
var instance = JSON.parse(response["instance"]);
var fields = instance[0]["fields"];
$("#table-ajax tbody").prepend("<tr><td>"+fields.data+"</td><td>"+fields.tip+"</td><td>"+fields.subcontractor+"</td><td>"+fields.obiectiv+"</td><td>"+fields.categorie_lucrare+"</td><td>"+fields.subcategorie_lucrare+"</td><td>"+fields.um+"</td><td>"+fields.cantitate+"</td><td>"+fields.valoare_prod+"</td></tr>")
},
error: function (xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.error);
}
})
})
later edit:
i've used pdb to debug, printed the form before checking if valid and it returns this:
form.data
<QueryDict: {'csrfmiddlewaretoken': ['*********'], 'lucrare': ['1'], 'date': ['2023-01-10'], 'tip': ['1'], 'subcontractor': ['TGC Tadjiki'], 'obiectiv': ['obiectiv'], 'categorie_lucrare': ['CONFECTII_METALICE'], 'subcategorie_lucrare': ['CONSTRUCTIE ATIC - CONF METALICA'], 'um': ['km'], 'cantitate': ['2'], 'valoare_prod': ['0']}>
so...the inputs are working,
also in the ajax code, i've also gave a console.log(serializedData) and it outputs this:
csrfmiddlewaretoken=***********=1&date=2023-01-10&tip=1&subcontractor=TGC%20Tadjiki&obiectiv=obiectiv&categorie_lucrare=HIDRO_TERASE&subcategorie_lucrare=CONSTRUCTIE%20ATIC%20-%20CONF%20METALICA&um=mp.&cantitate=2&valoare_prod=0
later later edit:
when I am not using ModelChoiceField in the forms.py, and write the inputs by hand, the form submits...
I found an answer to my question, in the Modelform modified the custom queryset so that they remain Charfield and have added choices:
class RaportProductieForm(forms.ModelForm):
date = forms.DateField(initial=datetime.date.today)
queryset=ManoperaRaportareBloc.objects.all()
OPTIONS1 = [(choice.pk, choice.categorie_lucrare) for choice in queryset]
OPTIONS2 = [(choice.pk, choice.subcategorie_lucrare) for choice in queryset]
queryset2 = Echipa.objects.all()
OPTIONS3 = [(choice.pk, choice.nume) for choice in queryset2]
categorie_lucrare = forms.CharField(widget=forms.Select( choices = OPTIONS1 ))
subcategorie_lucrare = forms.CharField(widget=forms.Select( choices = OPTIONS2 ))
subcontractor = forms.CharField(widget=forms.Select( choices = OPTIONS3 ))
class Meta:
model = RaportProductie
fields = ['lucrare', 'date', 'tip', 'subcontractor', 'obiectiv', 'categorie_lucrare', 'subcategorie_lucrare', 'um', 'cantitate', 'valoare_prod']

Navigating to different page instead of Ajax call

I am trying to save a form via ajax as I don't want to reload the page. It is working not completely but it is updating the data except the image or video or any upload file we give.
but after updating it is coming back to the ajax page but the url is diiferent and success message is coming on that page.
I am sharing some of the logic but if more information is required, please let me know .
js code :
$(document).ready(function() {
$('#contentdataform').submit(function(e) {
e.preventDefault();
$.ajax({ // create an AJAX call...
data: $(this).serialize(),
type: 'POST',
url: 'updatecontent',
success: function() {
mess("Success"); //mess is a function to generate a disappearing message box.
},
});
return false;
});
});
function updatecontentform(){
console.log('starting');
document.getElementById('contentdataform').submit();
}
views.py
#csrf_exempt
def updatecontent(request):
print("--------------------")
if request.method == "POST":
id = request.session['content_id']
fm = ContentForm(request.POST, instance= Content.objects.get(pk = id))
print("fm")
print(fm)
if fm.is_valid:
print("valid form")
form = fm.save(commit=False)
form.save()
else:
print("Not Valid")
return JsonResponse("Success", safe= False)
the output should be the message on the same page but it is reflecting on the new page with url '127.0.0.1:8000/updatecontent'

Show loading gif until the django view performs the data processing and renders the template with this data

I have a django project where the page has multiple nav links representing different agents. On clicking any nav link, the urls.py redirects to nav specific view and the view needs to perform some processing to get the data needed to render the template. However as this is syncrhonous rendering it takes a long while to load data (in the order of 15-20s).
Below is my urls.py:
from django.urls import path
from . import views
app_name = 'agent'
urlpatterns = [
path('agent1/', views.agent1, name='agent1'),
path('agent2/', views.agent2, name='agent2'),
path('agent3/', views.agent3, name='agent3'),
path('agent4/', views.agent4, name='agent4'),
]
My views method looks as below:
def agent1(request):
agent_data = Agent1.objects.all()
agent_details = get_agent_details(agent_data)
return render(request, 'manager/data.html', {'agent_data': agent_data, 'agent_details': agent_details})
I am using the {{ agent_data.name }}, {{ agent_data.code }}, {{ agent_data.qty }} and {{ agent_data.price }} along with data from agent_details dictionary in my html to populate a table's rows. How should I change my view method, so that it loads the data via AJAX (javascript) in order to show a loading gif in the meantime and also provide me the data so that I can populate the table. Could someone help me with the Ajax code and the steps as I am new to this technology and not finding any help going through the online tutorials.
So for this to work with ajax, you'll need some javascript in manager/data.html which knows the url to fetch data from.
As an example, I've got an ajax setup which checks a given email address isn't already in use;
(function($) {
$(document).ready(function() {
var validateEmailURL = $section_user_signup.data('ajax-email-url');
function validateEmailUnique() {
var valid = true;
clearError($email);
// Fetch unique status of the provided email
$.ajax({
async: false,
url: validateEmailURL,
method: 'POST',
type: 'POST',
dataType: 'json',
data: {
'email': $email.val(),
'csrftoken': $form.find('input[name="csrfmiddlewaretoken"]').val()
},
success: function (response) {
valid = true;
},
error: function (response) {
setError($email, response["responseJSON"]["error"]);
valid = false;
}
});
return valid;
}
});
})(window.jQuery);
This javascript uses the data attribute of a div for the URL to check;
<div data-ajax-email-url="{% url 'account_ajax_validate_email' %}">
The view which the ajax call goes to looks like this;
def ajax_check_email_unique(request, *args, **kwargs):
"""
Return an JsonResponse to identify if an email is unique.
"""
if not request.is_ajax():
return HttpResponseBadRequest()
if request.is_ajax and request.method == "POST":
email = request.POST.get('email')
if email_address_exists(email):
return JsonResponse(
{
"error":
"Email address already exists. Click "
f"here "
"to login"
},
status=400
)
return JsonResponse(
{"email": email},
status=200
)
# some error occurred
return JsonResponse({"error": ""}, status=400)
The important thing for any view which will be used by javascript is that you return a JsonResponse.
So if I was you, I'd setup a new view for ajax, and that makes your existing one really simple;
def agent1_ajax(request):
agent_data = Agent1.objects.all()
agent_details = get_agent_details(agent_data)
return JsonResponse({
"agent_data": agent_data, "agent_details": agent_details
}, status=200)
def agent1(request):
return render(request, 'manager/data.html', {})
And as far as a loading gif goes, you'd need an element that contains the gif and then you can bind to the ajax event to show/hide;
$(document).ajaxStart(function() {
$("#loading").show();
});
$(document).ajaxStop(function() {
$("#loading").hide();
});

Testing AJAX in Django

I want to test an AJAX call in my Django app.
What is does is adding a product to a favorite list. But I can't find a way to test it.
My views.py:
def add(request):
data = {'success': False}
if request.method=='POST':
product = request.POST.get('product')
user = request.user
splitted = product.split(' ')
sub_product = Product.objects.get(pk=(splitted[1]))
original_product = Product.objects.get(pk=(splitted[0]))
p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product)
p.save()
data['success'] = True
return JsonResponse(data)
My html:
<form class="add_btn" method='post'>{% csrf_token %}
<button class='added btn' value= '{{product.id }} {{ sub_product.id }}' ><i class=' fas fa-save'></i></button
My AJAX:
$(".row").on('click', ".added", function(event) {
let addedBtn = $(this);
console.log(addedBtn)
event.preventDefault();
event.stopPropagation();
var product = $(this).val();
console.log(product)
var url = '/finder/add/';
$.ajax({
url: url,
type: "POST",
data:{
'product': product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
addedBtn.hide();
}
});
});
The problem is that I pass '{{product.id }} {{ sub_product.id }}' into my views.
My test so far:
class Test_add_delete(TestCase):
def setUp(self):
self.user= User.objects.create(username="Toto", email="toto#gmail.com")
self.prod = Product.objects.create(
name=['gazpacho'],
brand=['alvalle'],
)
self.prod_2 = Product.objects.create(
name=['belvita'],
brand=['belvita', 'lu', 'mondelez'],
)
def test_add(self):
old_saved_products = SavedProduct.objects.count()
user = self.user.id
original_product = self.prod.id
sub_product = self.prod_2.id
response = self.client.post(reverse('finder:add', args=(user,))), {
'product': original_product, sub,product })
new_saved_products = SavedProducts.objects.count()
self.assertEqual(new_saved_products, old_saved_products + 1)
My test is not running and I get a SyntaxError 'product': original_product, sub_product. I know it's not the proper way to write it but my AJAX send the two ids with a space in between to the view.
If all you want to do is test if the data was actually saved, instead of just returning data['success'] = True you can return the whole entire new object... That way you can get back the item you just created from your API, and see all the other fields that may have been auto-gen (ie date_created and so on). That's a common thing you'll see across many APIs.
Another way to test this on a Django level is just to use python debugger
import pdb; pdb.set_trace() right before your return and you can just see what p is.
The set_trace() will stop python and give you access to the code scope from the command line. So just type 'l' to see where you are, and type(and hit enter) anything else that's defined, ie p which will show you what p is. You can also type h for the help menue and read the docs here

interaction Django and Ajax

I'm trying to send data to the server and use with AJAX
function stats(e){
jQuery.ajax({
type: "POST",
url:"stats",
data:{'csrfmiddlewaretoken': document.getElementsByName('csrfmiddlewaretoken')[0].value,
'test':{}},
success: function(data) {alert("Congratulations!"+data);},
error: function(data) {
alert("Please report this error: "+data.responseText);}
});
}
function in views.py:
def stats(request):
if request.is_ajax():
if request.user.is_authenticated():
if request.POST:
return HttpResponse(request.POST['test'])
else:
return HttpResponse("post_no_exists")
else:
return HttpResponse("no authenticate")
else:
raise Http404
Django raise MultiValueDictKeyError 'key "test" not found in QueryDict'.
When I change "test":{} -> "test":1 it succeds.
Whats my error?
Here:
...
data: {
'csrfmiddlewaretoken': ...,
'test': {}
}
...
You're trying to send an empty object literal as part of the POST request. jQuery can't figure out what value to send for that (empty object? what would that even mean?), so it simply doesn't send the test parameter at all. Thus, on the server side, trying to access request.POST['test'] throws a KeyError.
When you change the test to a different literal (in this case a number), jQuery can easily encode and send that as the value.
You need return answer as json
payload = {'answer': 'post_no_exists'}
return HttpResponse(json.dumps(payload, cls=LazyEncoder), content_type='application/json')
in js
alert("Congratulations!"+data.answer);