How to increment django DB using cookies - python

I am trying to increment my DB by 1 if a user has not visited that unique item.pk before. At the moment it will only increment by 1 for all items in my DB, id like to to increment by 1 for each item.pk in the DB.
The view is to Create a view that returns a single bug object based on the bug ID (pk) and render it to the bug_detail.html template or return 404 error if object is not found Also handles commenting on the bug as well as regulating the amount of views attributed to the bug.
def bug_detail(request, pk):
bug = get_object_or_404(Bug, pk=pk)
if request.method == "POST":
form = BugCommentForm(request.POST)
if form.is_valid():
bugComment = form.save(commit=False)
bugComment.bug = bug
bugComment.author = request.user
bug.comment_number += 1
bug.save()
bugComment.save()
return redirect(reverse('bug_detail', kwargs={'pk': pk}))
else:
messages.error(
request,
"Looks like your comment is empty!",
extra_tags="alert-danger")
form = BugCommentForm(instance=bug)
return redirect(reverse('bug_detail', kwargs={'pk': pk}))
else:
form = BugCommentForm()
comments = BugComment.objects.filter(bug__pk=bug.pk)
comments_total = len(comments)
response = render(request,
'bug_detail.html',
{'bug': bug,
'comments': comments,
'comments_total': comments_total,
'form': form})
if 'last_visit' in request.COOKIES and 'bugg' in request.COOKIES:
last_visit = request.COOKIES['last_visit']
# the cookie is a string - convert back to a datetime type
last_visit_time = datetime.strptime(
last_visit[:-7], "%Y-%m-%d %H:%M:%S")
curr_time = datetime.now()
if (curr_time - last_visit_time).days > 0:
# if at least one day has gone by then inc the views count.
response.set_cookie('last_visit', datetime.now())
bug.views += 1
bug.save()
elif 'bugg' not in request.COOKIES:
response.set_cookie('last_visit', datetime.now())
response.set_cookie('bugg', bug.pk)
bug.views += 1
bug.save()
else:
response.set_cookie('last_visit', datetime.now())
response.set_cookie('bugg', bug.pk)
bug.views += 1
bug.save()
return response

Related

form initials do not show

i am trying to set the form initials for the sender field as the logged in user, and it does not show. i removed the if request method statement and adjusted the indentaion and the initials showed. I am stuck, i believe the form is supposed to have that request method statement. i've gone through the documentation and it says the post method binds the data and submits, but there isn't any data when the page is refreshed or newly loaded. what could be wrong?
views.py
def transfer(request):
profile = Profile.objects.get(user=request.user)
if request.method == "POST":
form = TransferForm(request.POST,initial={"sender": profile})
if form.is_valid():
print(form)
form.save()
sender = models.sendcoins.objects.get(sender=request.user.profile)
profile2 = Profile.objects.get(username=receiver)
user_wallet = wallet.objects.get(owner=profile)
print(receiver)
temp = sender # NOTE: Delete this instance once money transfer is done
receiver = models.wallet.objects.get(owner=profile2) # FIELD 1
transfer_amount = sender.amount # FIELD 2
sender = models.wallet.objects.get(owner=profile) # FIELD 3
# Now transfer the money!
sender.balance = sender.balance - transfer_amount
receiver.balance = receiver.balance + transfer_amount
# Save the changes before redirecting
sender.save()
receiver.save()
temp.delete() # NOTE: Now deleting the instance for future money transactions
else:
return(HttpResponse("form is not valid"))
else:
form = TransferForm()
return render(request, "sendcoins.html", {"form": form})

Django problem with request.get to postgresql

Getting stuck with this issue, I've got a table that has date, category and sum and I'm trying to make a query that can choose between dates to get records, but when i pick dates it screams "column "2020-12-12" does not exist"
views.py
def outgoings_history(request):
if request.method == "POST":
date_from= request.POST.get('date_from')
date_to= request.POST.get('date_to')
search_result = Outgoings.objects.filter(user=request.user).order_by('-date')\
.raw('SELECT suma, kategoria, date FROM outgoings WHERE date BETWEEN "2020-12-12" AND "2020-12-12"')
return render(request, 'outgoings_history.html', {'data': search_result})
else:
displaydata = Outgoings.objects.filter(user=request.user).order_by('-date')
return render(request, 'outgoings_history.html', {'data': displaydata})
forms.py
class PickADate(forms.Form):
date_from= forms.DateField(widget=DateInput())
date_to= forms.DateField(widget=DateInput())[enter image description here][1]
The date '2020-12-12' is just a example and it has records this day but still doesn't show anything
You don't need to use .raw for this, you can use a `.filter():
from django.contrib.auth.decorators import login_required
#login_required
def outgoings_history(request):
search_result = Outgoings.objects.filter(
user=request.user,
).order_by('-date')
if request.method == 'POST':
form = PickADate(request.POST)
if form.is_valid():
date_from = form.cleaned_data['date_from']
date_to = form.cleaned_data['date_to']
search_result = search_results.filter(
date__range=(date_from, date_to)
)
return render(request, 'outgoings_history.html', {'data': search_result})
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].

