def index(request): form = ContactForm(request.POST or None) data = {} if request.is_ajax(): if form.is_valid(): form.save() data['name'] = form.cleaned_data.get('name') data['status'] = 'ok' return JsonResponse(data) def get_ip(request): address = request.META.get('HTTP_X_FORWARDED_FOR') if address: ip = address.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip ip = get_ip(request) u = User(user=ip) print(ip) result = User.objects.filter(Q(user__icontains=ip)) if len(result) == 1: print('user exits') elif len(result) > 1: print('users exists') else: u.save() print('This is a new user') count = User.objects.all().count() print('total visitors', count) context = {'form': form, 'count': count} return render(request, 'main/index.html', context)
def edit_contact(request): """ Edit contact """ #Get contact try: contact = Contact.objects.get(pk=1) except Contact.DoesNotExist: return HttpResponseRedirect('/') #Handle request if request.method == 'POST': form = ContactForm(request.POST, instance=contact) if form.is_valid(): try: form.save() form.result = True form.message = ugettext(u'Contact updated successfully') except DatabaseError: form.result = False form.message = ugettext(u'Contact save error. Try again.') else: form.result = False form.message = ugettext(u"Correct errors, please") if request.is_ajax(): response = {'message': form.message} if not form.result: response['result'] = 'error' response['errors'] = form.errors else: response['result'] = 'ok' return HttpResponse(dumps(response)) else: form = ContactForm(instance=contact) form.message = '' return {'contact_form': form}
def contact(request): contact_form = ContactForm(prefix='contact') if contact_form.is_valid(): contact_form.save() return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_403_FORBIDDEN)
def contact(request): if request.is_ajax(): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): name = request.POST.get("name", "") subject = "Contact from {0}".format(name) from_email = request.POST.get("email", "") body = """ Name: {0} Phone Number: {1} E-mail: {2} Message: \n {3}""".format( name, request.POST.get("phone", ""), from_email, request.POST.get("message", "") ) try: send_mail(subject, body, from_email, ["*****@*****.**"]) message = "FORM IS VALID" except BadHeaderError: message = "Invalid Header Found" form.save() else: message = "Form is INVALID" else: raise Http404 return HttpResponse(message) else: raise Http404
def contact(request): form = ContactForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) name = instance.name email = instance.email message = instance.message EmailMessage( 'New message from %s' % name, 'Hi admin, new message form this email address: %s\n\n Message: %s' % (email, message), conf_settings.EMAIL_HOST_USER, [ '*****@*****.**', ], ).send() form.save() messages.success(request, 'Your message has been sent!') return redirect('contact') context = {'form': form} return render(request, 'main/contact.html', context)
def post(self, *args, **kwargs): data = self.request.POST form = ContactForm(data) if form.is_valid(): form.save() # Response return self.render_json_response({'sent': True}) else: return self.render_json_response({'error': True})
def home(request): if request.method == 'POST': form = ContactForm(request.POST or None) if form.is_valid(): form.save() return HttpResponse('OK') else: form = ContactForm() context = { 'form': form, } return render(request, 'home.html', {'form': form})
def contact(request): if request.method == 'POST' and request.is_ajax(): form = ContactForm(request.POST) logger.debug(request.POST) if form.is_valid(): form.save() response = 'Dziękujemy, twoja wiadomość została wysłana.' return HttpResponse(response, 'text/html') else: template = 'main/contact.html' context = RequestContext(request, dict(form=form)) response = render_to_string(template, context) return HttpResponse(response, 'text/html')
def index_page(request): works_list = Works.objects.all() # works_list = Works.objects.filter(category=2).order_by("-start_date") paginator = Paginator(works_list, 40) page = request.GET.get("page") try: works = paginator.page(page) except PageNotAnInteger: works = paginator.page(1) except EmptyPage: works = paginator.page(paginator.num_pages) errors = [] if request.method == "POST": if not request.POST.get("name", ""): errors.append("Введите ваше имя") if not request.POST.get("email", ""): errors.append("Введите ваш e-mail") if not request.POST.get("message", ""): errors.append("Введите ваше сообщение") form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data send_mail(cd["name"], cd["message"], cd.get("email", "*****@*****.**"), ["*****@*****.**"]) form.save() return HttpResponseRedirect("/thanks/") else: form = ContactForm() return render( request, "main.html", { "services": Services.objects.all(), "works": works, "client_list": Clients.objects.all(), "slides_list": Slider.objects.all(), "form": form, "errors": errors, "about": About.objects.all(), }, )
def contact(reguest): #if reguest.is_ajax(): if reguest.method == 'POST': form = ContactForm(reguest.POST) if form.is_valid(): subject = form.cleaned_data['name'] sender = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(sender, subject, message) except BadHeaderError: return HttpResponse('Invalid header found') #return render(reguest, 'ok.html') form.save() return HttpResponse({'message': 'success'}) else: form = ContactForm() return render(reguest, 'contact.html', {'form': form})
def contact(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] email = form.cleaned_data["email"] tel = form.cleaned_data["tel"] message = form.cleaned_data["message"] form.save() try: send_mail("prise de rdv", message, email, ["*****@*****.**"]) except ConnectionRefusedError: print("ConnectionRefusedError") return redirect(accueil) except BadHeaderError: return HttpResponse("invalid header found.") return redirect(accueil) else: return render(request, "main/contact.html", {"form": form}) else: form = ContactForm() print("test") return render(request, "main/contact.html", {"form": form})
def contact(request): form = ContactForm(request.POST or None) if form.is_valid(): # instance = form.save(commit=False) # name = instance.name # email = instance.email # message = instance.message # EmailMessage( # 'New message from %s', %name, # 'Hi admin, This is my message from this email address: %s\n\n Message: %s', %(email, message), # conf_settings.EMAIL_HOST_USER, # ['*****@*****.**'], # ).send() form.save() messages.success(request, 'Your message has been sent!') return redirect('contact') context = {'form':form} return render(request, 'main/contact.html', context)
def post(self, request): form = ContactForm(request.POST) if(form.is_valid()): email = form.cleaned_data['received_email'] name = form.cleaned_data['received_from'] try: person = Person.objects.get(email=email) except Person.DoesNotExist: person = Person(name=name, email=email) person.save() contact = form.save() contact.person = person contact.save() if(self.lang == 'pt-br'): succes = 'Obrigado por entrar em contato! ;)' else: succes = 'Thank you for reaching out! ;)' messages.success(request, succes) form = ContactForm() context = {'form': form} return render(request, 'contact.html', context) else: if(self.lang == 'pt-br'): error = 'Não foi possível registrar seu contato, por favor mantenha em mente que todos os campos são' \ ' obrigatórios.' else: error = "It wasn't possible to register your contact, please make note that all fields are required." messages.error(request, error) context = {'form': form} return render(request, 'contact.html', context)
def contact(request): config = Home.objects.get(id=1) if request.method == 'POST': form = ContactForm(data=request.POST) if form.is_valid(): c = form.save() c.send_client_email() c.send_admin_emails() return render(request=request, template_name='main/contacted.html', context={ 'config': config, 'form': form }) else: form = ContactForm() return render(request=request, template_name='main/contact.html', context={ 'config': config, 'form': form })
def property(request, pk, slug, action = None): ''' displays the full listing for properties and functions such as contact owner, or set up a reservation. Need to gather the property information room/pictures and forms ''' property = get_object_or_404(Property, id=pk) save_impression(imp_type="P", imp_property=property) contact = property.get_contact_user() #perform certain actions that are passed in in the action kwarg if action == "reserve": load_modal = "propertyReserveModal" elif action == "contact": load_modal = "propertyContactModal" elif action == "schedule": load_modal = "propertyScheduleModal" else: load_modal = slug favorited = get_favorites(request.user) template = 'propertycontent/property.html' base_dir = settings.BASE_DIR related_properties = property.get_related_properties() # get the images, videos, rooms for properties property_images = PropertyImage.objects.filter(property=pk, floorplan=False) floorplan_images = PropertyImage.objects.filter(property=pk, floorplan=True) property_rooms = PropertyRoom.objects.filter(property=pk) property_videos = PropertyVideo.objects.filter(property=pk) # add nearby businesses to display in the nearby section. Right now there # is no logic, but we will need to build in a model method try: nearby = Property.objects.filter(school=property.school, type="BUS")[0:4] except: nearby = [] walkscore_json = get_walkscore(property) for p in related_properties: save_impression(imp_type="S", imp_property=p) #set form defaults based on if the user is logged in if request.user.is_authenticated(): email = request.user.email first_name = request.user.first_name last_name = request.user.last_name else: email = None first_name = None last_name = None #shared initial values dictionary to be used on multiple forms initial_dict = {'first_name':first_name, 'last_name':last_name, 'email':email} #set contact forms to use contact_form = ContactForm() initial_contact_form = ContactForm(initial=initial_dict) #filter room choices and set the reserve forms room_choices = PropertyRoom.objects.filter(property=property.id) reserve_form = ReserveForm() reserve_form.fields["floor_plan"].queryset = room_choices initial_reserve_form = ReserveForm(initial=initial_dict) initial_reserve_form.fields["floor_plan"].queryset = room_choices #setup for the schedule form schedule_form = ScheduleForm() initial_schedule_form = ScheduleForm(initial=initial_dict) ''' build a shared dictionary to be used with all renders. We will tack on other values to the dictionary, but these will be included in all ''' render_dict = {'property':property, 'property_images':property_images, 'property_rooms':property_rooms, 'favorited':favorited, 'contact_form':contact_form, 'reserve_form':reserve_form, 'floorplan_images':floorplan_images, 'related_properties': related_properties, 'schedule_form':schedule_form, 'property_videos':property_videos, 'nearby':nearby, 'contact':contact} if request.method == "POST": ''' If we're receiving a POST request, that means that one of the actions has been taken on the property page. The user might be sending a contact email or scheduling a tour ''' #only send to property contact if in production internal_email = settings.EMAIL_HOST_USER if base_dir == "/home/studentrentit/rvprod": # In Prod Environment, email contact email_to = [property.get_contact_user().email] email_bcc = [internal_email] else: # Not in Prod, email test/developer email_to = ['*****@*****.**'] email_bcc = [] if 'body' in request.POST: #handle if contact form was submitted contact_form = ContactForm(request.POST) if contact_form.is_valid(): #handle if ContactForm was submitted cd = contact_form.cleaned_data body_footer = "<p>" + cd["first_name"] + " " + cd["last_name"] + \ " is interested in " + str(property) + " and can be reached by email at " + cd['email'] \ + " or calling their phone at " + cd['phone_number'] + '.' headers = {'Reply-To': cd['email']} email_to.append(cd['email']) #build the email and send it msg = EmailMessage('RentVersity.com - Property Contact', get_template('email/default.html').render( Context({ 'body':cd['body'] + body_footer, 'webURLroot' : settings.WEB_URL_ROOT, 'email_header' : 'Property Contact from RentVersitys.com' }) ), settings.EMAIL_HOST_USER, email_to, headers=headers ) msg.content_subtype = "html" # Main content is now text/html msg.send() contact = contact_form.save(commit=False) contact.property = property contact.save() return render(request, template, dict(render_dict, **{'contact_form':initial_contact_form, 'status':'sent'})) else: #contact_form errors return render(request, template, dict(render_dict, **{'contact_form':contact_form, 'status':'error', 'load_modal':'propertyContactModal'})) elif 'schedule_date' in request.POST: #handle if the schedule form was submitted schedule_form = ScheduleForm(request.POST) if schedule_form.is_valid(): schedule = schedule_form.save(commit=False) schedule.property = property #save the user if logged in try: schedule.user = get_user_model().objects.get(username = request.user) except get_user_model().DoesNotExist: pass schedule.save() cd = schedule_form.cleaned_data headers = {'Reply-To': cd['email']} body_footer = "<p>They can be reached by email at " + cd['email'] + " or calling their phone at " + cd['phone_number'] + '.' email_to.append(cd['email']) #build up body text body = cd["first_name"] + " " + cd["last_name"] + ' has scheduled a tour on ' + cd['schedule_date'].strftime('%b %d %Y') + \ ' at ' + cd['schedule_time'].strftime('%I:%M %p') + ' for ' + str(property) + \ '. Please follow up with them to confirm or change the appointment.'\ + body_footer #build the email and send it msg = EmailMessage('RentVersity.com - Apartment Tour', get_template('email/default.html').render( Context({ 'body' : body, 'webURLroot' : settings.WEB_URL_ROOT, 'email_header' : 'Tour Scheduled from RentVersity.com' }) ), settings.EMAIL_HOST_USER, email_to, email_bcc, headers=headers ) msg.content_subtype = "html" # Main content is now text/html msg.send() return render(request, template, dict(render_dict, **{'schedule_form':initial_schedule_form, 'status':'scheduled'})) else: #schedule_form errors return render(request, template, dict(render_dict, **{'schedule_form':schedule_form, 'status':'error', 'load_modal':'propertyScheduleModal'})) return render(request, template, dict(render_dict, **{'reserve_form':initial_reserve_form, 'contact_form':initial_contact_form, 'schedule_form':initial_schedule_form, 'walkscore':walkscore_json, 'contact':contact, 'load_modal':load_modal }))