• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

gcivil-nyu-org / INET-Wednesday-Spring2024-Team-2 / 528

22 Apr 2024 08:03PM UTC coverage: 89.652% (-0.04%) from 89.695%
528

push

travis-pro

web-flow
Merge pull request #156 from gcivil-nyu-org/vamshi-signup-validation

phone numbervalidation

3 of 4 new or added lines in 1 file covered. (75.0%)

10 existing lines in 1 file now uncovered.

1005 of 1121 relevant lines covered (89.65%)

0.9 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.52
/users/forms.py
1
import re
1✔
2
from datetime import date, timedelta
1✔
3
from crispy_forms.helper import FormHelper
1✔
4
from crispy_forms.layout import Layout, Submit, Row, Column, Field
1✔
5
from django import forms
1✔
6
from django.contrib.auth.forms import UserCreationForm
1✔
7
from django.contrib.auth import get_user_model
1✔
8
from .models import CustomUser, Rental_Listings
1✔
9
from django.contrib.auth.forms import AuthenticationForm
1✔
10
from django.core.exceptions import ValidationError
1✔
11
from django.contrib.auth.forms import UserChangeForm
1✔
12

13
User = get_user_model()
1✔
14

15

16
class UserSignUpForm(UserCreationForm):
1✔
17
    full_name = forms.CharField(max_length=255, required=True)
1✔
18
    phone_number = forms.CharField(max_length=15, required=True)
1✔
19
    city = forms.CharField(max_length=100, required=True)
1✔
20
    email = forms.EmailField(required=True)
1✔
21

22
    class Meta:
1✔
23
        model = User
1✔
24
        fields = (
1✔
25
            "email",
26
            "full_name",
27
            "phone_number",
28
            "city",
29
            "password1",
30
            "password2",
31
        )
32

33
    def clean_email(self):
1✔
34
        email = self.cleaned_data["email"]
1✔
35
        if not email.endswith("@nyu.edu"):
1✔
36
            raise ValidationError("Oops! Only NYU email addresses are supported.")
1✔
37
        if User.objects.filter(username=self.cleaned_data["email"]).exists():
1✔
38
            raise ValidationError("Email already exists. Please use a different one.")
×
39
        return email
1✔
40
    def clean_phone_number(self):
41
        phone_number = self.cleaned_data.get('phone_number')
1✔
42
        if len(phone_number) != 10 or not phone_number.isdigit():
1✔
43
            raise ValidationError("Phone number must be 10 digits.")
1✔
NEW
44
        return phone_number
×
45

1✔
46
class LandlordSignupForm(UserCreationForm):
47
    pdf_file = forms.FileField(required=False, label="OwnerShip Document")  #
48

1✔
49
    class Meta:
1✔
50
        model = CustomUser
51
        fields = (
1✔
52
            "username",
1✔
53
            "email",
1✔
54
            "full_name",
55
            "phone_number",
56
            "city",
57
            "password1",
58
            "password2",
59
            # "user_type",
60
            "pdf_file",
61
        )
62

63
    # def _init_(self, *args, **kwargs):
64
    #     super(LandlordSignupForm, self)._init_(*args, **kwargs)
65
    #     self.fields["user_type"].initial = CustomUser.LANDLORD
66
    #     self.fields[
67
    #         "user_type"
68
    #     ].widget = forms.HiddenInput()  # Hide the user_type field
69

70
    def _init_(self, *args, **kwargs):
71
        super(LandlordSignupForm, self)._init_(*args, **kwargs)
72
        # No need to set user_type initial value here, as it will be set in save.
1✔
UNCOV
73

×
74
    def save(self, commit=True):
75
        user = super(LandlordSignupForm, self).save(commit=False)
76
        user.user_type = CustomUser.LANDLORD  # Set user_type to LANDLORD
1✔
77

1✔
78
        if commit:
1✔
79
            user.save()
80
            self.save_m2m()
1✔
81

1✔
82
        return user
1✔
83

84

1✔
85
class RentalListingForm(forms.ModelForm):
86
    ROOMS_CHOICES = [(i, str(i)) for i in range(1, 11)]
87
    BATHS_CHOICES = [(i * 0.5, str(i * 0.5)) for i in range(2, 21)]
1✔
88

