I am trying to send email based on the form boolean value.
If the Trigger_Email is True then send the mail
Below is the models.py
class New_Shipment(models.Model):
Status_CHOICES = (
("1", "Open"),
("2", "Close"),
)
alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.')
Courier_or_Freight_details = models.CharField(max_length=200, validators=[alphanumeric])
Quantity = models.IntegerField()
Action_On = models.CharField(max_length=200, validators=[alphanumeric])
Status = models.CharField(max_length=300, validators=[alphanumeric], choices=Status_CHOICES)
Trigger_Email = models.BooleanField(default=False)
Below is my views.py
def my_form1(request, new_shipment=New_Shipment):
if request.method == "POST":
form1 = MyForm1(request.POST)
if form1.is_valid():
new_shipment = get_object_or_404(New_Shipment)
elif new_shipment.Trigger_Email:
subject = "New Shipment Details"
message = "Hello \n New Shipment details added to the EPC\n\n Regards,\nIsmail"
from_email = settings.EMAIL_HOST_USER
to_list = ['toemail#gmail.com']
send_mail(subject, message, from_email, to_list, fail_silently=True)
form1.save()
return HttpResponse('Submitted successfully')
# return redirect('/home_page/')
else:
form1 = MyForm1()
return render(request, "authentication/New_shipment.html", {'form1': form1})
url.py
from django.conf.urls import url
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('signup', views.signup, name="signup"),
path('activate/<uidb64>/<token>', views.activate, name='activate'),
path('signin', views.signin, name="signin"),
path('Monthly_Shipment', views.Monthly_Shipment, name="Monthly_Shipment"),
path('signout', views.signout, name="signout"),
path('home_page', views.home_page, name="home_page"),
url(r'form1', views.my_form1, name='form1'),
path('View_New_shipment', views.View_New_shipment, name="View_New_shipment"),
]
Any Kind of help will be appreciated. Thanks in advance
Change elif to if inside form1.is_valid() condition.
Instead:
if form1.is_valid():
new_shipment = get_object_or_404(New_Shipment)
elif new_shipment.Trigger_Email:
subject = "New Shipment Details"
...
Do this:
if form1.is_valid():
new_shipment = get_object_or_404(New_Shipment)
if new_shipment.Trigger_Email:
subject = "New Shipment Details"
...
Related
I'm using django-formtools to create a multi-step form wizard. I want to use data entered in the first step to call an API, then use the response data in the next step as a ChoiceField. This is what my code currently looks like:
views.py
from server.companies.models import Company
from server.data_sources.models import DataDictionary, DataSource
from django.shortcuts import render
from formtools.wizard.views import SessionWizardView
import json
import logging
from server.data_sources import ds
from server.data_sources.models import SOURCE
logger = logging.getLogger("server." + __name__)
def create_records(data):
if not data or data == {}:
return
name = data.get("company_name")
is_sandbox = data.get("is_sandbox")
city = data.get("city")
state = data.get("state")
username = data.get("username")
password = data.get("password")
data_source = DataSource.objects.create(
name=name,
source_type=SOURCE,
)
ds.login(data_source, username, password)
company = Company.objects.create(
name=name,
data_source=data_source,
)
return company
class Wizard(SessionWizardView):
template_name = "wizard.html"
def done(self, form_list, **kwargs):
return render(
self.request,
"done.html",
{"form_data": [form.cleaned_data for form in form_list]},
)
def get_form_step_data(self, form):
return form.data
def get_form(self, step=None, data=None, files=None):
form = super().get_form(step, data, files)
company = None
# determine the step if not given
if step is None:
step = self.steps.current
if step == "0":
if form.is_valid():
step_zero_data = form.cleaned_data
company = create_records(step_zero_data)
source = company.data_source
data_dict = {}
for field in ds.select(
company, "DATADICT", ["dd_dbf", "dd_name", "dd_desc"]
):
table = field["dd_dbf"]
field_name = field["dd_name"]
try:
data_dict[table] += [field_name]
except KeyError:
data_dict[table] = {}
data_dict[table] = []
data_dict[table] += [field_name]
# Find the existing data dictionary stored
data_dict_json = json.dumps(data_dict, indent=4)
existing_data_dict = DataDictionary.objects.filter(
data_source=source
).first()
if existing_data_dict:
existing_data_dict.data = data_dict_json
existing_data_dict.save()
else:
DataDictionary.objects.create(
data_source=source, data=data_dict_json
)
if step == "1":
pass
return form
urls.py
from django.conf.urls import url
from .forms import CustomerAccountCreationForm, CustomerWORequiredFieldsForm
from .views import ContactWizard
customer_creation_wizards_forms = [
CustomerAccountCreationForm,
CustomerWORequiredFieldsForm,
]
urlpatterns = [
url(
r"^customers/",
ContactWizard.as_view(
customer_creation_wizards_forms,
),
),
]
forms.py
So this is where I want to have the dynamic choice field. I'd like to use the data in my view (the data_dict) to populate those choices. Does anyone have any ideas on how to achieve this?
from django import forms
class CustomerAccountCreationForm(forms.Form):
company_name = forms.CharField(max_length=100, label="Company Name")
city = forms.CharField(max_length=100, label="Company City")
state = forms.CharField(max_length=100, label="Company State")
class CustomerWORequiredFieldsForm(forms.Form):
DYNAMIC_CHOICES = (
("1", "1"),
("2", "2"),
("3", "3"),
)
company_level_login = forms.BooleanField(
required=False, label="Company Level Login?"
)
is_closed_on_completion = forms.BooleanField(
required=False, label="Close WOs on completion?"
)
field_mapping = forms.CharField(max_length=100, label="Field Mapping")
I have requirement to build a crm . In that i have 3 things 1 is super user who is there by default.
Second organization in which I use a foreign key of user because I don't want to create a custom user and re write a lot of things third agent who is user as foreign key and connected to an organization no I want to login as organization in the dashboard if I am using the super user as login credential it is telling me required organization instance if I am login using organization account it is giving error NoReverseMatch at /leads/login_handle
Here is my views.py
login and sign up handle code
def signup_handle(request):
if request.method == "POST":
name = request.POST.get('name')
email = request.POST.get('email')
pass1 = request.POST.get('pass')
pass2 = request.POST.get('re_pass')
pass2 = request.POST.get('re_pass')
check = request.POST.get('agree-term')
if(pass1 != pass2):
return HttpResponse("Babe your passwod does not matches please try again")
else:
x = User.objects.create(email = email,username = email,first_name = name,is_staff = False)
# x = User.objects.create(name,email,pass1)
x.set_password(pass1)
x.save()
y = Organization(user = x,name = name)
y.save()
# print(f"lets verify the data name = {name},{check}")
return HttpResponse("Babe you have successfully created your account")
else:
return HttpResponse("Babe something goes wrong")
def login_handle(request):
if request.method == "POST":
username = request.POST.get('your_name')
password = request.POST.get('your_pass')
# username = email
# print(f"{username} and password is {password}")
user = authenticate(request,username=username,password=password)
if user is not None:
login(request, user)
return redirect('')
else:
return HttpResponse("Babe try again you are not authenticated")
else:
return HttpResponse("babe only post method applicable")
here is my complete models.py file
from ckeditor.fields import RichTextField
from django.db import models
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField
# Create your models here.
class Source(models.Model):
name = models.CharField(max_length=50,blank=True)
def __str__(self):
return self.name
class Followup(models.Model):
created_by = models.CharField(max_length=20,blank=True,null=True)
body = RichTextField(blank = True,null = True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now_add=True)
class Organization(models.Model):
name = models.CharField(max_length=50,blank=True)
user = models.ForeignKey(User,on_delete=models.PROTECT,blank=True)
def __str__(self):
return self.name
class Agent(models.Model):
name = models.CharField(max_length=20,blank=True)
user = models.ForeignKey(User,on_delete=models.PROTECT,blank=True)
image = models.ImageField(upload_to="Agents/images",blank = True)
organization = models.ForeignKey(Organization,on_delete=models.PROTECT,blank=True,default="")
def __str__(self):
return self.name
class Lead(models.Model):
status = (
("fresh","Fresh"),
("open","Open"),
("closed","Closed"),
("pending","Pending"),
)
closed_by = (
("low_budget","Low Budget"),
("we_cant_do","We Cant Do"),
("client","Client Converted"),
)
pending_by = (
("with_customer","With Customer"),
("with_process","With Process"),
("pending_on_us","Pending On Us"),
)
name = models.CharField(max_length=20,blank=True)
email = models.CharField(max_length=30,default="")
assign_to = models.CharField(max_length=30,default="")
mobile_no = models.IntegerField(blank=True)
subject = models.CharField(max_length=100,blank=True)
message = models.TextField(blank=True)
source = models.CharField(max_length=30,default="")
# source = models.ForeignKey(Source,blank=True,on_delete=models.PROTECT,null=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now_add=True)
state = models.CharField(choices=status,max_length=20,blank=True,default="fresh")
closed_by = models.CharField(max_length=15,choices=closed_by,blank=True)
pending_by = models.CharField(max_length=15,choices=pending_by,blank=True)
image=models.ImageField(upload_to="lead/images",blank = True)
def __str__(self):
return self.name
As the first answer says i added a path in redirect now it logged in but not rendering the page
def login_handle(request):
if request.method == "POST":
username = request.POST.get('your_name')
password = request.POST.get('your_pass')
# username = email
# print(f"{username} and pasword is {password}")
user = authenticate(request,username=username,password=password)
if user is not None:
login(request, user)
return redirect('/')
else:
return HttpResponse("Babe try again you are not authenticated")
else:
return HttpResponse("babe only post method applicable")
I am getting the error
Here is my app name home urls.py
urls.py
from django.contrib import admin
from django.urls import path
from home import views
urlpatterns = [
path('',views.index,name="index"),
# create agent
path('create_agent_page',views.create_agent_page,name="create_agent_page"),
path('create_agent',views.create_agent,name="create_agent"),
path('signup_page',views.signup_page,name="signup_page"),
path('login_page',views.login_page,name="login_page"),
path('signup_handle',views.signup_handle,name="signup_handle"),
path('login_handle',views.login_handle,name="login_handle"),
#Lead handleing
path('create_lead',views.create_lead_page,name="create_lead"),
path('follow_up/<int:id>',views.follow_up,name="follow_up"),
path('update_lead/<int:id>',views.update_lead,name="update_lead"),
# path('update_lead',views.update_lead,name="update_lead"),
path('creat_handle_lead',views.creat_handle_lead,name="creat_handle_lead"),
path('lead_list',views.lead_list,name="lead_list"),
]
here is my project urls.py
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
urlpatterns = [
path('admin/', admin.site.urls),
path('leads/', include('home.urls')),
]
return redirect('')
This is wrong. You must do
from django.urls import reverse
return HttpResponseRedirect(reverse('app_name:url_pattern_name'))
or you can specify your url pattern manually
from django.urls import reverse
return HttpResponseRedirect('/dashboard/')
My code is the follwing :
in views.py:
class ProjectDetailView(generic.DetailView):
model = project
template_name = 'project_details.html'
class ProjectCreate(CreateView):
model = project
fields = ['project_name']
template_name = 'project_form.html'
def create_invite(request):
if request.method == "POST":
invite_form = InviteForm(data=request.POST)
if invite_form.is_valid():
email1 = invite_form.cleaned_data['email1']
email2 = invite_form.cleaned_data['email2']
email3 = invite_form.cleaned_data['email3']
email4 = invite_form.cleaned_data['email4']
email5 = invite_form.cleaned_data['email5']
for i in invite_form.cleaned_data:
invite = Invitation.create(i)
invite.send_invitation(request)
print("The mail was went")
return reverse('website:ProjectDetails', kwargs = {'pk' : project.pk} )
else:
print("Your form is not valid")
else:
invite_form = InviteForm()
return render(request, 'team_invite.html', {'invite_form': invite_form})
in form.py:
from django import forms
class InviteForm(forms.Form):
email1 = forms.EmailField(label='Email 1')
email2 = forms.EmailField(label='Email 2')
email3 = forms.EmailField(label='Email 3')
email4 = forms.EmailField(label='Email 4')
email5 = forms.EmailField(label='Email 5')
urls.py:
from django.conf.urls import url
from website import views
app_name = 'website'
urlpatterns = [
url(r'^candidateIndex/$', views.CandidateIndex.as_view(), name='candidate_index'),
url(r'^HRcreate/$', views.ProjectCreate.as_view(), name='HR_create'),
url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'),
url(r'^project/add/$',views.ProjectCreate.as_view(), name='addproject'),
url(r'^invite/$',views.create_invite, name='addteam'),
]
Like you can see: I have a form that send email invites to user. Using that form I have two issues :
1) it seems that instead of taking the value in the input which is the email, it seems to take only the variable which is Email1 or Email2 ect..
2) when I try to redirect to the detail page using the project pk I get an error:
django.urls.exceptions.NoReverseMatch: Reverse for 'ProjectDetails' with keyword arguments '{'pk': <property object at 0x10ecf79a8>}' not found. 1 pattern(s) tried: ['website/project/(?P<pk>[0-9]+)/$']
Any ideas ?
I would like to fill my form field (url) and use that url as default value in my next form field (in another view). I am not able to switch views and take that form value. Any advices? Here are my files:
views.py
def subcategory(request, category_name_slug, subcategory_name_slug):
context = {}
form = SiteAddForm()
context['form'] = form
try:
category = Category.objects.get(slug=category_name_slug)
subcategory = SubCategory.objects.filter(category=category
).get(slug=subcategory_name_slug)
sites = Site.objects.filter(subcategory=subcategory)
context['subcategory'] = subcategory
context['sites'] = sites
except (SubCategory.DoesNotExist, Category.DoesNotExist):
raise Http404("Nie ma takiej strony")
if request.method == 'POST':
form = SiteAddForm(request.POST)
if form.is_valid():
siteurl = form.cleaned_data['url']
context['siteurl'] = siteurl
return render(request, 'mainapp/add_site.html', context)
return render(request, 'mainapp/subcategory.html', context)
def add_site(request, category_name_slug, subcategory_name_slug):
context = {}
forms = SiteAddFormA()
context['form'] = forms
return render(request, 'mainapp/add_site.html', context)
forms.py:
from django import forms
from mainapp.models import Site
class SiteAddForm(forms.Form):
url = forms.URLField(label='Url')
class SiteAddFormA(forms.ModelForm):
url = forms.URLField(max_length=200, help_text='Please enter the URL of the page.')
class Meta:
model = Site
fields = ('url', 'name', 'description',)
urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category,
name='category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/(?P<subcategory_name_slug>[\w\-]+)/$',
views.subcategory,
name='subcategory'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/(?P<subcategory_name_slug>[\w\-]+)/(?P<id>[\w\-]+)/$',
views.site,
name='site'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/(?P<subcategory_name_slug>[\w\-]+)/add_site/$',
views.add_site,
name='add_site'),
]
models.py:
class Site(models.Model):
category = models.ForeignKey('Category')
subcategory = ChainedForeignKey(
'Subcategory',
chained_field='category',
chained_model_field='category',
show_all=False,
auto_choose=True)
name = models.CharField(max_length=30)
description = models.TextField()
keywords = MyTextField()
date = models.DateTimeField(default=datetime.now)
url = models.URLField()
def __str__(self):
return self.name
I am having a hard time figuring out a way of doing multipart/formencoded image upload using django and tastypie. I went through all the possible answers on stackoverflow but cant seem to find a solution that would work. Also, i am a beginner in python so cant seem to understand a lot of stuff. I have written some code and would like someone to point me as to what am i doing wrong.
Models.py
import random
from django.db import models
from django.template.loader import get_template
from django.template import Context
import suuq.settings
from usermanagement import utils
from django.contrib.auth.models import UserManager
from django.db.models import ImageField
class adManager(models.Manager):
def create_ad(self, category, title, email, tag, location, address, description, phone, img):
if not category:
raise ValueError('add must have a category')
if not title:
raise ValueError('add must have a title')
if not email:
raise ValueError('ad must have a email')
if not tag:
raise ValueError('ad must have a tag')
if not location:
raise ValueError('ad must have a location')
if not address:
raise ValueError('ad must have a address')
if not description:
raise ValueError('ad must have a description')
if not phone:
raise ValueError('ad must have a phone number')
if not img:
raise ValueError('ad must have a image')
ad = self.create(category = category, title = title, email = UserManager.normalize_email(email).strip().lower(),
tag = tag, location = location, address = address, description = description, phone = phone, img=img)
ad.save()
return ad
class Ad(models.Model):
objects = adManager()
category = models.CharField(max_length=100)
title = models.CharField(max_length=200)
email = models.EmailField(
max_length=255,
unique=True,
)
tag = models.CharField(max_length=200)
location = models.CharField(max_length=50)
address = models.CharField(max_length=200)
description = models.CharField(max_length=140)
phone = models.CharField(max_length=10, null=True)
img = models.ImageField(upload_to="img", null=True, blank=True)
api.py
import json
from django.conf.urls import url
from django import forms
from tastypie.authentication import SessionAuthentication
from tastypie.authorization import Authorization
from tastypie.exceptions import Unauthorized
from tastypie.resources import ModelResource
from tastypie.throttle import CacheThrottle
from tastypie.utils import trailing_slash
from tastypie.validation import FormValidation
from django.db.models import FileField
from tastypie import http, fields
from PIL import Image
from ad.models import Ad
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)
class AdResource(ModelResource, MultipartResource):
img = fields.FileField(attribute="img", null=True, blank=True)
class Meta:
queryset = Ad.objects.all()
resource_name = 'ad'
fields = ['id', 'category', 'title','email','tag','location', 'address', 'description', 'phone', 'img']
allowed_methods = ['post','get','delete']
include_resource_uri = False
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/add%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('add_ad'), name="add_ad"),
]
def add_ad(self, request, **kwargs):
self.method_check(request, allowed=['post'])
data = json.loads(request.body)
category = data.get('category', '')
title = data.get('title', '')
email = data.get('email', '')
tag = data.get('tag', '')
location = data.get('location', '')
address = data.get('address', '')
description = data.get('description', '')
phone = data.get('phone', '')
if(request.method == 'POST'):
if "multipart/form-data" not in str(request.META['CONTENT_TYPE']):
return
else:
if('img' in request.FILES):
upload = request.FILES['img']
img = Image.open(upload)
return
else:
return
else:
return
ad = Ad.objects.create_ad(category=category, title=title, email=email, tag=tag,
location=location, address=address, description=description, phone=phone, img=img)
return self.create_response(request, {
'success': True,
'ad_id': ad.id,
'message': 'ad address successfully added'
})
I know my code is not indented properly but i have it properly indented on my dev end. Please help me fix my logic, i am really stuck.
I found the problem and here is my updated solution using multipart form data
class AdResource(ModelResource):
img = fields.FileField(attribute="img", null=True, blank=True)
class Meta:
queryset = Ad.objects.all()
resource_name = 'ad'
fields = ['id', 'category', 'title','email','tag','location', 'address', 'description', 'phone', 'img']
allowed_methods = ['post','get','delete']
include_resource_uri = False
always_return_data = True
limit = 0
authentication = SessionAuthentication()
authorization = AdAuthorization()
throttle = CacheThrottle(throttle_at=200)
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/add%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('add_ad'), name="add_ad"),
]
def add_ad(self, request, **kwargs):
self.is_authenticated(request)
self.method_check(request, allowed=['post'])
format = request.META.get('CONTENT_TYPE')
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
category = data.get('category', '')
title = data.get('title', '')
email = data.get('email', '')
tag = data.get('tag', '')
location = data.get('location', '')
address = data.get('address', '')
description = data.get('description', '')
phone = data.get('phone', '')
img = data.get('img','')
ad = Ad.objects.create_ad(user=request.user, category=category, title=title, email=email, tag=tag,
location=location, address=address, description=description, phone=phone, img=img)
return self.create_response(request, {
'success': True,
'message': 'Ad address successfully added',
'id': ad.id
})
else:
return self.create_response(request, {
'success': False,
'message': 'Invalid format'
})