示例#1
0
文件: views.py 项目: s2idm/hotel
def create_post(request):
    if request.method == 'POST':
        date_depart = request.POST.get('date_depart')
        date_arriver = request.POST.get('date_arriver')
        nom = request.POST.get('nom')
        telephone = request.POST.get('telephone')
        email = request.POST.get('email')
        message = request.POST.get('message')
        adultes = request.POST.get('adultes')
        enfants = request.POST.get('enfants')
        moyen = request.POST.get('moyen')
        response_data = {}

        post = Contact(nom=nom,date_arriver=date_arriver,date_depart=date_depart,telephone=telephone,
                       email=email,message=message,adultes=adultes,moyen=moyen,enfants=enfants)
        post.save()

        response_data['result'] = 'Create post successful!'


        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )
    def handle(self, *args, **options):
        filename = options['filename'][0]
        with open(filename) as myfile:
            print("Reading electoral data...")
            reader = csv.DictReader(myfile)
            data = [preprocess_dict(x) for x in reader]
            print("done - %d records read" % len(data))

        records_done = 0
        temp_list = []
        for grouper, my_group in groupby(data, key=groupby_key):
            my_group = list(my_group)
            domecile_dict = split_dict(my_group[0], domecile_elements)
            domecile_dict['electoral_registration_office'] = self.ero
            domecile_obj, result = Domecile.objects.get_or_create(
                **domecile_dict)
            for line in my_group:
                contact = split_dict(line, contact_elements)
                contact_obj = Contact.objects.filter(
                    domecile=domecile_obj,
                    ero_number=contact['ero_number'],
                    pd=contact['pd']).first()
                records_done += 1
                if not contact_obj:
                    contact_obj = Contact(**contact)
                    contact_obj.domecile = domecile_obj
                    temp_list.append(contact_obj)
                if records_done % 5000 == 0:
                    print("%d records done - last one %s, %s" %
                          (records_done, contact_obj, domecile_obj))
                    Contact.objects.bulk_create(temp_list)
                    temp_list = []
        if temp_list:
            Contact.objects.bulk_create(temp_list)
            print(temp_list)
示例#3
0
    def handle(self, *args, **options):
        filename = options['filename'][0]
        with open(filename) as myfile:
            print("Reading electoral data...")
            reader = csv.DictReader(myfile)
            data = [transform_dict(x, rename_dict) for x in reader]
            for line in data:
                if 'postcode' not in line or not line['postcode']:
                    for i in range(7, 0, -1):
                        index = 'address_' + str(i)
                        if line[index]:
                            try:
                                line['postcode'] = line['address_' + str(i)]
                                line['address_%d' + str(i)] = ''
                                break
                            except KeyError:
                                line['postcode'] = ''
                                break
                            finally:
                                if line['postcode'] == 'OTHER ELECTORS':
                                    line['postcode'] = ''
            data.sort(key=groupby_key)
            print("done - %d records read" % len(data))

        records_done = 0
        temp_list = []
        for grouper, my_group in groupby(data, key=groupby_key):
            my_group = list(my_group)
            domecile_dict = split_dict(my_group[0], domecile_elements)
            domecile_dict['electoral_registration_office'] = self.ero
            try:
                domecile_obj, result = Domecile.objects.get_or_create(**domecile_dict)
            except DataError:
                print(domecile_dict)
                raise
            for line in my_group:
                contact_dict = split_dict(line, contact_elements)
                if contact_dict['date_of_attainment']:
                    temp = [int(x) for x in contact_dict['date_of_attainment'].split('/')]
                    contact_dict['date_of_attainment'] = date(temp[2], temp[1], temp[0])
                else:
                    contact_dict['date_of_attainment'] = None
                contact_obj = Contact.objects.filter(ero_number=contact_dict['ero_number'],
                                                     domecile__electoral_registration_office=self.ero,
                                                     pd=contact_dict['pd']).first()
                records_done += 1
                if not contact_obj:
                    contact_obj = Contact(**contact_dict)
                    contact_obj.domecile = domecile_obj
                    temp_list.append(contact_obj)
                    if records_done % 1000 == 0:
                        print("%d records done - last one %s, %s" % (records_done, contact_obj, domecile_obj))
                        Contact.objects.bulk_create(temp_list)
                        temp_list = []
        if temp_list:
            Contact.objects.bulk_create(temp_list)
            print(temp_list)
