I'm trying to add a Listing model for an eCommerce app to a Wishlist model, but I'm not quite sure where I'm going wrong.
I referenced this post in order to create a Wishlist model and link it to my User and Listing models via a Foreign key for each.
Wishlist post
urls.py
from django.urls import path
from . import views
app_name = "auctions"
urlpatterns = [
# Listing paths
path("", views.index, name="index"),
path("login/", views.login_view, name="login"),
path("logout/", views.logout_view, name="logout"),
path("register/", views.register, name="register"),
path("addlisting/", views.add_listing, name="add_listing"),
path("viewlisting/<int:listing_id>", views.view_listing, name="view_listing"),
# Watchlist paths
path("watchlist_add/<int:listing_id>", views.watchlist_add, name="watchlist_add"),
]
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from datetime import datetime
# Categories
categories = [
('misc', 'misc'),
('computers','computers'),
('toys','toys'),
('pets','pets'),
('beauty','beauty'),
('video games','video games'),
('food','food'),
('clothing','clothing'),
]
ACTIVE_CHOICES = [
('Yes', 'Yes'),
('No', 'No'),
]
class User(AbstractUser):
pass
class Listing(models.Model):
listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner")
listing_title = models.CharField(max_length=100)
listing_description = models.TextField(max_length=1200)
listing_img = models.URLField(null=True, blank=True, max_length=250)
created_on = models.DateTimeField(auto_now=True)
starting_price = models.DecimalField(decimal_places=2, max_digits=10, default=1.00)
# From above categories list
category = models.CharField(max_length=30, choices=categories, default='misc')
# From active or inactive list
active_flag = models.CharField(max_length=10, choices=ACTIVE_CHOICES, default="Yes", verbose_name="active listing")
class Meta:
ordering = ['-created_on']
def __str__(self):
return f"Name: {self.listing_title}, Price: ${self.starting_price}, Posted By: {self.listing_owner}"
class Watchlist(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
item = models.ForeignKey(Listing, on_delete=models.CASCADE, null=True)
def __str__(self):
return f"{self.item}"
views.py
#login_required
def view_listing(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
if request.method == "GET":
return render(request, "auctions/view_listing.html" , { "listing": listing})
else:
try:
form = ListingForm(request.POST, instance=listing)
form.save()
return redirect("auctions:index")
except ValueError:
return render(request, "auctions/view_listing.html", {"listing": listing, "form": form})
#login_required
def watchlist_add(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
obj, created = Watchlist.objects.get_or_create(user=request.user, item_id=listing_id)
return HttpResponseRedirect(reverse("auctions:index"))
view_listing.html
{% extends "auctions/layout.html" %} {% block body %}
<h1 class="display-3 text-center mb-5">{{ listing.listing_title }}</h1>
<div class="container d-flex">
<figure class="figure">
{% if listing.listing_img %}
<img src="{{ listing.listing_img }}" alt="{{ listing.listing_title }}" title="{{ listing.listing_title }}"> {% else %}
<img src="https://res.cloudinary.com/guez/image/upload/v1606759078/cs50_commerce_project/default_image.jpg" alt="default image" title="default image"> {% endif %}
<figcaption class="figure - caption">Listed By: {{ listing.listing_owner|capfirst }}</figcaption>
</figure>
<div class="container m-4">
<p class="display-4">${{ listing.starting_price }}</p>
<hr>
<p class="">Description: {{ listing.listing_description }}</p>
<p class="figure-caption">Category: {{ listing.category|capfirst }}</p>
<small></small>
</div>
<div class="container">
<form action="{% url 'auctions:watchlist_add' listing.pk %}" method="post">
{% csrf_token %}
<input type="hidden" value="{{ listing.pk }}" name="listing">
<input type="submit" value="Add To Watchlist" class="btn btn-outline-warning">
</form>
<!--Add To Watchlist-->
</div>
</div>
{% endblock %}
Before there are any items on my wishlist, I go to view_listing.html and hit the 'Add To Watchlist' button. I then get an AttributeError that reads "AttributeError: 'Listing' object has no attribute 'remove'". Here's the stack trace:
System check identified no issues (0 silenced).
December 07, 2020 - 00:08:42
Django version 3.1, using settings 'commerce.settings'
Starting development server at http://0.0.0.0:8080/
Quit the server with CONTROL-C.
[07/Dec/2020 00:08:44] "GET /admin/auctions/watchlist/2/delete/ HTTP/1.1" 200 5409
[07/Dec/2020 00:08:45] "POST /admin/auctions/watchlist/2/delete/ HTTP/1.1" 302 0
[07/Dec/2020 00:08:45] "GET /admin/auctions/watchlist/ HTTP/1.1" 200 5215
[07/Dec/2020 00:08:46] "GET /admin/jsi18n/ HTTP/1.1" 200 3187
[07/Dec/2020 00:08:48] "GET /admin/auctions/watchlist/ HTTP/1.1" 200 5215
[07/Dec/2020 00:08:48] "GET /admin/jsi18n/ HTTP/1.1" 200 3187
[07/Dec/2020 00:08:51] "GET /admin/auctions/watchlist/ HTTP/1.1" 200 5215
[07/Dec/2020 00:08:51] "GET /admin/jsi18n/ HTTP/1.1" 200 3187
[07/Dec/2020 00:09:01] "GET / HTTP/1.1" 200 3962
[07/Dec/2020 00:09:03] "GET /viewlisting/8 HTTP/1.1" 200 2350
Name: Sega Genesis, Price: $1.00, Posted By: guez already in cart.
Internal Server Error: /watchlist_add/8
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/ubuntu/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/.local/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/ubuntu/project2/commerce/auctions/views.py", line 108, in watchlist_add
obj.listings.remove(listing)
AttributeError: 'Listing' object has no attribute 'remove'
[07/Dec/2020 00:09:06] "POST /watchlist_add/8 HTTP/1.1" 500 73233
I want to add the item to Wishlist via the watchlist_add function and then pass that new Wishlist object to the view_listing function in order to determine whether the button should or should not exist in the view_listing.html template if the item is already in request.user 's Watchlist.
?
Your code seems having a logic problem. You get_or_create a WatchList object, and you test if that obj is in the WatchList or not. The obj will always be in your WatchList.objects.all(), because it was there before or you just created.
obj.listings.remove(listing)
According to [django doc about remove()][1], you should use it the following way:
obj.listing_set.remove(obj)
together, how about something like:
#login_required
def watchlist_add(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
already_existed = Watchlist.objects.get_or_create(user=request.user, item=listing).exists()
if already_existed:
# do something:
# return ...
else:
Watchlist.objects.create(user=request.user, item=listing)
# do something
# return ....
Or you can still use get_or_create...
#login_required
def watchlist_add(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
obj, created = Watchlist.objects.get_or_create(user=request.user, item_id=listing_id)
if created: # means it was a new one
# do something
# return ...
else:
# do something, maybe delete whatever button you want to delete,
# maybe return a variable like below
# and in template you have {% if delete_button %}
# delete_button = True
# return ....
[1]: https://docs.djangoproject.com/en/3.1/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove
Related
When I try to send messages to a temporary email address, it arrives there but does not go into the django database.
view.py
def about(req):
form = MessangeForm()
if req.method == "POST":
form = MessangeForm(req.POST)
if form.is_valid():
subject = form.cleaned_data.get('title')
body = form.cleaned_data.get('body')
try:
send_mail(subject, body, settings.EMAIL_HOST_USER, ["nakkosikni#gufum.com"], fail_silently=False)
form.save()
except Exception as err:
print(str(err))
return redirect('index')
return render(req, "about.html", {"form": form})
models.py
class Messange(models.Model):
title = models.CharField(verbose_name='Subject', max_length=250, null=True, blank=True )
body = models.TextField(verbose_name='Body')
def __str__(self):
return f'(self.body)'
forms.py
class MessangeForm(ModelForm):
class Meta:
model = Messange
fields = ["title", "body"]
widgets = {
"body": forms.Textarea(attrs={'class': 'form-control'}),
}
HTML Template
{% extends 'index.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h1>About</h1>
<!-- <p>{{ user.username }} </p> -->
<form method="POST" >
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-primary">Add Comment</button>
</form>
{% endblock %}
When I click on submit button I get this error.
[07/Dec/2022 22:19:08] "GET /about HTTP/1.1" 200 2437 ОШИБКА: неверный синтаксис для типа time: "иавипачич" LINE 1: ...service_messange" ("title", "body") VALUES ('сч', 'иавипачич... ^
[07/Dec/2022 22:19:26] "POST /about HTTP/1.1" 302 0 [07/Dec/2022 22:19:26] "GET / HTTP/1.1" 200 226
Translated:
[07/Dec/2022 22:19:08] "GET /about HTTP/1.1" 200 2437 ERROR: Invalid syntax for time type: "avipacich" LINE 1: ...service_messange" ("title", "body") VALUES ('sch', 'iawipacich... ^
I don't understand what needs to be changed there.
The DataError exception shown in the image is a django database exception. The cause of the error in this case was not due to any problems in the code shown, rather a change in the model before the database migrations were run. The body field of the class Mesange was changed from a date to a CharField, but the migrations were not run, leading to the error. The database was simply looking for a date and/or time, but was receiving a CharField.
The solution was simply to run
python manage.py makemigrations
python manage.py migrate
I try build gooogle login with flask login.
I find the thread here
Using Google OAuth2 with Flask
I was able to port the accepted answer to use Requests-OAuthlib instead of Rauth. As of this writing, the package's last commit was on June 2019 and was currently use by 30K+ repositories.
the init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import dir
from flask_mail import Mail
# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()
mail = Mail()
GOOGLE_LOGIN_CLIENT_ID = "mygoogle API id .apps.googleusercontent.com" #I am sure It is correct
GOOGLE_LOGIN_CLIENT_SECRET = "my_secret_key"
def create_app():
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret-key-goes-here'
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + str(dir.dir) + '/admin.sqlite'
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'ruaxe.sdafsafsafs'
app.config['MAIL_PASSWORD'] = 'uiykejafsaffiqklziccld'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['OAUTH_CREDENTIALS'] = {
'google': {
'id': GOOGLE_LOGIN_CLIENT_ID,
'secret': GOOGLE_LOGIN_CLIENT_SECRET
}
}
mail.init_app(app)
db.init_app(app)
with app.app_context():
db.create_all()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
from .models import User
#login_manager.user_loader
def load_user(user_id):
# since the user_id is just the primary key of our user table, use it in the query for the user
return User.query.get(int(user_id))
# blueprint for auth routes in our app
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
# blueprint for non-auth parts of app
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
Then i build the auth.py with login page
auth = Blueprint('auth', __name__)
#auth.route('/login', methods=['GET'])
def login():
if current_user is not None and current_user.is_authenticated:
return redirect(url_for('main.index'))
return render_template('login.html')
the user view page i build in main.py
from __future__ import print_function
from flask import Blueprint, render_template, request, redirect, flash, url_for, current_app
from flask_login import login_required, current_user,login_user
from project.function import cmsHaravan as hara, cmsCalendar as cal
from .function import config as cf, cmsContacts as ct
from datetime import datetime, timedelta, date
from .models import User, Order, Shop
from . import db, mail
from flask_mail import Message
import random
import string
from werkzeug.security import generate_password_hash
import json
from requests_oauthlib import OAuth2Session
from urllib.request import urlopen
main = Blueprint('main', __name__)
class OAuthSignIn(object):
providers = None
def __init__(self, provider_name):
self.provider_name = provider_name
credentials = current_app.config['OAUTH_CREDENTIALS'][provider_name]
self.consumer_id = credentials['id']
self.consumer_secret = credentials['secret']
def authorize(self):
pass
def callback(self):
pass
def get_callback_url(self):
return url_for('main.profile', provider=self.provider_name,
_external=True)
#classmethod
def get_provider(self, provider_name):
if self.providers is None:
self.providers={}
for provider_class in self.__subclasses__():
provider = provider_class()
self.providers[provider.provider_name] = provider
return self.providers[provider_name]
class GoogleSignIn(OAuthSignIn):
openid_url = "https://accounts.google.com/.well-known/openid-configuration"
def __init__(self):
super(GoogleSignIn, self).__init__("google")
self.openid_config = json.load(urlopen(self.openid_url))
self.session = OAuth2Session(
client_id=self.consumer_id,
redirect_uri=self.get_callback_url(),
scope=self.openid_config["scopes_supported"]
)
def authorize(self):
auth_url, _ = self.session.authorization_url(
self.openid_config["authorization_endpoint"])
print(auth_url)
return redirect(auth_url)
def callback(self):
if "code" not in request.args:
return None, None
self.session.fetch_token(
token_url=self.openid_config["token_endpoint"],
code=request.args["code"],
client_secret=self.consumer_secret,
)
me = self.session.get(self.openid_config["userinfo_endpoint"]).json()
print(me)
print(me["name"], me["email"])
return me["name"], me["email"]
#main.route('/authorize/<provider>')
def oauth_authorize(provider):
# Flask-Login function
if not current_user.is_anonymous:
return redirect(url_for('index'))
oauth = OAuthSignIn.get_provider(provider)
return oauth.authorize()
#main.route('/profile/<provider>')
def oauth_callback(provider):
if not current_user.is_anonymous:
return redirect(url_for('main.index'))
oauth = OAuthSignIn.get_provider(provider)
name, email = oauth.callback()
print("da lay duoc email", email)
if email is None:
# I need a valid email address for my user identification
flash('Authentication failed.')
return redirect(url_for('auth.login'))
# Look if the user already exists
user=User.query.filter_by(email=email).first()
if not user:
# Create the user. Try and use their name returned by Google,
# but if it is not set, split the email address at the #.
name = name
if name is None or name == "":
name = email.split('#')[0]
# We can do more work here to ensure a unique nickname, if you
# require that.
user=User(firstname=name, email=email)
db.session.add(user)
db.session.commit()
# Log in the user, by default remembering them for their next visit
# unless they log out.
login_user(user, remember=True)
return redirect(url_for('main.index'))
#main.route('/profile')
#login_required
def profile():
ListCarBrands = cal.getListCarBrands()
ListProvinces = cal.getListProvinces()
order_email = current_user.email
list_order = {}
i = 0
for row in Order.query.filter_by(order_email=order_email):
i = i + 1
total_order = i
list_order[i] = row.__dict__
return render_template('profile.html', list_order=list_order, name=current_user.lastname,
biensoxe=current_user.biensoxe,
ListCarBrands=ListCarBrands, brands=current_user.brands, carclass=current_user.carclass,
firstname=current_user.firstname, lastname=current_user.lastname, phone=current_user.phone,
email=current_user.email, ListProvinces=ListProvinces, provinces=current_user.provinces)
The login.html
{% extends "base.html" %}
{% block content %}
<div id="sign-in">
<h1>Sign In</h1>
<p>
<a href={{ url_for('main.oauth_authorize', provider='google') }}><img src="{{ url_for('static', filename='img/sign-in-with-google.png') }}" /></a>
</div>
<form method="POST" action="/login">
<div class="ui-information-body">
<div class="align-content-center">
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="notification is-danger">
{{ messages[0] }}
</div>
{% endif %}
{% endwith %}
<h4>Login {{ error }}</h4>
<div class="row">
<div class="col-5 "><label class="label-input-group">Email </label><input type="email"
class="next-input"
name="email" id="email"
value=""></div>
</div>
<div class="row">
<div class="col-5 "><label class="label-input-group">Password</label><input type="password"
class="next-input"
name="password"
id="password"
value=""></div>
</div>
<div class="row">
<div class="col-5 "><span class="label-input-group"><br></span>
<a href="{{ url_for('main.reset_password') }}" class="btn btn-danger btn-lg btn-block">
Nếu bạn quên mật khẩu? Reset
</a></div>
</div>
<div class="row">
<div class="col-5 "><span class="label-input-group"><br></span><input
class="btn btn-primary btn-lg btn-block" type="submit" value="Login"></div>
</div>
</div>
</div>
</div>
</form>
{% endblock %}
Profile html
{% extends "base.html" %}
{% block content %}
<form method="POST" action="/profile">
Some code here for user can update profile
</form>
</div>
{% endblock %}
Then i run program, i can get the link as the code in
def authorize(self):
auth_url, _ = self.session.authorization_url(
self.openid_config["authorization_endpoint"])
print(auth_url) ##### This function run
return redirect(auth_url)
https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=880298757050-ij79mostsm1fccdcvuj43m0oe0quisih.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fprofile%3Fprovider%3Dgoogle&scope=openid+email+profile&state=xwbrUEpMjhIFrM6l3PlXgcXdgzyDbd
127.0.0.1 - - [21/Aug/2020 14:03:32] "GET /authorize/google HTTP/1.1" 302 -
127.0.0.1 - - [21/Aug/2020 14:03:35] "GET /profile?provider=google&state=xwbrUEpMjhIFrM6l3PlXgcXdgzyDbd&code=4%2F3QFTG6I2FzBPUKD_Sk0hq4IUhlr0jA4EQ2fTLyQizyYsPkCLxRf_WXwQz929v4wUeJhN4IXWFWu7nLKBJ2NHhog&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&prompt=consent HTTP/1.1" 302 -
127.0.0.1 - - [21/Aug/2020 14:03:35] "GET /login?next=%2Fprofile%3Fprovider%3Dgoogle%26state%3DxwbrUEpMjhIFrM6l3PlXgcXdgzyDbd%26code%3D4%252F3QFTG6I2FzBPUKD_Sk0hq4IUhlr0jA4EQ2fTLyQizyYsPkCLxRf_WXwQz929v4wUeJhN4IXWFWu7nLKBJ2NHhog%26scope%3Demail%2Bprofile%2Bopenid%2Bhttps%253A%252F%252Fwww.googleapis.com%252Fauth%252Fuserinfo.email%2Bhttps%253A%252F%252Fwww.googleapis.com%252Fauth%252Fuserinfo.profile%26authuser%3D0%26prompt%3Dconsent HTTP/1.1" 200 -
127.0.0.1 - - [21/Aug/2020 14:03:35] "GET /static/img/sign-in-with-google.png HTTP/1.1" 404 -
127.0.0.1 - - [21/Aug/2020 14:03:35] "GET /static/css/bootstrap.js HTTP/1.1" 404 -
BUT I TRY TO PRINT EMAIL AS THE CODE in route profile
oauth = OAuthSignIn.get_provider(provider)
name, email = oauth.callback()
print("da lay duoc email", email)
Nothing come! So anyone can help me
Thanks to all
Thanks all
I change scope and it run!
class GoogleSignIn(OAuthSignIn):
openid_url = "https://accounts.google.com/.well-known/openid-configuration"
def __init__(self):
super(GoogleSignIn, self).__init__("google")
self.openid_config = json.load(urlopen(self.openid_url))
self.session = OAuth2Session(
client_id=self.consumer_id,
redirect_uri=self.get_callback_url(),
scope='https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/userinfo.email'
)
I have made a view that sends email through a template to an email address. I want to send the name of the user, who originally created the request but I am unable to wrap my head around it, because it's FK.
I've tried running it through a for loop and creating objects but that just prints the entirety of the data.
admin view
desired result
Views.py
def accept_leave(request): #accept email
all_item = Leave.objects.all()
context ={'all_item':all_item }
subject = "Leave Accepted"#email subject
email_from = "settings.EMAIL_HOST_USER" # email from
to_email = ['talhamurtaza#clickmail.info'] # email to
with open("C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/accept_email.txt", 'rb') as f:
msgbody = f.read()
msg = EmailMultiAlternatives(
subject=subject, body=msgbody, from_email=email_from,to=to_email)
html_template = get_template(
"C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/accept_email.html").render()
msg.attach_alternative(html_template, "text/html")
msg.send()
return render(request, 'projectfiles/email.html', context)
def reject_leave(request): #reject email
all_item = Employee.objects.all()
context = {'name': request.user}
subject = "Leave Rejected" # email subject
email_from = "settings.EMAIL_HOST_USER" # email from
to_email = ['talhamurtaza#clickmail.info'] # email to
with open(
"C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/reject_email.txt", 'rb') as f:
msgbody = f.read()
msg = EmailMultiAlternatives(
subject=subject, body=msgbody, from_email=email_from, to=to_email)
html_template = get_template(
"C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/reject_email.html").render()
msg.attach_alternative(html_template, "text/html")
msg.send()
return render(request, 'projectfiles/rejectemail.html',context)
models.py
class Employee(models.Model):
employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
employee_designation = models.CharField(max_length = 10)
employee_department = models.CharField(max_length = 35)
def __str__(self):
# return self.employee_department + " " + " " + str(self.employee_name.username) + " " + " " + " ID: " + str(self.pk)
return self.employee_name.username
class Meta:
verbose_name_plural = "Employee"
class Leave(models.Model):
#This class will connect the user with the leave types etc and other classes data
employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
leave_Type = models.CharField(max_length=25)
class Meta:
verbose_name_plural = "Leave"
def __str__(self):
return self.leave_Type + " by " + str(self.employee_leaves)
email.html
<title>Email Sent</title>
{% include 'projectfiles/base2.html' %}
<br>
<br>
<br>
<div class='container'>
<center>
<h3>Leave Accepted</h3>
<hr width="50%">
{{request.user}}
<br>
<br>
<h6>
Pending <strong> | | </strong> Home
</h6>
</center>
</div>
accept.html
{% include 'projectfiles/base2.html' %}
<h3>Application accepted</h3>
{{request.user}}
<h6>Have a good day</h6>
adminpage.html
<title>Admin Dashboard</title>
{% include 'projectfiles/base2.html' %}
{% block asd %}
{% endblock asd %}
<br><br>
<div class="container">
<center>{% if count %}
<h3>Pending: <font color='#1783FF'> "{{ count }}"</font></h3><hr width="40%" noshade>
{% else %}
<br><br> <h2>NO LEAVES</h2>
{% endif %}</center>
</div>
<br>
{% for obj in all_items%}
<center>
<div class="container">
<h3><b>Applicant:</b> {{obj.employee_leaves}}</h3>
<b>Leave Type:</b> {{obj.leave_Type}}<br>
<small>Leave ID: {{obj.id}}</small><br>
Accept <b>||</b> Reject
<hr width="50%"></center>
</div>
{% endfor %}
urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^(?i)Home/$', views.home, name='Home-Page'),
url(r'^(?i)request/', views.request_leave, name='Leave-Page'),
url(r'^(?i)user_dlt/', views.userdlt_page, name='userdlt-Page'),
url(r'^password/$', views.change_password, name='change_password'),
# ADMIN DASHBOARD PAGES
url(r'^(?i)showprofile/$', views.showusers, name='Users-Page'),
url(r'^(?i)leaves/$', views.leave_show, name='leave_show'),
url(r'^acceptemail/$', views.accept_leave, name='Accept-page'),
url(r'^rejectemail/$', views.reject_leave, name='Reject-page'),
#==================
#=========login,logout & User registration URLS=========
url(r'^(?i)login/$', auth_views.LoginView.as_view(template_name='projectfiles/login.html'), name='LoginPage'),
url(r'^(?i)logout/$', auth_views.LogoutView.as_view(template_name='projectfiles/logout.html'), name='LogoutPage'),
url(r'^(?i)registraion/$', views.reg_user, name='RegPage'),
url(r'^(?i)notifications/$', views.notifications, name='notifications-Page'),
#=========End=========
]
error
[22/May/2019 10:21:39] "GET /favicon.ico HTTP/1.1" 404 4170
[22/May/2019 10:21:46] "GET /admin HTTP/1.1" 301 0
[22/May/2019 10:21:46] "GET /admin/ HTTP/1.1" 200 6253
[22/May/2019 10:21:47] "GET /static/admin/css/base.css HTTP/1.1" 200 16066
[22/May/2019 10:21:47] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[22/May/2019 10:21:47] "GET /static/admin/css/dashboard.css HTTP/1.1" 200 412
[22/May/2019 10:21:47] "GET /static/admin/img/icon-addlink.svg HTTP/1.1" 200 331
[22/May/2019 10:21:47] "GET /static/admin/img/icon-changelink.svg HTTP/1.1" 200 380
[22/May/2019 10:21:47] "GET /static/admin/img/icon-deletelink.svg HTTP/1.1" 200 392
[22/May/2019 10:21:47] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
[22/May/2019 10:21:47] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[22/May/2019 10:21:47] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
[22/May/2019 10:21:52] "GET /home/ HTTP/1.1" 200 7492
[22/May/2019 10:21:52] "GET /static/css/styles.css HTTP/1.1" 200 304
[22/May/2019 10:21:52] "GET /static/js/file.js HTTP/1.1" 200 150
[22/May/2019 10:21:58] "GET /leaves/ HTTP/1.1" 200 2613
[22/May/2019 10:21:58] "GET /static/js/login.js HTTP/1.1" 200 293
[22/May/2019 10:22:05] "GET /acceptemail/4/ HTTP/1.1" 302 0
Not Found: /acceptemail/4/
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="/static/css/styles.css">
<style>
body {
background-color:
[22/May/2019 10:22:05] "GET /acceptemail/4/%0A%0A%0A%0A%0A%3C!doctype%20html%3E%0A%3Chtml%20lang=%22en%22%3E%0A%0A%3Chead%3E%0A%20%20%3C!--%20Required%20meta%20tags%20--%3E%0A%20%20%3Cmeta%20charset=%22utf-8%22%3E%0A%20%20%3Cmeta%20name=%22viewport%22%20content=%22width=device-width,%20initial-scale=1,%20shrink-to-fit=no%22%3E%0A%0A%20%20%3C!--%20Bootstrap%20CSS%20--%3E%0A%20%20%3Clink%20rel=%22stylesheet%22%20href=%22https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css%22%0A%20%20%20%20integrity=%22sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm%22%20crossorigin=%22anonymous%22%3E%0A%20%20%20%20%3Clink%20rel=%22stylesheet%22%20href=%22/static/css/styles.css%22%3E%0A%0A%0A%0A%0A%0A%20%20%20%20%3Cstyle%3E%0A%20%20%20%20%20%20body%20%7B%0A%20%20background-color: HTTP/1.1" 404 6369
new view
def accept_leave(request, id): # accept email
all_item = Leave.objects.get(id=id)
context ={'all_item': all_item}
subject = "Leave Accepted"#email subject
email_from = "settings.EMAIL_HOST_USER" # email from
to_email = ['talhamurtaza#clickmail.info'] # email to
with open("C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/accept_email.txt", 'rb') as f:
msgbody = f.read()
msg = EmailMultiAlternatives(
subject=subject, body=msgbody, from_email=email_from,to=to_email)
html_template = get_template(
"C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/accept_email.html").render()
msg.attach_alternative(html_template, "text/html")
msg.send()
html = render_to_string(
"projectfiles/email/accept_email.html", {'all_item': all_item})
return HttpResponseRedirect(html)
I want the requesting user's name and some other info such as what type of leave he chose to pass in the email template and be sent.
and can you please guide me as to what approach to take if I want the one object to move to a done status from its pending as shown in the adminpage.
enter image description here
There are a lot of issues with your code:
Your view accept_leave is not receiving the applicant's name. Your 'accept' button shouldn't be a link to accept_leave (a GET request), but you should create a form for each of the applicants and the 'accept' button should submit the form (as a POST request) with the applicant's id (or username, something unique) in the URL or as an input field. Check here to learn how to work with forms.
Alternatively, if you really want to use GET, and not use a form, change the URL of your accept_leave view to also have the applicant id (/acceptemail/(?P<id>[0-9]+)$) and pass the id to your url constructor in the template ({% url 'accept-page' id=obj.id %})
Once you have passed the applicant id to your view, you'll retrieve it with employee = Employee.objects.get(id=...) and you can use that object to fill in what you need to send the email (but also to create the Leave object for that employee).
You want to render your templates with Django's template rendering engine, so you can pass context variables to your template (e.g. employee) and use them in your email templates (e.g. {{ employee.name }}). You can do that with render_to_string, e.g.:
html = render_to_string("projectfiles/email/accept_email.html", {'employee': employee})
text = render_to_string("projectfiles/email/accept_email.txt", {'employee': employee})
to then use html and text to send the email.
Before, you guys give me that "use the search tools" kind of speech. Yeah, I already did it, and to no avail. Anyways, I have been scratching my head for the last two days trying to figure out why I keep getting this error" Reverse for 'post_share' with arguments '('',)' not found. 2 pattern(s) tried: ['blog\/(?P[0-9]+)\/share\/$', 'blog\/post_share\/$']"
I am using Django 2 and I am reading the book Code for Django by Example book by Antonio Mele.
Forms.py
class EmailPostForm(forms.Form):
name = forms.CharField(max_length = 30)
email = forms.EmailField()
to = forms.EmailField()
comments = forms.CharField(required = False, widget = forms.Textarea)
Views.py
def post_share(request, post_id):
post = get_object_or_404(Post, id = post_id, status = 'published')
sent = False
if request.method == 'POST':
form = EmailPostForm(request, POST)
if form.is_valid():
cd = form.cleaned_data
post_url = request.build_absolute_uri(post.get_absolute_url())
subject = '{} ({}) recommends you reading "{}"'.format(cd['name'], cd['email'], post.title)
message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])
send_mail(subject, message, 'sample#gmail.com', [cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blogg/shared.html', {
'post': post,
'form': form,
'sent':sent
})
urls.py
app_name = 'blog'
urlpatterns = [
path('post_list', views.post_list, name = 'post_list'),
path('post_detail/<int:year>/<int:month>/<int:day>/<str:post>', views.post_detail, name = 'post_detail'),
path('post_share/', views.post_share, name = 'post_share'),
# re_path(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'),
path('<int:post_id>/share/', views.post_share, name='post_share'),
]
details
{% extends 'blogg/base.html'%}
{% block title %} {{ post.title }} {% endblock %}
{% block content %}
<h1> {{ post.title }}</h1>
<p>Published {{ post.publish }} by {{ post.author }}</p>
{{ post.body|linebreaks }}
<p>
Share Post
</p>
{% endblock %}
Error
NoReverseMatch at /blog/post_detail/2018/04/24/simple-test
Reverse for 'post_share' with arguments '('',)' not found. 2 pattern(s) tried: ['blog\\/(?P<post_id>[0-9]+)\\/share\\/$', 'blog\\/post_share\\/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/post_detail/2018/04/24/simple-test
Django Version: 2.0.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'post_share' with arguments '('',)' not found. 2 pattern(s) tried: ['blog\\/(?P<post_id>[0-9]+)\\/share\\/$', 'blog\\/post_share\\/$']
Exception Location: C:\Dev\blog\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632
Python Executable: C:\Dev\blog\Scripts\python.exe
Python Version: 3.6.4
Python Path:
['C:\\Dev\\blog\\src\\mysite',
'C:\\Dev\\blog\\Scripts\\python36.zip',
'C:\\Dev\\blog\\DLLs',
'C:\\Dev\\blog\\lib',
'C:\\Dev\\blog\\Scripts',
'c:\\program files (x86)\\python36-32\\Lib',
'c:\\program files (x86)\\python36-32\\DLLs',
'C:\\Dev\\blog',
'C:\\Dev\\blog\\lib\\site-packages']
Server time: Tue, 24 Apr 2018 12:40:59 +0000`
Try declaring the to and name variables at the start of the function like this..
def post_share(request, post_id):
post = get_object_or_404(Post, status='published', id=post_id)
sent = False
to = ""
name = ""
...........
I'm trying to make a Django application, but I have an Issue that template doesn't pass it's content to view.
this is my form..
<form action="{% url 'view-job' %}" method="post" enctype=application/x-www-form-urlencoded>
{% csrf_token %}
<div>
<label for="name">Job name: </label>
<input type="text" id="name" />
</div>
<div>
<label for="owner">Owner: </label>
<input type="text" id="owner" />
</div>
...
and this is my post handling view (views_job.py)
def job(request, pk=None):
if request.method == 'GET':
return get(request, pk)
elif request.method == 'POST':
return post(request)
...
and post(request)
def post(request):
#data = json.loads(request.body.decode("utf-8"))
#data = load_json(request)
new_job = create_new_job(request)
#new_job = create_new_job(request)
if new_job != False:
return new_job
else:
return HttpResponse(status=500)
create_new_job(req)
def create_new_job(req):
config = parse_config()
try:
queryset = Job.objects.create(
name=req.POST.get('name'),
owner=req.POST.get('owner'),
execute_date=req.POST.get('execute_date'),
created_date=timezone.now(),
master=req.POST.get('master') if 'master' in req.POST != None else config[DEFAULT][MASTER],
deploy_mode=req.POST.get('deploy_mode') if 'deploy_mode' in req.POST != None else config[DEFAULT][DEPLOY_MODE],
conf=req.POST.get('conf'),
classpath=req.POST.get('classpath'),
app_arguments=req.POST.get('app_arguments'),
user_params=req.POST.get('user_params'),
status=READY,
)
#queryset.save()
except:
print("Error")
print(req.POST.get('name'))
return False
return render(req, 'jobUI/job_details.html',
{
#'job':queryset
}
)
The console prints
INFO 2018-03-21 18:48:29,033 basehttp 1321 140106696156928 "GET /jobUI/job/ HTTP/1.1" 200 1799
INFO 2018-03-21 18:48:30,208 basehttp 1321 140106696156928 "GET /jobUI/job/newjob/ HTTP/1.1" 200 1620
Error
None
ERROR 2018-03-21 18:48:47,499 basehttp 1321 140106696156928 "POST /jobUI/job/ HTTP/1.1" 500 0
I don't know why request.POST['name'] is None and other things too..
How can I fix it?
thank you.
Because your input fields don't have a name attribute; without that the browser won't send any data.
Note, you should really be using the Django forms framework for this. And you certainly absolutely shouldn't have a blank except clause.