enter image description here
i just want to fetch the data from my website and record it to my django databae
this my views.py code :
def index(request):
feature1 = Feature.objects.all()
Appnt = Appointment.objects.all()
if request.method == 'GET':
Appnt.name = request.GET['name']
Appnt.email = request.GET['email']
Appnt.phone = request.GET['phone']
Appnt.Adate = request.GET['date']
Appnt.Dept = request.GET['department']
Appnt.Doc = request.GET['doctor']
Appnt.message = request.GET['message']
contaxt = {
'feature1' : feature1,
'Appointment' : Appnt
}
return render(request, 'index.html', contaxt)
If the parameters can be blank (not passed), use get:
def index(request):
feature1 = Feature.objects.all()
Appnt = Appointment.objects.all()
if request.method == 'GET':
Appnt.name = request.GET.get('name')
Appnt.email = request.GET.get('email')
Appnt.phone = request.GET.get('phone')
Appnt.Adate = request.GET.get('date')
Appnt.Dept = request.GET.get('department')
Appnt.Doc = request.GET.get('doctor')
Appnt.message = request.GET.get('message')
context = {
'feature1' : feature1,
'Appointment' : Appnt
}
return render(request, 'index.html', context)
If the parameters should not be blank, the problem is how the client makes the request.
Related
in my django project, I want the function that generates the returned result not to process the other request before it ends. How can I provide this?
views.py
def orderresult(request):
if request.method == 'POST':
username = request.POST["username"]
order = request.POST["order"]
doubleResult = ResultsFormView(order,username).resultview() # ====> Async await function
result = doubleResult[0]
boolresult = doubleResult[1]
context = {
"result" : result,
"boolresult" : boolresult
}
return render(request, 'npages/result.html', context=context)
I tried something like this but it doesn't work.
async def orderresult(request):
if request.method == 'POST':
username = request.POST["username"]
order = request.POST["order"]
doubleResult = await ResultsFormView(order,username).resultview() # ====> Async await function
result = doubleResult[0]
boolresult = doubleResult[1]
context = {
"result" : result,
"boolresult" : boolresult
}
return render(request, 'npages/result.html', context=context)
I'm working on a Django project where I want to use ajax jquery to complete my search in my search form.
Tried everything, but it does not seem to work.
Pls, where have I missed it?
used this tutorial
views.py
import json
def search(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
query = form.cleaned_data['query']
catid = form.cleaned_data['catid']
if catid == 0:
products = Product.objects.filter(name__icontains=query)
else:
products = Product.objects.filter(name__icontains=query, category_id=catid)
category = Category.objects.all()
context = {
'products': products,
'category': category,
'query': query,
}
return render(request, 'shop/product/search.html', context)
return HttpResponseRedirect('/')
def search_auto(request):
if request.is_ajax():
q = request.GET.get('term', '')
products = Product.objects.filter(name__icontains=q)
results = []
for pl in products:
product_json = {}
product_json = pl.name
results.append(product_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
<script>
$(function() {$("#query").autocomplete({
url: "{% url 'shop:search_auto' %}",
select: function (event, ui) {AutoCompleteSelectHandler(event, ui)},
minLength: 2,
});
});
function AutoCompleteSelectHandler(event, ui)
{var selectedObj = ui.item;}
</script>
path('search', views.search_auto, name='search_auto'),
Thanks.
i was trying to make my first e-commerce website using django and i received this error.
I already search in google but I can't find how to fix it. please help me to find the error.
this is attached. If any data is missing please comment.
cart.js :
var updateBtns = document.getElementsByClassName('update-cart')
for (var i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function () {
var productId = this.dataset.product`enter code here`
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
if (user == 'AnonymousUser') {
console.log('Not logged in')
} else {
updateUserOrder(productId)
}
})
}
function updateUserOrder(productId, action) {
console.log('User is logged in, sending data...')
var url = '/update_item/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({ 'productId': productId, 'action': action })
})
.then(response => response.json())
.then((data) => {
console.log('data:', data);
}
);
}
views.py :
from django.shortcuts import render
from django.http import JsonResponse
from django.http import HttpRequest
import json
from .models import *
def store(request):
products = Product.objects.all()
context = {'products': products}
return render(request, 'store/store.html', context)
def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(
customer=customer, complete=False)
items = order.orderitem_set.all()
else:
# Create empty cart for now for non-logged in user
items = []
order = {'get_cart_total': 0, 'get_cart_items': 0}
context = {'items': items, 'order': order}
return render(request, 'store/cart.html', context)
def checkout(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(
customer=customer, complete=False)
items = order.orderitem_set.all()
else:
# Create empty cart for now for non-logged in user
items = []
order = {'get_cart_total': 0, 'get_cart_items': 0}
context = {'items': items, 'order': order}
return render(request, 'store/checkout.html', context)
def updateItem(request):
data = json.loads(request.data)
productId = data['productId']
action = data['action']
print('Action:', action)
print('productId:', productId)
return JsonResponse('Item was added', safe=False)'''
def updateItem(request):
data = json.loads(request.data)
request.data is available in Django rest framework, but it doesn't exist in regular Django views.
Change the view to use request.body instead.
def updateItem(request):
data = json.loads(request.body)
I have a view with model form, the ModelForm doesn't really contain all fields in the model. other fields I've used the methods of form.field = value before form.save(), but all of this fields being saved as default. none take the value am trying to give. here are the code :
def PostAd(request):
ad_post_form = AdPostForm()
if request.user.is_authenticated:
obj = Account.objects.get(user=request.user)
if request.method == "POST":
ad_post_form = AdPostForm(request.POST, request.FILES)
if ad_post_form.is_valid():
ad_post_form.created_by = request.user
if obj.role == 'admin':
ad_post_form.is_active = True
ad_post_form.save()
return redirect('home')
else:
ad_post_form = AdPostForm(request.POST, request.FILES)
else:
if request.method == "POST":
ad_post_form = AdPostForm(request.POST, request.FILES)
if ad_post_form.is_valid():
otp_number = random.randint(100000, 999999)
ad_post_form.otp = otp_number
ad_post_form.is_activated = False
ad_post_form.save()
current_id = ad_post_form.id
current_contact_email = request.POST.get('contact_email')
email_url_active = str(settings.URL_LOCAL) + 'new_ad/adidnumberis' + str(
current_id) + '/needactivate/activate/' + str(otp_number) + '/'
email_msg = "Please Confirm adding the Ad to Jehlum. Click link " + email_url_active
email = EmailMessage('Active Email', email_msg, to=[current_contact_email])
email.send()
return redirect('home')
else:
ad_post_form = AdPostForm()
context = {
'ad_post_form': ad_post_form,
}
return render(request, 'pages/post-ad.html', context)
the problem is ad_post_form.is_active = True is being saved as False(default)
also ad_post_form.otp = otp_number is being saved as 0 (default) and i need to give the spicific values i assigned here .
You need to get the model instance and set the attributes there. You so this by calling save with commit=False.
if ad_post_form.is_valid():
ad_post = ad_post_form.save(commit=False)
ad_post.created_by = request.user
...
ad_post.save()
Here is my code:
def render_new_article(request):
if request.method == "POST":
step_number = int(request.POST.get("step_number", ""))
new_article = request.session['new_article']
if 'prev' in request.POST:
step_number = step_number - 1
elif 'next' in request.POST:
if step_number == 0:
print type(new_article.steps)
new_article.title = request.POST.get("title", "")
new_article.description = request.POST.get(
"description", "")
else:
print type(new_article.steps)
new_article.steps[int(step_number)] = request.POST.get(
"step_description", "")
request.session['new_article'] = new_article
step_number = step_number + 1
elif 'publish' in request.POST:
new_article.draft = False
draft_article = Article.objects.filter(
parent_id=new_article.pk).exclude(parent_id=None)[:1]
if len(draft_article) > 0:
draft_article[0].delete()
new_article.full_clean()
new_article.save()
del request.session['new_article']
return HttpResponseRedirect("/article?articleid=" + str(new_article.pk))
c = RequestContext(request, {
'user': request.user, 'step_number': step_number,
'article': new_article,
})
return render_to_response("new_article.html", c)
else:
# This function renders the home.
article_id = request.GET.get('article_id', '')
user = User.objects.get(id=request.user.pk)
app_user = AppUser.objects.get(user=user)
new_article = Article(created_by=app_user, steps={}, id=None,
draft=True, parent_id=None, pk=None)
if article_id.strip() != '':
new_article = Article.objects.get(pk=article_id)
new_article.steps = ast.literal_eval(new_article.steps)
print "getting article from DB"
request.session['new_article'] = new_article
c = RequestContext(request, {
'user': request.user, 'step_number': 0,
'article': new_article,
})
return render_to_response("new_article.html", c)
This gives me an error whenever I try to run it on Openshift, but it works fine locally. I have checked the Django Version and Python Version also.