How do I redirect to url2 after performing a task on url1 in django?

I have a edit-scholarship.html in which you can search for a scholarship by passing name and type and then select that scholarship and edit it in update-scholarship.html by passing scholarship id from the url.
Now after updating the scholarship, the url becomes
http://127.0.0.1:8000/admin/updatescholarship/50
50 is the scholarship id passed into the url
Now when I try to go to dashboard in my project, the url becomes
http://127.0.0.1:8000/admin/updatescholarship/dashboard
I dont't want the dashboard to get appended after the updatescholarship . The url should be
http://127.0.0.1:8000/admin/dashboard
Here's my edit-scholarship view
def admin_editscholarship(request):
if request.method == 'POST':
name = request.POST['sch_name']
type = request.POST['sch_type']
schdets = ScholarshipDetails.objects.filter(name = name,type = type)
if schdets is not None:
#if something exists in scholarship details, then print it
print('Scholarship found')
else:
schdets = None
return render(request,'admin-editscholarship.html',{'schdets':schdets})
Here's my update-scholarship view
def admin_updatescholarship(request,pk=None):
#can update the new data in the selectd scholarship
if pk:
sch = ScholarshipDetails.objects.get(pk = pk)
if request.method == 'POST':
form = EditScholarshipForm(request.POST,instance=sch)
if form.is_valid():
form.save()
print('\nform saved')
args = {'form' : form}
messages.success(request,'Successfully updated')
return render(request,'admin-editscholarship.html',args)
Here's my urls.py
path('admin/dashboard',views.admin_dash),
path('admin/addscholarship',views.admin_addscholarship),
path('admin/editscholarship',views.admin_editscholarship),
url(r'^admin/updatescholarship/(?P<pk>\d+)$',views.admin_updatescholarship,name =
'updatescholarship'),
path('admin/students',views.admin_students),
path('admin/requests',views.admin_requests)
you can redirect to other url using django redirect
from django.shortcuts import redirect
def fn_test(request):
task here
return redirect('path_to_redirect/')

How to work with context in Django