示例#4
0
def home(request):
    if request.method=="POST":
        print('This is post')
        email=request.POST['email']
        name=request.POST['name']
        number=request.POST['number']
        # print(email,name,number)
        ins=Contact(name=name,email=email,number=number)
        ins.save()
        print("data is returned to DB")
    context={}
    return render(request,'home.html',context)
示例#5
0
def contact(request):
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        subject = request.POST['subject']
        msg = request.POST['msg']
        print(name, email, subject, msg)
        contact = Contact(name=name, email= email, subject=subject, msg= msg)
        contact.save()


    context = {'contact': 'active'}
    return render(request, 'core/contact.html', context)
示例#6
0
def contact_added(request,pk):
        user = User.objects.get(id=pk)
        contact_profile = Profile.objects.get(pk=pk)
        mainuser = request.user
        new_contact = Contact(user=mainuser, name=contact_profile.user.username, email=user.email)
        new_contact.save()
        pk = request.user.id
        return redirect(to='profile', pk=pk)


        return render(request, 'profile', {
        'contact_profile': contact_profile,
        'user': user,
 
        })
示例#7
0
def login(msg):
    """
    Verifica se o usuário consta na base de dados do App Care e interage com o contato.
    Também registra na base do bot, os dados do novo contato do bot, caso ainda não exista.
    :param msg: Mensagem recebida
    :return: Falso ou verdadeiro, para a autorização do contato.
    """
    try:
        # Verifica se o usuário existe na base da dados do Bot
        contact = Contact.objects.get(user_id=msg['user_id'])

    except Contact.DoesNotExist:
        try:
            # Verifica se o contato é cadastrado na base do App Care.
            if user_app(msg['phone_number']):
                # Salva o contato na base de dados do Bot.
                Contact(user_id=msg['user_id'],
                        first_name=msg['first_name'],
                        last_name=msg['last_name'],
                        phone_number=msg['phone_number']).save()

            else:
                bot.send_message(
                    text='Olá {0} {1}!\n\n'
                    'Não te localizei como um usuário registrado.\n\n'
                    'Solicite o cadastro no App Care e retorne para que eu possa te atender.\n\n'
                    'Obrigado pelo contato.'.format(msg['first_name'],
                                                    msg['last_name']),
                    chat_id=msg['user_id'])
                return False

        except BaseException:
            return False

    return True
示例#8
0
 def test_str(self):
     contact = Contact(
         speaker=self.speaker,
         kind='E',
         value='*****@*****.**',
     )
     self.assertEqual('*****@*****.**', str(contact))
示例#9
0
    def test_choices(self):
        """Contact kind should be limited to E or P"""
        contact = Contact(
            speaker=self.speaker,
            kind='A',
            value='21-996186180',
        )

        self.assertRaises(ValidationError, contact.full_clean)
示例#10
0
文件: views.py 项目: Firexd2/poker
    def get_context_data(self, **kwargs):
        context = super(BaseView, self).get_context_data()

        context['translation'] = Translation.get_translation_by(
            self.request.GET.get('lang', ''))
        context['all_translations'] = Translation.get_all_translations()
        context['contacts'] = Contact.get_all_contacts()
        # переменная, которая хранит строку GET параметра с текущим языком. подставлять на все URL
        context['parameter_lang'] = self._get_parameter_lang()

        return context
示例#11
0
def separate_contacts_and_domiciles(line):
    domecile = {
        key.replace('Domecile.', ''): y
        for key, y in line.items() if 'Domecile.' in key
    }
    try:
        matched = Domecile.objects.get(
            **{
                key.replace('Domecile.', ''): y
                for key, y in line.items() if 'Domecile.' in key
            })
    except Domecile.DoesNotExist:
        matched = Domecile(**domecile)
        matched.save()
    contact = {
        key.replace('Contact.', ''): y
        for key, y in line.items() if 'Contact.' in key
    }
    contact = Contact(**contact)
    contact.domecile = matched
    return contact