1✔
89
    UNIT_TYPE_CHOICES = [("Apartment", "Apartment"), ("House", "House")]
1✔
90
    NEIGHBORHOOD_CHOICES = [
91
        ("Manhattan", "Manhattan"),
1✔
92
        ("Brooklyn", "Brooklyn"),
1✔
93
        ("Upper East Side", "Upper East Side"),
94
        ("Upper West Side", "Upper West Side"),
95
        ("Midtown", "Midtown"),
96
        ("Harlem", "Harlem"),
97
        ("Chelsea", "Chelsea"),
98
        ("Greenwich Village", "Greenwich Village"),
99
        ("Soho", "Soho"),
100
        ("East Village", "East Village"),
101
        ("Lower East Side", "Lower East Side"),
102
        ("Williamsburg", "Williamsburg"),
103
        ("Bushwick", "Bushwick"),
104
        ("Park Slope", "Park Slope"),
105
        ("Brooklyn Heights", "Brooklyn Heights"),
106
        ("Red Hook", "Red Hook"),
107
        ("Astoria", "Astoria"),
108
        ("Long Island City", "Long Island City"),
109
        ("Flushing", "Flushing"),
110
        ("Jamaica", "Jamaica"),
111
        ("Forest Hills", "Forest Hills"),
112
        ("Riverdale", "Riverdale"),
113
        ("Fordham", "Fordham"),
114
        ("Concourse", "Concourse"),
115
        ("Throgs Neck", "Throgs Neck"),
116
        ("St. George", "St. George"),
117
        ("Tottenville", "Tottenville"),
118
        ("Stapleton", "Stapleton"),
119
    ]
120

121
    BOROUGH_CHOICES = [
122
        ("Manhattan", "Manhattan"),
123
        ("Brooklyn", "Brooklyn"),
1✔
124
        ("Queens", "Queens"),
125
        ("Bronx", "Bronx"),
126
        ("Staten Island", "Staten Island"),
127
    ]
128

129
    rooms = forms.ChoiceField(choices=ROOMS_CHOICES)
130
    beds = forms.ChoiceField(choices=ROOMS_CHOICES)
131
    baths = forms.ChoiceField(choices=BATHS_CHOICES)
1✔
132
    unit_type = forms.ChoiceField(choices=UNIT_TYPE_CHOICES)
1✔
133
    neighborhood = forms.ChoiceField(choices=NEIGHBORHOOD_CHOICES)
1✔
134
    borough = forms.ChoiceField(choices=BOROUGH_CHOICES)
1✔
135
    photo = forms.ImageField(required=False, widget=forms.ClearableFileInput(attrs={'multiple': True}))
1✔
136

1✔
137

1✔
138
    def __init__(self, *args, **kwargs):
139
        super(RentalListingForm, self).__init__(*args, **kwargs)
140
        self.helper = FormHelper()
141
        self.helper.form_method = "post"
1✔
142
        self.helper.form_enctype = "multipart/form-data"
1✔
143
        self.helper.layout = Layout(
1✔
144
            Row(
1✔
145
                Column("address", css_class="form-group col-md-6 mb-0"),
1✔
146
                Column("zipcode", css_class="form-group col-md-6 mb-0"),
1✔
147
                css_class="form-row",
148
            ),
149
            "price",
150
            "sq_ft",
151
            Row(
152
                Column("rooms", css_class="form-group col-md-4 mb-0"),
153
                Column("beds", css_class="form-group col-md-4 mb-0"),
154
                Column("baths", css_class="form-group col-md-4 mb-0"),
155
                css_class="form-row",
156
            ),
157
            "unit_type",
158
            "neighborhood",
159
            "borough",
160
            "broker_fee",
161
            "central_air_conditioning",
162
            "dishwasher",
163
            "doorman",
164
            "elevator",
165
            "furnished",
166
            "parking_available",
167
            "washer_dryer_in_unit",
168
            "Submitted_date",
169
            "Availability_Date",
170
            Field("photo", multiple=True),
171
            Submit("submit", "Submit", css_class="btn btn-primary"),
172
        )
173

174
    class Meta:
175
        model = Rental_Listings
