Django attribute error. 'module' object has no attribute 'XYZ' - python

So this is in my urls.py
from django.conf.urls import patterns, include, url
from v1_1 import views
urlpatterns = patterns('',
url(r'', include('social_auth.urls')),
url(r'^$', views.fblogin), ### LINE1
url(r'^logged-in/$', 'v1_1.views.fb_loggedin'), ### LINE2
)
And it results in error because of LINE1. It (the same code) used to work some time back. If i change LINE1 to url(r'^$', 'v1_1.views.fblogin'), it works fine... i am unable to understand the problem :/
Here's my views.py
from django.http import HttpResponse
from django.template import RequestContext, Context, Template
from django.template.loader import get_template
from kb_db1.models import User
from django.core.exceptions import ObjectDoesNotExist
import datetime
def home(request):
t = get_template('profile.html')
c = get_user(1)
r = t.render(c)
return HttpResponse(r)
def fblogin(request):
t = get_template('login.html')
c = Context({'name':'Suneet' , 'STATIC_URL':'/stic' , })
r = t.render(c)
return HttpResponse(r)
def fb_loggedin(request):
t = get_template('profile.html')
user = request.user
c = get_user(user)
#c = Context({'user2':user , 'fb_app_id':'139460226147895', 'app_scope':'email', 'STATIC_URL':'/stic' , })
r = t.render(c)
return HttpResponse(r)
def notfound(request):
t = get_template('404.html')
c = Context({'name': 'Adrian', 'section.title': 'Suneet'})
r = t.render(c)
return HttpResponse(r)
def display_meta(request):
t = get_template('done.html')
c = get_user(2)
#return render(request, t, {'m_list': m_list})
r = t.render(c)
return HttpResponse(r)
def get_user(user):
id = user.id
try:
u_list = User.objects.get(id=id)
try:
u_list.profile = u_list.get_profile()
u_list.profile = prettify_user(u_list.profile)
except ObjectDoesNotExist:
u_list.profile = u_list
u_list.profile.cumulative_rating = '- '
c = Context({'u_list':u_list, 'user2':user, 'STATIC_URL':'/stic'})
except ObjectDoesNotExist:
print("Either the entry or blog doesn't exist.")
c = Context({ 'name': 'Error', 'user2':user, 'fb_app_id':'139460226147895', 'STATIC_URL':'/stic'})
return c
def prettify_user(user):
try:
confident_rating, confident_votes = calc_rating(user.cumulative_rating, user.cumulative_votes, 5.2, 5)
user.cumulative_rating = "%.0f" %(confident_rating*10) # 9.750 => 97.50 => 98 | 9.749 => 97.49 => 97.4
user.cumulative_votes = confident_votes
except ObjectDoesNotExist:
user = 'me'
return user
def calc_rating(rating, votes, fake_rating_val, fake_votes_no):
total_votes = votes+fake_votes_no
rating = (float(rating*votes) + fake_rating_val*fake_votes_no)/total_votes
return rating, total_votes
def chck_anon(user):
if not user.is_anonymous:
user.is_anonymous = True
return user

Related

Django same function data not showing after page render