示例#12
0
def contact(request):
    if request.method == 'POST':

        nm = request.POST['name']
        em = request.POST['email']
        sb = request.POST['subject']
        msg = request.POST['message']
        contact = Contact(name=nm, email=em, subject=sb, message=msg)
        contact.save()
        messages.success(request, 'Form Submitted Sucessfully!!')

        contact = Contact()

    context = {'contact': 'active'}

    return render(request, 'core/contact.html', context)


#  if request.method == 'POST':
#         name = request.POST['name']
#         phone = request.POST['phone']
#         email = request.POST['email']
#         message = request.POST['message']

#         contact = Contact(name=name, phone=phone, email=email, message=message)
#         contact.save()
#     # showIndx = Contact.objects.all()
#     return render(request, 'myblog/index.html')
示例#13
0
def formulario(request):
    contatos = Contact.objects.all()
    
    if request.method == 'POST':
        nome = request.POST.get('first_name')
        sobrenome = request.POST.get('last_name')
        email = request.POST.get('email')
        twitter = request.POST.get('twitter')
        novo_contato = Contact(
               first_name=nome,
               last_name=sobrenome, 
               email=email, 
               twitter=twitter
        )
        novo_contato.save()
        print('antes')
        return HttpResponseRedirect(reverse('url:core_formis'))
    
    print('depois')
    return render(request, 'core/index.html', {
            'contatos' : contatos,
         })
示例#14
0
def contactUs(request):
    if request.method == "POST":
        c = Contact()        
        c.name = request.POST["name"]
        c.phone = request.POST["phone"]
        c.email = request.POST["email"]
        c.description = request.POST["message"]
        c.save()

    a = Home.objects.get(id=1)
    
    context= {
       'detail':a   

    }
    return render(request, 'core/contact.html',context=context)
示例#15
0
class ContactModelTest(TestCase):
    def setUp(self):
        self.obj = Contact(name='Marcelo Andriolli',
                           email='*****@*****.**',
                           phone='48-996274443')
        self.obj.save()

    def test_create(self):
        self.assertTrue(Contact.objects.exists())

    def test_get(self):
        contact = Contact.objects.get(name='Marcelo Andriolli')
        self.assertTrue(self.obj.name, contact.name)

    def test_update(self):
        expected = '*****@*****.**'
        self.obj.email = expected
        self.obj.save()
        self.assertTrue(expected, self.obj.email)

    def test_delete(self):
        Contact.objects.filter(name='Marcelo Andriolli').delete()
        self.assertFalse(Contact.objects.exists())
示例#16
0
def create_contact(name, phone, email=None):
    contact = Contact(name=name, phone=phone, email=email)
    if not email:
        contact.no_mail = True
    else:
        contact.no_mail = False
    contact.save()

    return Contact.objects.get(pk=contact.id)
示例#17
0
def quickCreate(name, sport, distance, city, date):
    """ example :
    quickCreate(name="Triathlon de Montélimar", sport="Triathlon", distance="XS", city="Montélimar", date="25/06/2015")
    """
    s = Sport
    try:
        s = Sport.objects.get(name=sport)
    except Sport.DoesNotExist:
        print("Sport {0} does not exist".format(sport))

    dc = DistanceCategory
    try:
        dc = DistanceCategory.objects.get(name=distance)
    except DistanceCategory.DoesNotExist:
        print("Distance {0} does not exist".format(distance))

    e = Event(name=name, edition=1)
    e.save()

    c = Contact(name="Pierre Dupont")
    c.save()

    l = Location(country=Location.objects.all()[0].country, city=city)
    l.save()

    r = Race(
        sport=s,
        event=e,
        date=datetime.strptime(date, "%d/%m/%Y"),
        distance_cat=dc,
        price=40,
        contact=c,
        location=l,
    )
    r.save()

    return r
示例#18
0
def create_user(msg):
    """
    Create a user in botdb
    """

    Contact(
        user_id=msg["user_id"],
        first_name=msg["first_name"],
        last_name=msg["last_name"],
        phone_number=msg["phone_number"],
    ).save()

    text = 'Seja bem-vindo {} {} \U0001F642'.format(msg['first_name'],
                                                    msg['last_name'])
    bot.sendMessage(msg['user_id'], text)
示例#19
0
def new_contact(request):
    sauvegarde = False

    if request.method == "POST":
        form = NouveauContactForm(request.POST, request.FILES)
        if form.is_valid():
            contact = Contact()
            contact.nom = form.cleaned_data["nom"]
            contact.adresse = form.cleaned_data["adresse"]
            contact.photo = form.cleaned_data["photo"]
            contact.save()

            sauvegarde = True
    else:
        form = NouveauContactForm()

    return render(request, 'core/contact.html', locals())
示例#20
0
    def handle(self, *args, **options):
        filename = options['filename'][0]
        with open(filename) as myfile:
            print("Reading electoral data...")
            reader = csv.DictReader(myfile)
            data = [transform_dict(x, rename_dict) for x in reader]
            data.sort(key=groupby_key)
            print("done - %d records read" % len(data))

        records_done = 0
        temp_list, error_list = [], []
        for grouper, my_group in groupby(data, key=groupby_key):
            my_group = list(my_group)
            domecile_dict = split_dict(my_group[0], domecile_elements)
            domecile_dict['electoral_registration_office'] = self.ero
            domecile_obj, result = Domecile.objects.get_or_create(
                **domecile_dict)
            for line in my_group:
                contact_dict = split_dict(line, contact_elements)
                if contact_dict['date_of_attainment']:
                    temp = [
                        int(x)
                        for x in contact_dict['date_of_attainment'].split('/')
                    ]
                    contact_dict['date_of_attainment'] = date(
                        temp[2], temp[1], temp[0])
                else:
                    contact_dict['date_of_attainment'] = None
                contact_obj = Contact.objects.filter(
                    ero_number=contact_dict['ero_number'],
                    domecile__electoral_registration_office=self.ero,
                    pd=contact_dict['pd']).first()
                records_done += 1
                if not contact_obj:
                    contact_obj = Contact(**contact_dict)
                    contact_obj.domecile = domecile_obj
                    temp_list.append(contact_obj)
                    if records_done % 5 == 0:
                        try:
                            print("%d records done - last one %s, %s" %
                                  (records_done, contact_obj, domecile_obj))
                        except:
                            pass
                        try:
                            Contact.objects.bulk_create(temp_list)
                        except:
                            error_list += temp_list
                        temp_list = []
        if temp_list:
            try:
                Contact.objects.bulk_create(temp_list)
            except:
                error_list += temp_list

        if error_list:
            for i in error_list:
                try:
                    i.save()
                except:
                    try:
                        print(i)
                    except:
                        pass
示例#21
0
    def test_get(self):
        tm1 = Contact(name='Dr Kelly Harris',
                      description='Head, department of Life Sciences',
                      email='*****@*****.**',
                      contact_type='FACULTY/STAFF',
                      department='LIFE')
        tm1.save()
        tm1_expected = {
            'id': tm1.id,
            'name': tm1.name,
            'website': tm1.website,
            'email': tm1.email,
            'fax': tm1.fax,
            'description': tm1.description,
            'department': tm1.department,
            'contact_type': tm1.contact_type,
            'phone_contact_set': []
        }

        tm2 = Contact(name='Police',
                      department='OTHER',
                      contact_type='EMERGENCY')
        tm2.save()
        tm2_phone = PhoneNumber(phone='119',
                                platforms='TEXT/CALL',
                                contact=tm2)
        tm2_phone.save()
        tm2_expected = {
            'id':
            tm2.id,
            'name':
            tm2.name,
            'website':
            tm2.website,
            'email':
            tm2.email,
            'fax':
            tm2.fax,
            'description':
            tm2.description,
            'department':
            tm2.department,
            'contact_type':
            tm2.contact_type,
            'phone_contact_set': [{
                'id': 1,
                'contact': 2,
                'phone': '119',
                'platforms': 'TEXT/CALL'
            }]
        }

        tm3 = Contact(name='Department of Computing Main Office',
                      website='https://uwi/compsci.html',
                      fax='(876) 390-4838',
                      department='COMP',
                      email='*****@*****.**',
                      contact_type='OFFICE')
        tm3.save()
        tm3_phone1 = PhoneNumber(phone='(876) 983-4782',
                                 platforms='TEXT/CALL',
                                 contact=tm3)
        tm3_phone1.save()
        tm3_phone2 = PhoneNumber(phone='(876) 489-5892',
                                 platforms='TEXT/CALL',
                                 contact=tm3)
        tm3_phone2.save()
        tm3_expected = {
            'id':
            tm3.id,
            'name':
            tm3.name,
            'website':
            tm3.website,
            'email':
            tm3.email,
            'fax':
            tm3.fax,
            'description':
            tm3.description,
            'department':
            tm3.department,
            'contact_type':
            tm3.contact_type,
            'phone_contact_set': [{
                'id': 2,
                'contact': 3,
                'phone': '(876) 983-4782',
                'platforms': 'TEXT/CALL'
            }, {
                'id': 3,
                'contact': 3,
                'phone': '(876) 489-5892',
                'platforms': 'TEXT/CALL'
            }]
        }

        tm4 = Contact(name='MITS', department='OTHER', contact_type='OTHER')
        tm4.save()
        tm4_phone = PhoneNumber(phone='(876) 278-2892',
                                platforms='WHATSAPP',
                                contact=tm4)
        tm4_phone.save()
        tm4_expected = {
            'id':
            tm4.id,
            'name':
            tm4.name,
            'website':
            tm4.website,
            'email':
            tm4.email,
            'fax':
            tm4.fax,
            'description':
            tm4.description,
            'department':
            tm4.department,
            'contact_type':
            tm4.contact_type,
            'phone_contact_set': [{
                'id': 4,
                'contact': 4,
                'phone': '(876) 278-2892',
                'platforms': 'WHATSAPP'
            }]
        }

        #check for all objects being returned
        response = self.client.get('/contact/')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 4)

        expected_response = [
            tm3_expected, tm1_expected, tm4_expected, tm2_expected
        ]

        self.assertEqual(data, expected_response)

        #test department filter
        #test1
        response = self.client.get('/contact/?department=LIFE')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 1)

        expected_response = [tm1_expected]

        self.assertEqual(data, expected_response)

        #test2
        response = self.client.get('/contact/?department=COMP')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 1)

        expected_response = [tm3_expected]

        self.assertEqual(data, expected_response)

        #test3
        response = self.client.get('/contact/?department=OTHER')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 0)

        expected_response = []

        self.assertEqual(data, expected_response)

        #test contact type filter
        #test1
        response = self.client.get('/contact/?type=OTHER')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 1)

        expected_response = [tm4_expected]

        self.assertEqual(data, expected_response)

        #test2
        response = self.client.get('/contact/?type=EMERGENCY')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 1)

        expected_response = [tm2_expected]

        self.assertEqual(data, expected_response)

        #test search filter
        #test1
        response = self.client.get('/contact/?search=pol')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 1)

        expected_response = [tm2_expected]

        self.assertEqual(data, expected_response)

        #test2
        response = self.client.get('/contact/?search=head%20of%20life')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 1)

        expected_response = [tm1_expected]

        self.assertEqual(data, expected_response)

        #test3
        response = self.client.get('/contact/?search=office&department=COMP')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 1)

        expected_response = [tm3_expected]

        self.assertEqual(data, expected_response)

        #test 4
        response = self.client.get('/contact/?search=green&department=COMP')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 0)

        expected_response = []

        self.assertEqual(data, expected_response)

        #test 5
        response = self.client.get('/contact/?search=4782')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 1)

        expected_response = [tm3_expected]

        self.assertEqual(data, expected_response)

        #test 6
        response = self.client.get('/contact/?search=office&type=EMERGENCY')
        self.assertEqual(response.status_code, 200)

        data = response.json()

        self.assertEqual(len(data), 0)

        expected_response = []

        self.assertEqual(data, expected_response)
示例#22
0
 def test_str(self):
     contact = Contact(speaker=self.speaker,
                       kind=Contact.EMAIL,
                       value='*****@*****.**')
     self.assertEqual('*****@*****.**', str(contact))
示例#23
0
 def setUp(self):
     self.obj = Contact(name='Marcelo Andriolli',
                        email='*****@*****.**',
                        phone='48-996274443')
     self.obj.save()