176
        fields = [
177
            "address",
1✔
178
            "zipcode",
1✔
179
            "price",
1✔
180
            "sq_ft",
181
            "rooms",
182
            "beds",
183
            "baths",
184
            "unit_type",
185
            "neighborhood",
186
            "borough",
187
            "broker_fee",
188
            "central_air_conditioning",
189
            "dishwasher",
190
            "doorman",
191
            "elevator",
192
            "furnished",
193
            "parking_available",
194
            "washer_dryer_in_unit",
195
            "Submitted_date",
196
            "Availability_Date",
197
            "photo",
198
        ]
199
        widgets = {
200
            "Submitted_date": forms.DateInput(attrs={"type": "date"}),
201
            "Availability_Date": forms.DateInput(attrs={"type": "date"}),
202
        }
1✔
203

204
    def clean_price(self):
205
        price = self.cleaned_data["price"]
206
        if price < 0:
207
            raise forms.ValidationError("Price cannot be negative.")
1✔
208
        return price
1✔
209

1✔
210
    def clean_Availability_Date(self):
1✔
211
        availability_date = self.cleaned_data.get("Availability_Date")
1✔
212
        if availability_date and availability_date < date.today():
213
            raise ValidationError("The availability date cannot be in the past.")
1✔
214
        if availability_date and availability_date > date.today() + timedelta(days=365):
1✔
215
            raise ValidationError("The availability date is too far in the future.")
1✔
216
        return availability_date
1✔
217

1✔
UNCOV
218
    def clean_rooms_beds(self):
×
219
        rooms = self.cleaned_data.get("rooms")
1✔
220
        beds = self.cleaned_data.get("beds")
221

1✔
UNCOV
222
        if rooms is not None and beds is not None and rooms < beds:
×
223
            raise ValidationError(
×
224
                "Total number of rooms cannot be less than the number of bedrooms."
UNCOV
225
            )
×
UNCOV
226

×
227
    def clean_zipcode(self):
228
        zipcode = self.cleaned_data["zipcode"]
229
        if not zipcode.isdigit() or len(zipcode) != 5:
230
            raise forms.ValidationError("Please enter a valid 5-digit zip code.")
1✔
231
        return zipcode
1✔
232

1✔
233
    def clean_sq_ft(self):
1✔
234
        sq_ft = self.cleaned_data["sq_ft"]
1✔
235
        if sq_ft < 100:
236
            raise forms.ValidationError(
1✔
237
                "Please enter a valid square footage (100 sq ft minimum)."
1✔
238
            )
1✔
UNCOV
239
        return sq_ft
×
240

241
    def clean_address(self):
242
        address = self.cleaned_data["address"]
1✔
243
        if len(address) > 255:
244
            raise forms.ValidationError("Address is too long.")
1✔
245
        return address
1✔
246

1✔
UNCOV
247

×
248
class CustomLoginForm(AuthenticationForm):
1✔
249
    def __init__(self, *args, **kwargs):
250
        super().__init__(*args, **kwargs)
251

1✔
252

1✔
253
class CustomUserEditForm(forms.ModelForm):
1✔
254
    class Meta:
255
        model = CustomUser
256
        fields = ("full_name", "phone_number", "city")
1✔
257
        widgets = {
1✔
258
            "full_name": forms.TextInput(attrs={"class": "form-control"}),
1✔
259
            "phone_number": forms.TextInput(attrs={"class": "form-control"}),
1✔
260
            "city": forms.TextInput(attrs={"class": "form-control"}),
1✔
261
        }
262

263
    def clean_full_name(self):
264
        full_name = self.cleaned_data["full_name"]
265
        if not re.match("^[a-zA-Z\\s]*$", full_name):  # noqa: W605
266
            raise ValidationError("Name should only contain letters and spaces.")
1✔
267
        return full_name
1✔
268

1✔
UNCOV
269
    def clean_phone_number(self):
×
270
        phone_number = self.cleaned_data["phone_number"]
1✔
271
        if not phone_number.isdigit() or len(phone_number) != 10:
272
            raise ValidationError("Phone number must contain exactly 10 digits.")
1✔
273
        return phone_number
1✔
274

1✔
UNCOV
275
    def clean_city(self):
×
276
        city = self.cleaned_data["city"]
1✔
277
        if not re.match("^[a-zA-Z\\s]*$", city):  # noqa: W605
278
            raise ValidationError("City should only contain letters and spaces.")
1✔
279
        return city
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc