i want to show duplicate value error on front end - django

i have an query_name field in database. i want that every value should be unique so i changed it constraint and add unique= true.
now i want that if user enter the duplicate value then error duplicate value show to the user. currently error is showing only in backend
here is my code in python
def save_report(request):
if request.method == 'POST':
print(request.POST.dict())
data_dict = request.POST.dict()
query_json = {}
#query json data
query_json['data_src_name'] = data_dict['data_src_name']
query_json['fields'] = data_dict['fields']
query_json['group_by'] = data_dict['group_by']
query_json['order_by'] = data_dict['order_by']
query_json['where'] = data_dict['where']
query_json['limit'] = data_dict['limit']
query_json = json.dumps(query_json)
report_creation_obj = ReportCreationData.objects.create(
query_json = query_json,
data_source_name = data_dict['data_src_name'],
query_name = data_dict['query_name'],
mail_body = data_dict['mail_body'])
report_creation_obj.save()
return HttpResponse('success')
else:
return render(request, 'home/report_creation.html', context = None)
database :
query_name = models.CharField(max_length=100,unique= True, default= True)
code 2 :
def save_report(request):
if request.method == 'POST':
print(request.POST.dict())
querydata = ReportCreationData.objects.all()
querydata_list = []
querydata_dict = {'query_name':''}
for data in querydata:
querydata_dict['query_name'] = data.query_name
print ('querydata_dict', querydata_dict)
data_dict = request.POST.dict()
query_name = data_dict['query_name'],
print ('query_name', query_name)
query_json = {}
#query json data
query_json['data_src_name'] = data_dict['data_src_name']
query_json['fields'] = data_dict['fields']
query_json['group_by'] = data_dict['group_by']
query_json['order_by'] = data_dict['order_by']
query_json['where'] = data_dict['where']
query_json['limit'] = data_dict['limit']
query_json = json.dumps(query_json)
report_creation_obj = ReportCreationData.objects.create(
query_json = query_json,
data_source_name = data_dict['data_src_name'],
query_name = data_dict['query_name'],
mail_body = data_dict['mail_body'])
if (query_name == querydata_dict).exists():
raise ('already exists')
else:
report_creation_obj.save()
return HttpResponse('success')
else:
return render(request, 'home/report_creation.html')
with code 2 getting error:
AttributeError: 'bool' object has no attribute 'exists'
Please help
Thanks

You can try before inserting the data,run a select query from database and apply where clause on your query_name with your current value.So by this you can get duplicate records.

Related

inserting a lot of data via create_bulk

hello I have a table named Exercise data where I pass data from form and save them in the db, my problem is that I have more same objects to save inside the db but I don't know how to do it.
I left you my views.py file where you can find the code I created.
I read around that I should use the create_bulk but I don't understand how I can pass it some data from my form, could someone help me please? =)
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
schedaName = form.cleaned_data['nome_scheda']
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
gruppi = DatiGruppi(
giorni_settimana = form.cleaned_data['giorni_settimana'],
dati_gruppo = form.cleaned_data['dati_gruppo'],
gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
)
gruppi.save()
esercizi = DatiEsercizi(
serie = form.cleaned_data['serie'],
ripetizione = form.cleaned_data['ripetizione'],
peso = form.cleaned_data['peso'],
gruppo_single = DatiGruppi.objects.get(gruppi_scheda = scheda.id),
dati_esercizio = form.cleaned_data['dati_esercizio']
)
#esercizi.save()
print(esercizi)
return redirect('/backoffice')
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)

elif condition in django view

I'm having view function which filters object according to the data I give and if that filtered object does not exist in the database it adds the object to DB(i didn't write add function yet). Shows error if it exists already. I'm getting data from a template using ajax post request.
#view.py
#csrf_exempt
def setUserInDB(request):
if request.method=="POST":
if request.POST.get('pname','u_id'):
pname = request.POST.get('pname')
u_id = request.POST.get('u_id')
user = userprofile.objects.get(pk=u_id)
pid = Project.objects.get(title=pname)
else:
u_id = None
pname = None
if request.POST.get('db_id','chkbox'):
db_id = request.POST.get('db_id')
db = Db_profile.objects.get(pk=db_id)
chkbox = request.POST.get('chkbox')
print chkbox
else:
db_id = None
chkbox = None
if Projectwiseusersetup.objects.filter(userid=user,project_id=pid,
db_profileid= db,setasdefaultproject=chkbox):
print "already exist"
elif (((Projectwiseusersetup.objects.filter(userid = user,project_id =
pid,db_profileid=db,setasdefaultproject=False)).exists()) and
(chkbox==True)):
print "FtoT"
elif Projectwiseusersetup.objects.filter(userid = user,project_id =
pid,db_profileid=db,setasdefaultproject=True) and chkbox==False:
print "TtoF"
else:
print "aaaa"
user,pid,db,chkbox }---- i'm getting these data from ajax post request,
userid, project_id, db_profileid, setasdefaultproject(boolean) }----- model fields
when I try to check my elif condition, i'm getting output in console "aaaa"(else part). what is wrong with elif?
Here the ex:
x = 4
if x == 1:
print ("1")
elif (x == 2):
print("2")
elif (x == 3):
print("3")
else:
print("4")

Save request.POST to database

in view.py:
#require_POST
#csrf_exempt
def ipn(request):
transactions_logger = logging.getLogger("django")
processor = Ipn(request.POST, logger=transactions_logger)
verification_success = processor.verify_ipn()
encoding = request.POST.get('ok_charset', None)
data = QueryDict(request.body, encoding=encoding)
if verification_success:
form = OkpayIpnForm(data)
if form.is_valid():
print("ALL FINE!!")
form.save()
return HttpResponse("")
In forms.py:
class OkpayIpnForm(forms.ModelForm):
class Meta:
model = OkpayIpn
exclude = []
Code for IPN Checkprocessor = Ipn(request.POST, logger=transactions_logger:
class Ipn(object):
OKPAY_VERIFICATION_URL = 'https://checkout.okpay.com/ipn-verify'
OKPAY_IPN_INVALID = b'INVALID'
OKPAY_IPN_VERIFIED = b'VERIFIED'
OKPAY_IPN_TEST = b'TEST'
OKPAY_STATUS_COMPLETED = 'completed'
__verification_result = False
def __init__(self, request_data, logger):
if 'ok_verify' in request_data:
raise Exception("ok_verify must not be present in initial request data for {}".format(
self.__class__.__name__
))
self._request_data = request_data
self.logger = logger
return
def verify_ipn(self):
self.__verification_result = False
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
verify_request_payload = {
'ok_verify': 'true',
}
verify_request_payload.update(self._request_data)
resp = requests.post(self.OKPAY_VERIFICATION_URL, data=verify_request_payload, headers=headers)
if resp.content == self.OKPAY_IPN_VERIFIED or resp.content == self.OKPAY_IPN_TEST:
self.__verification_result = True
# if resp.content == self.OKPAY_IPN_VERIFIED: # anyway disable test on production.
# self.__verification_result = True
return self.__verification_result
All is ok, I revice IPN and validate it, then I try to validate form and save it to Database.
But form doesn't pass validation and doesn't save to database.
Thank You for help
Problem was that 1 CharField of Model for saving IPN has maxlength=20, but recieved 40 symbols.
Thx jape he advised to add in form validation else statement and print form.errors
the error of of form validation was :
<li>ok_item_1_type<ul class="errorlist"><li>Ensure this value has at most 20 characters (it has 40).</li></ul></li>

Django. Contains 2 slightly different forms but second form's data being saved in both

Here are my lines dealing with the two forms :
user = request.user
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
The data submitted in second form is being saved in both liked and disliked.
I have used User foreignkey in both the liked and disliked models.
Here is the complete function :
def collect(request):
context = RequestContext(request)
submitted = False
if request.method == 'POST':
data = request.POST
user_liked_form = UserLikedForm(data = request.POST)
user_disliked_form = UserDislikedForm(data = request.POST)
# user_id = data["user_id"]
user = request.user
if user_liked_form.is_valid() and user_disliked_form.is_valid():
# user_liked_form.save(commit = True)
# user_disliked_form.save(commit = True)
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
submitted = True
else:
print user_liked_form.errors, user_disliked_form.errors
else:
user_liked_form = UserLikedForm()
user_disliked_form = UserDislikedForm()
return render_to_response(
'collect.html',
{'user_liked_form': user_liked_form, 'user_disliked_form': user_disliked_form, 'submitted': submitted},
context)
It sounds like your UserLikedForm and UserDislikedForm have the same field names and when the form is submitted, only the second value comes through in request.POST. To fix this, you will need to add a prefix to the forms:
user_liked_form = UserLikedForm(prefix='liked')
user_disliked_form = UserDislikedForm(prefix='disliked')
That way when the forms are rendered, each form will have unique field names.

Django: saving into model field

another django question. I have a edit form like this. Look at current_status in the code.
It has been updated:
def edit_item(request, client_id = 0, item_id = 0):
client = None
item = None
status = None
contact = None
status_id = request.POST.get('status_id', None)
contact_id = request.POST.get('contact_id', None)
save_item = request.POST.get('save_item', None)
save_status = request.POST.get('save_status', None)
try:
client = models.Client.objects.get(pk = client_id)
item = models.StorageItem.objects.get(pk = item_id)
except:
return HttpResponseNotFound()
try:
status = models.Status.objects.get(pk = status_id)
contact = models.Contact.objects.get(pk = contact_id)
except:
pass
if request.method == 'POST':
form = forms.ItemForm(request.POST, instance = item)
if form.is_valid() and save_item is not None:
form.save(True)
request.user.message_set.create(message = "Item {0} has been updated successfully.".format(item.tiptop_id))
return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")
if status is not None and contact is not None and save_status is not None:
current_status = models.ItemStatusHistory(item = item, contact = contact, status = status,
user = request.user)
item.current_item_status_date = date.today()
item.save()
current_status.save()
request.user.message_set.create(message = "Item status has been updated successfully.")
else:
form = forms.ItemForm(instance = item)
title = str(client) + ' : Edit Item'
status_list = models.Status.objects.all()
return render_to_response('edit_item.html', {'form':form, 'title':title, 'status_list':status_list, 'item':item}, context_instance = RequestContext(request))
current_status save's the latest date of when the form is edited. What I ALSO want to do is to save this value into this models field.
class StorageItem(models.Model):
current_item_status_date = models.DateField()
Is ItemForm a ModelForm (see Django Model Forms)?
If so form.save() will return a model instance. Then you can edit its fields if you need to. For example.
my_obj = form.save()
my_obj.current_item_status_date = datetime.date.today()
my_obj.save()
If not, then simply create a new instance of your model and save the field value.
my_obj = StorageItem(current_item_status_date=datetime.date.today())
my_obj.save()