I'm trying to create a confirmation page. User can create orders on one page, then the create_order view validates the forms and send a request with context to another view which is called confirm_order. I think that I would work correct but there is one problem. The first time confirm_order gets request and context which contains data from forms. But when User clicks on confirm in this page, the confirm_view is called without this context so I'm getting error:
> ValidationError at /create-job/ [u'ManagementForm data is missing or
> has been tampered with']
Do you guys know how to send the context second time?
Here are those two views:
def create_order(request):
LanguageLevelFormSet = formset_factory(LanguageLevelForm, extra=5, max_num=5)
language_level_formset = LanguageLevelFormSet(request.POST or None)
job_creation_form = JobCreationForm(request.POST or None, request.FILES or None)
context = {'job_creation_form': job_creation_form,
'formset': language_level_formset}
if request.method == 'POST':
if job_creation_form.is_valid() and language_level_formset.is_valid():
cleaned_data_job_creation_form = job_creation_form.cleaned_data
cleaned_data_language_level_formset = language_level_formset.cleaned_data
context = {
'cleaned_data_job_creation_form': cleaned_data_job_creation_form,
"cleaned_data_language_level_formset": cleaned_data_language_level_formset,
}
mutable = request.POST._mutable # I'm adding parameter 'review' to be able to differ between two different posts in confirm_order view
request.POST._mutable = True
request.POST['review'] = True
request.POST._mutable = mutable
return confirm_order(request, context)
else:
return render(request, 'auth/jobs/create-job.html', context=context)
return render(request, 'auth/jobs/create-job.html', context=context)
def confirm_order(request, context):
print context
cleaned_data_job_creation_form = context['cleaned_data_job_creation_form']
cleaned_data_language_level_formset = context['cleaned_data_language_level_formset']
print request.POST['review']
if request.method == 'POST' and request.POST['review'] == True:
file = cleaned_data_job_creation_form['file']
count = 5 #simplified multiple rows
jobs = []
for language_level_form in [d for d in cleaned_data_language_level_formset if d]:
language = language_level_form['language']
level = language_level_form['level']
d = {}
d['language_from'] = cleaned_data_job_creation_form['language_from'].name
d['language_to'] = language
d['number_of_characters'] = count
d['price_per_sign'] = 1
d['estimated_price'] = count * d['price_per_sign']
jobs.append(d)
table = CreatedOrdersTable(jobs)
context = {'table': table,
'cleaned_data_job_creation_form': cleaned_data_job_creation_form,
'cleaned_data_language_level_formset': cleaned_data_language_level_formset}
return render(request, 'auth/jobs/confirm-order.html', context=context)
else:
for language_level_form in [d for d in cleaned_data_language_level_formset if d]:
language = language_level_form['language']
level = language_level_form['level']
Job.objects.create(
customer=request.user,
text_to_translate=cleaned_data_job_creation_form['text_to_translate'],
file=cleaned_data_job_creation_form['file'],
short_description=cleaned_data_job_creation_form['short_description'],
notes=cleaned_data_job_creation_form['notes'],
language_from=cleaned_data_job_creation_form['language_from'],
language_to=language,
level=level,
)
return HttpResponseRedirect('/order-success')
You are returning a template render on your first view. So, the request doesn't end on your confirm_order view.
If you want, you can redirect to reverse('confirm_order') and add the data on session.
In your confirm_order view you will pop the data from session and continue with your flow.

Decimal value in form wont validate Django

Here's my form i am trying to user to pass two char fields and two coordinates so they can be turned into objects. I just figured out the validation on the char fields, but now the decimal fields wont work. Any suggestions?
from django import forms
class SubmitForm(forms.Form):
title = forms.CharField(max_length=100)
story = forms.CharField(max_length=3000)
lat = forms.DecimalField(max_digits=25, decimal_places=20)
lng = forms.DecimalField(max_digits=25, decimal_places=20)
def clean_title(self):
if len(self.cleaned_data['title']) < 4:
raise forms.ValidationError("Enter your full title")
# Always return the cleaned data
return self.cleaned_data['title']
def clean_story(self):
if len(self.cleaned_data['story']) < 4:
raise forms.ValidationError("Enter your full story")
# Always return the cleaned data
return self.cleaned_data['story']
def clean_lng(self):
if self.cleaned_data['lng'] == 0.0:
raise forms.ValidationError("Enter your full story")
return self.cleaned_data['lng']
def clean_lat(self):
if self.cleaned_data['lat'] == 0.0:
raise forms.ValidationError("Enter your full story")
# Always return the cleaned data
return self.cleaned_data['lat']
def clean(self):
cleaned_data = self.cleaned_data
return cleaned_data
Here's my view
def test(request):
ctxt = {}
if request.method == 'POST':
form = SubmitForm(request.POST) # A form bound to the POST data
if form.is_valid():
lat1 = form.cleaned_data['lat']
lng1 = form.cleaned_data['lng']
# title1 = form.cleaned_data['title']
titlepost = form.cleaned_data['title']
story1 = form.cleaned_data['story']
ctxt = {'titlehere':titlepost}
catid = "test1234"
cat = Category(category=catid)
cat.full_clean()
cat.save()
marker = Marker(lat=lat1, lng=lng1,category=cat, title=titlepost, story=story1)
marker.full_clean()
marker.save()
return render_to_response('home.html', ctxt, context_instance=RequestContext(request))
else:
return render_to_response('test.html', ctxt, context_instance=RequestContext(request))
else:
now = datetime.datetime.now()
form = SubmitForm()
latest_marks = Marker.objects.all().order_by('-submitted')[0:10]
ctxt = {
'marks':latest_marks,
'now':now.date(),
'form': form,
}
return render_to_response('test.html', ctxt, context_instance=RequestContext(request))
For some reason each time i send the form I get this error message
Not really sure what going on. Still pretty new to Django. Any help would be appreciated.
Edit: add in colons I was missing. Error still consists
You're missing some colons after your if statements in the clean methods of your form.
Did you consider using Modelforms ?
You can simplify your code just by using a modelform for Marker model (less code duplication, less code in general to create the model ...)
FYI:
You can send the min_length to CharField and get the len() validation for free :)
class SubmitForm(forms.Form):
title = forms.CharField(max_length=100, min_length=4)
For some reason each time i send the form I get this error message
I can't see the error!
But I tried this and it works ok.
import math
class MyForm(forms.Form):
title = forms.CharField(max_length=100, min_length=4)
story = forms.CharField(max_length=3000, min_length=4)
lat = forms.DecimalField(max_digits=25, decimal_places=20)
lng = forms.DecimalField(max_digits=25, decimal_places=20)
def clean_lat(self):
lat = self.cleaned_data['lat']
if math.ceil(float(lat)) <= 0:
raise forms.ValidationError("Enter your full story")
return self.cleaned_data['lat']
def clean_lng(self):
lng = self.cleaned_data['lng']
if math.ceil(float(lng)) <= 0:
raise forms.ValidationError("Enter your full story")
return self.cleaned_data['lng']

Categories

Resources