I am creating university management system using django. I have created faculty(teacher) registration form. For that, in my views.py
def faculty_registration(request):
data = {}
form = FacultyRegisterForm()
activetab = 'list'
if request.method == 'POST':
activetab = 'add'
form = FacultyRegisterForm(request.POST)
if form.is_valid():
userdata = User()
if User.objects.filter(username=request.POST.get('email')).exists():
messages.error(request, f"This email already exists.")
return redirect('/faculty/faculty_registration')
else:
userdatafirst_name = request.POST.get("first_name")
userdata.username = request.POST.get('email')
userdata.email = request.POST.get('email')
try:
fac_ID = Faculty.objects.last().id
except:
fac_ID = 0
LastInsertId = fac_ID+1
print('after_id',LastInsertId)
password = User.objects.make_random_password()
faculty_pw = password+str(LastInsertId)
print("pass",faculty_pw)
userdata.password = make_password(faculty_pw)
print( "teacher_pasword",userdata.password)
userdata.save()
fac = Faculty()
fac.faculty_college_id = request.POST.get("faculty_college")
fac.faculty_programme_id = request.POST.get('faculty_programme')
fac.salutation = request.POST.get("salutation")
fac.first_name = request.POST.get("first_name")
fac.middle_name = request.POST.get("middle_name")
fac.last_name = request.POST.get("last_name")
fac.phone = request.POST.get("phone")
fac.email = request.POST.get("email")
fac.address = request.POST.get('address')
fac.department = request.POST.get('department')
fac.highest_qualification = request.POST.get("highest_qualification")
fac.years_of_experience = request.POST.get('years_of_experience')
fac.previous_institute = request.POST.get('previous_institute')
# fac.documents = request.POST.get("documents")
if 'documents' in request.FILES:
filename = request.FILES['documents']
if str(filename).lower().split('.')[-1] == 'pdf':
if int(len(request.FILES['documents'].read())) < (3 * 1024 * 1024):
fac.documents = request.FILES['documents']
else:
messages.warning(request, "please upload a pdf within 3 mb")
navshow = 'add'
return redirect('faculty_registration')
else:
messages.warning(request, "please upload a pdf")
navshow = 'add'
return redirect('faculty_registration')
fac.photo = request.FILES.get('photo', 'faculty_picture/def.png')
fac.created_by_id = request.user.id
fac.user_id = userdata.id
fac.save()
assign_role(userdata, 'teacher')
html_content = render_to_string("email_template.html",{'title':'Kindly Note your Mailid and Password For Login.','to_mail':fac.email,'to_password':faculty_pw})
text_content = strip_tags(html_content)
msg = EmailMessage(
'Welcome to University', #subject
text_content, #content
settings.EMAIL_HOST_USER, #from email
[fac.email], #reclist
)
msg.content_subtype = "html" # Main content is now text/html
msg.send()
# print("send_email",send_email)
messages.success(request, f"Lecturer has been added successfully")
return redirect('/faculty/faculty_registration')
else:
print("\ninvalid form\n")
else:
form = FacultyRegisterForm()
# fac_data = Faculty.objects.order_by('-id')
fac_data = Faculty.objects.order_by(Lower('first_name'))
data['form'] = form
data['faculties'] = fac_data
data['activetab'] = activetab
return render(request, 'faculty_register.html', data)
Also I have added searchbar button to search faculty name.
So I created following function:
def searchbar (request):
data = {}
find = request.GET['find']
res = Faculty.objects.filter(Q(first_name__icontains=find) | Q(middle_name__icontains=find)| Q(last_name__icontains=find))
activetab = 'list'
form = FacultyRegisterForm()
data['form'] = form
data['activetab'] = activetab
data['faculties'] = res
return render(request,"faculty_register.html",data)
I have also added 'add' functionality to add faculty.
Now my problem is when I click search button, I am not able to add faculty because I think i am rendering the same page 'faculty_register.html' in both return function. So how can I get same page data even after clicking 'search button'.
URLs:
urlpatterns = [
path('faculty_registration', views.faculty_registration, name='faculty_registration'),
path('faculty/searchbar', views.searchbar, name= 'searchbarf')]
I've tried to add searchbar function in faculty_registration but not able to solve this.

Django redirect not working in my view function

From my crop crop_prediction view I am trying to redirect it to 'http://localhost:8000/Efarma/crop_detail/' page but instead of this it render the current html page ,the home page which is also the starting page of this website.
Some error is showing in my console '[26/Apr/2022 22:31:29,457] - Broken pipe from ('127.0.0.1', 62868)' but I have no idea what is it.
To go to crop_detail page i have to manually put it in search box.
urls.py:-
from django.urls import path, include
from .import views
urlpatterns = [
path('', views.home),
path('crop_prediction/', views.crop_prediction),
path('crop_detail/', views.crop_info)
]
views.py:-
def home(request):
return render(request, 'Efarma/index.html')
def crop_prediction(request):
global resultJson, firebase
print(request.POST)
print(request.GET)
if request.method == "POST":
N = float(request.POST.get("nitrogen"))
P = float(request.POST.get("phosphorus"))
K = float(request.POST.get("potassium"))
ph = float(request.POST.get("ph"))
rainfall = float(request.POST.get("rainfall"))
city = request.POST.get("city")
if weather_fetch(city) != None:
temperature, humidity = weather_fetch(city)
data = np.array([[N, P, K, temperature, humidity, ph, rainfall]])
print(temperature, humidity, "--------kkk-------")
my_prediction = pickle.load(
open('CropRecommendation\model\model.pkl', 'rb'))
final_prediction = my_prediction.predict(data)
value = final_prediction[0]
firebase = firebase.FirebaseApplication(
'https://e-farma-5dc42-default-rtdb.firebaseio.com/')
predicted_crop_info = firebase.get(value, None)
predicted_crop_info["crop"] = value
resultJson = dumps(predicted_crop_info)
return redirect('http://localhost:8000/Efarma/crop_detail/')
else:
return redirect('http://localhost:8000/Efarma/crop_detail/')
def crop_info(request):
print(resultJson)
return render(request, "Efarma/crop_detail.html", {"result": resultJson})
error:-

In Django no other function getting called except one rest showing error 403

This is our code for url
from django.conf.urls import url,include
from django.urls import path,re_path
from . import views
app_name = 'challengeide'
urlpatterns = [
url('challengeide', views.qtn,name='test'),
url('challenge/', views.challengeide, name='challengeide'),
url('challenge/', views.dataentry, name='dataentry'),
#url('challengeide', views.dataentry,name='dataentry'),
url('challenge/challengeide/', views.send_challenge_request, name='send_challenge_request'),
]
this is code for views
from django.shortcuts import render
from django.http import JsonResponse, HttpResponseForbidden
import requests
from challengeide.models import Challenge_Detail
from challengeide.models import ChallengeDemo
import json
from django.utils.datastructures import MultiValueDictKeyError
from users.models import Profile
from django.shortcuts import redirect, get_object_or_404
from django.http.response import HttpResponseRedirect
from django.contrib.auth import get_user_model
def qtn(request):
try:
#print("If loop")
data = request.POST['opponent']
data1 = request.POST['qts']
opponent_row = Profile.objects.get(slug = data)
global to_id
to_id = opponent_row.user_id
print(data,data1)
global a
a = int(data1)
question_desc = Challenge_Detail.objects.get(id = a)
#print(a)
#dataentry(request)
return render(request,"challengeide.html",{'ChallengeDetails':question_desc})
except MultiValueDictKeyError :
#print("in else")
question_desc = Challenge_Detail.objects.get(id = a)
e1 = question_desc.expout
e2 = question_desc.expout2
e3 = question_desc.expout3
e4 = question_desc.expout4
e5 = question_desc.expout5
i1 = question_desc.expin
i2 = question_desc.expin2
i3 = question_desc.expin3
i4 = question_desc.expin4
i5 = question_desc.expin5
for i in range(1,6):
if (i==1):
if request.is_ajax():
source = request.POST['source']
lang = request.POST['lang']
data = {
'client_secret': '' ,
'async': 0,
'source': source,
'lang': lang,
'time_limit': 5,
'memory_limit': 262144,
}
x = str(i1)
i1 = x.replace("qwe","\n")
data['input'] = i1
'''
if 'input' in request.POST:
data['input'] = request.POST['input']'''
r = requests.post(RUN_URL, data=data)
temp =(r.json().copy())
print(temp)
print(data)
global out_returned
if(temp["run_status"]["status"]!="CE"):
out_returned = temp['run_status']["output"]
e = temp['compile_status']
print(e)
compare(out_returned,e1)
print(e1)
print(out_returned)
else:
error = (temp["compile_status"])
print(error)
ex = {"Problem" :error}
print(type(ex))
print(ex)
return JsonResponse(r.json(), safe=False))
else:
return HttpResponseForbidden()
def send_challenge_request(request):
print("dataintial")
user = get_object_or_404(User, id=to_id)
print(request.user)
print(user)
print("dataentry")
entry = ChallengeDemo(
from_id=request.user,
to_id=user,
score1 = 10.5,
score2 = 12.5,
qtn_id = 1
)
entry.save()
print("dataexit")
return render(request, 'challenge.html')
this is where we are calling the function send_challenge_request in html
<a
class="btn btn-primary mr-2"
href="{% url 'challengeide:send_challenge_request' %}"
>Submit</a
>
the function send_challenge_request is not getting called and error 403 Access to localhost was denied is been shown and this is the anchor tag which we using to call the function present in views.py.

No Reverse Match Found error in Django when using < > in URL

I'm having problems with my URL paths.
Whenever I remove -- path('<query>/follow', views.follow, name='follow') -- everything works fine. When I include it, the page with the link on it reveals 'Reverse for 'follow' with no arguments not found' though I can manually type the follow path into the URL and it succeeds. Why is this and how can I fix it?
html
Follow
urls.py
urlpatterns = [
path('', views.explore, name='explore'),
path('happening/profile/', views.profile, name='profile'),
path('happening/', views.happening, name='happening'),
path('home/', views.home, name='home'),
path('home/likes/', views.likes, name='likes'),
path('<query>/follow', views.follow, name='follow'),
path('<query>/', views.profpage, name='profpage'),
]
views.py
def profpage(request, query):
obj = User.objects.filter(username=query)
if not obj:
attempt = {'user':query}
return render(request, 'error.html', attempt)
try:
obj2 = reversed(get_list_or_404(Comments, user=query))
except:
obj2= {}
try:
obj3 = get_list_or_404(Comments, user=query)
except:
obj3 = {}
like_dict={}
for x in obj3:
likes = x.likes.all().count()
like_dict[int(x.id)] = int(likes)
img = UserProfile.objects.filter(user__username=query)
for x in obj:
obj = x
for x in img:
img=x
content = {'obj': obj,
'img':img,
'info':obj2,
'like_dict':like_dict,
'query':query,
}
return render(request, 'profpage.html', content)
def follow(request, query):
print("WORKING")
return HttpResponse(request)

How to render output of cartridge API's on custom HTML page?

I am working on a cartridge project. I have created custom html templates for better visual and now I want to render all data which is coming through cartridge's built in APIs on my custom html pages. For.ex. I have a product.html, on which I want to show all products stored in db (category wise).
Actually, I tried to explore url,
url("^shop/", include("cartridge.shop.urls")),
I am not getting that on which API or Function, this url is hitting.
urls.py file of shop app looks like this, I tested it, none of those url get called,
from __future__ import unicode_literals
from django.conf.urls import url
from mezzanine.conf import settings
from cartridge.shop import views
_slash = "/" if settings.APPEND_SLASH else ""
urlpatterns = [
url("^product/(?P<slug>.*)%s$" % _slash, views.product,
name="shop_product"),
url("^wishlist%s$" % _slash, views.wishlist, name="shop_wishlist"),
url("^cart%s$" % _slash, views.cart, name="shop_cart"),
url("^checkout%s$" % _slash, views.checkout_steps, name="shop_checkout"),
url("^checkout/complete%s$" % _slash, views.complete,
name="shop_complete"),
url("^invoice/(?P<order_id>\d+)%s$" % _slash, views.invoice,
name="shop_invoice"),
url("^invoice/(?P<order_id>\d+)/resend%s$" % _slash,
views.invoice_resend_email, name="shop_invoice_resend"),
]
These are cartridge's views for '/shop/product', '/shop/wishlist' and '/shop/cart'
from __future__ import unicode_literals
from future.builtins import int, str
from json import dumps
from django.contrib.auth.decorators import login_required
from django.contrib.messages import info
from django.core.urlresolvers import reverse
from django.db.models import Sum
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.template import RequestContext
from django.template.defaultfilters import slugify
from django.template.loader import get_template
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.views.decorators.cache import never_cache
from mezzanine.conf import settings
from mezzanine.utils.importing import import_dotted_path
from mezzanine.utils.views import set_cookie, paginate
from mezzanine.utils.urls import next_url
from cartridge.shop import checkout
from cartridge.shop.forms import (AddProductForm, CartItemFormSet,
DiscountForm, OrderForm)
from cartridge.shop.models import Product, ProductVariation, Order
from cartridge.shop.models import DiscountCode
from cartridge.shop.utils import recalculate_cart, sign
try:
from xhtml2pdf import pisa
except (ImportError, SyntaxError):
pisa = None
HAS_PDF = pisa is not None
# Set up checkout handlers.
handler = lambda s: import_dotted_path(s) if s else lambda *args: None
billship_handler = handler(settings.SHOP_HANDLER_BILLING_SHIPPING)
tax_handler = handler(settings.SHOP_HANDLER_TAX)
payment_handler = handler(settings.SHOP_HANDLER_PAYMENT)
order_handler = handler(settings.SHOP_HANDLER_ORDER)
def product(request, slug, template="shop/product.html",
form_class=AddProductForm, extra_context=None):
"""
Display a product - convert the product variations to JSON as well as
handling adding the product to either the cart or the wishlist.
"""
published_products = Product.objects.published(for_user=request.user)
product = get_object_or_404(published_products, slug=slug)
fields = [f.name for f in ProductVariation.option_fields()]
variations = product.variations.all()
variations_json = dumps([dict([(f, getattr(v, f))
for f in fields + ["sku", "image_id"]]) for v in variations])
to_cart = (request.method == "POST" and
request.POST.get("add_wishlist") is None)
initial_data = {}
if variations:
initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
initial_data["quantity"] = 1
add_product_form = form_class(request.POST or None, product=product,
initial=initial_data, to_cart=to_cart)
if request.method == "POST":
if add_product_form.is_valid():
if to_cart:
quantity = add_product_form.cleaned_data["quantity"]
request.cart.add_item(add_product_form.variation, quantity)
recalculate_cart(request)
info(request, _("Item added to cart"))
return redirect("shop_cart")
else:
skus = request.wishlist
sku = add_product_form.variation.sku
if sku not in skus:
skus.append(sku)
info(request, _("Item added to wishlist"))
response = redirect("shop_wishlist")
set_cookie(response, "wishlist", ",".join(skus))
return response
related = []
if settings.SHOP_USE_RELATED_PRODUCTS:
related = product.related_products.published(for_user=request.user)
context = {
"product": product,
"editable_obj": product,
"images": product.images.all(),
"variations": variations,
"variations_json": variations_json,
"has_available_variations": any([v.has_price() for v in variations]),
"related_products": related,
"add_product_form": add_product_form
}
context.update(extra_context or {})
templates = [u"shop/%s.html" % str(product.slug), template]
return TemplateResponse(request, templates, context)
#never_cache
def wishlist(request, template="shop/wishlist.html",
form_class=AddProductForm, extra_context=None):
"""
Display the wishlist and handle removing items from the wishlist and
adding them to the cart.
"""
if not settings.SHOP_USE_WISHLIST:
raise Http404
skus = request.wishlist
error = None
if request.method == "POST":
to_cart = request.POST.get("add_cart")
add_product_form = form_class(request.POST or None,
to_cart=to_cart)
if to_cart:
if add_product_form.is_valid():
request.cart.add_item(add_product_form.variation, 1)
recalculate_cart(request)
message = _("Item added to cart")
url = "shop_cart"
else:
error = list(add_product_form.errors.values())[0]
else:
message = _("Item removed from wishlist")
url = "shop_wishlist"
sku = request.POST.get("sku")
if sku in skus:
skus.remove(sku)
if not error:
info(request, message)
response = redirect(url)
set_cookie(response, "wishlist", ",".join(skus))
return response
# Remove skus from the cookie that no longer exist.
published_products = Product.objects.published(for_user=request.user)
f = {"product__in": published_products, "sku__in": skus}
wishlist = ProductVariation.objects.filter(**f).select_related("product")
wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku))
context = {"wishlist_items": wishlist, "error": error}
context.update(extra_context or {})
response = TemplateResponse(request, template, context)
if len(wishlist) < len(skus):
skus = [variation.sku for variation in wishlist]
set_cookie(response, "wishlist", ",".join(skus))
return response
#never_cache
def cart(request, template="shop/cart.html",
cart_formset_class=CartItemFormSet,
discount_form_class=DiscountForm,
extra_context=None):
"""
Display cart and handle removing items from the cart.
"""
cart_formset = cart_formset_class(instance=request.cart)
discount_form = discount_form_class(request, request.POST or None)
if request.method == "POST":
valid = True
if request.POST.get("update_cart"):
valid = request.cart.has_items()
if not valid:
# Session timed out.
info(request, _("Your cart has expired"))
else:
cart_formset = cart_formset_class(request.POST,
instance=request.cart)
valid = cart_formset.is_valid()
if valid:
cart_formset.save()
recalculate_cart(request)
info(request, _("Cart updated"))
else:
# Reset the cart formset so that the cart
# always indicates the correct quantities.
# The user is shown their invalid quantity
# via the error message, which we need to
# copy over to the new formset here.
errors = cart_formset._errors
cart_formset = cart_formset_class(instance=request.cart)
cart_formset._errors = errors
else:
valid = discount_form.is_valid()
if valid:
discount_form.set_discount()
# Potentially need to set shipping if a discount code
# was previously entered with free shipping, and then
# another was entered (replacing the old) without
# free shipping, *and* the user has already progressed
# to the final checkout step, which they'd go straight
# to when returning to checkout, bypassing billing and
# shipping details step where shipping is normally set.
recalculate_cart(request)
if valid:
return redirect("shop_cart")
context = {"cart_formset": cart_formset}
context.update(extra_context or {})
settings.use_editable()
if (settings.SHOP_DISCOUNT_FIELD_IN_CART and
DiscountCode.objects.active().exists()):
context["discount_form"] = discount_form
return TemplateResponse(request, template, context)
When you hit shop url, your application will try to use an empty url from your cartridge.shop.urls file. So basically when you would like to check which API / view is called, go to this file and look for something similar to this:
url(r'^$', 'your-view', name='your-view'),
ok after posting your second urls file you have following options:
you call:
/shop/wishlist/ - you are executing a view named wishlist
/shop/cart/ - you are executing a view named cart
/shop/checkout/complete/ - you are executing a view named complete
so just find your views.py file, and all those views are going to be there

Categories