I need to add some validation constraints on my CustomUserCreationForm Meta class.
I can't find where and how to add it. Should I use a RegexValidator or not for this purpose?
For example I'd like the first_name to be minimum length 2 and maximum length 30 only letters.
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.forms import ModelForm
from .models import *
import datetime
class CustomUserCreationForm(UserCreationForm):
birth_date = forms.DateField(
label='birthdate',
widget=forms.DateInput(
attrs={'placeholder':'jj/mm/aaaa'}
)
)
introduction = forms.CharField(
label='introduction',
min_length=20,
max_length=500,
widget = forms.Textarea(
attrs={
'placeholder': 'Hey, I\'m Wely.',
'cols':"40",
'rows':"5"
}
)
)
address1 = forms.CharField(
label='Address (1st line)',
min_length=2,
max_length=40,
widget = forms.TextInput(
attrs={'placeholder': '1st av. Lincoln'}
)
)
address2 = forms.CharField(
required=False,
label='Address (2nd line)',
min_length=0,
max_length=40,
widget = forms.TextInput(
attrs={'placeholder': 'Apt 3'}
)
)
registration_video = forms.CharField(
label='video',
widget = forms.FileInput(
attrs={'style': 'display:none'}
)
)
class Meta:
model = CustomUser
fields = ('first_name', 'last_name', 'email')
labels = {
'first_name': 'First name',
'last_name': 'Last Name',
'email': 'E-mail address'
}
widgets = {
'first_name': forms.TextInput(attrs = {'placeholder': 'Alicia'}),
'last_name': forms.TextInput(attrs = {'placeholder': 'Rodriguez'}),
'email': forms.EmailInput(attrs = {'placeholder': 'alicia#mail.com'}),
}
Not use RegexValidator. Only change like this. Here we add minlength and maxlength inside the attr for first_name field.
class Meta:
model = CustomUser
fields = ('first_name', 'last_name', 'email')
labels = {
'first_name': 'First name',
'last_name': 'Last Name',
'email': 'E-mail address'
}
widgets = {
'first_name': forms.TextInput(attrs = {'placeholder': 'Alicia','minlength':2,'maxlength':30}),
'last_name': forms.TextInput(attrs = {'placeholder': 'Rodriguez'}),
'email': forms.EmailInput(attrs = {'placeholder': 'alicia#mail.com'}),
}
Related
I want to save user and profile information in db at the same time as social login.
Argument of type "Self#UserManager" cannot be assigned to parameter "self" of type "Profile" in function "create_profile"
"UserManager" is incompatible with "Profile" I got an error like this
How can I fix this error?
from django.db import models, transaction
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
# Create your models here.
class UserManager(BaseUserManager):
#transaction.atomic
def create_user(self, validate_data):
username = validate_data["username"]
email = validate_data["email"]
password = validate_data["password1"]
first_name = validate_data['first_name']
last_name = validate_data['last_name']
if not username:
raise ValueError('아이디는 필수 항목입니다.')
if not email:
raise ValueError('이메일은 필수 항목입니다.')
if not password:
raise ValueError('패드워드는 필수 항목입니다.')
user = self.model(
username=username,
first_name=first_name,
last_name=last_name,
email = self.normalize_email(email)
)
user.set_password(password)
user.full_clean()
user.save(using=self._db)
profile = Profile.create_profile(self, user=user, data=validate_data)
profile.save()
return user
def create_superuser(self, email=None, password=None, nickname="슈퍼", **extra_fields):
superuser = self.model(
email = self.normalize_email(email),
password = password,
nickname = nickname,
)
superuser.set_password(password)
superuser.full_clean()
superuser.is_staff = True
superuser.is_superuser = True
superuser.is_active = True
superuser.save(using=self._db)
return superuser
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
nickname = models.CharField(max_length=20)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
realname = models.CharField(max_length=128, null=True, blank=True)
nickname = models.CharField(max_length=128, null=True, blank=True, unique=True)
prfile_pic = models.ImageField(null=True, blank=True)
provier = models.CharField(max_length=128, null=True, blank=True)
def __str__(self):
return self.user.nickname
def create_profile(self, user, data):
first_name = data.get("first_name", "")
last_name = data.get("last_name", "")
profile = Profile(
user=user,
realname = first_name + last_name,
)
profile.save()
return profile
I did a search but I'm not sure
i want to assign logged in user to the model but perform_create not working
any help how to fix this.
OkHttp: {"aggregator":["Invalid pk "0" - object does not exist."]}
class FarmerViewset(
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
# mixins.DestroyModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet
):
queryset = Farmer.objects.all()
serializer_class = FarmerSerializers
def perform_create(self, serializer):
serializer.validated_data['aggregator'] = self.request.user
serializer.save()
seliarizer.py
class FarmerSerializers(serializers.ModelSerializer):
farmer_requests = RequestSerializers(many=True, read_only=True)
class Meta:
model = Farmer
fields = '__all__'
extra_kwargs = {
'created_at': {'read_only': True},
'updated_at': {'read_only': True},
}
model
class Farmer(models.Model):
first_name = models.CharField(_(" Enter first name"),max_length=30)
last_name = models.CharField(_(" Enter last name"),max_length=30)
phone = models.IntegerField(_("Telephone number"), null=True)
district = models.ForeignKey(
"authentication.District",
verbose_name=("district"),
on_delete = models.CASCADE
)
sector = models.ForeignKey(
"authentication.Sector",
verbose_name=("sector"),
on_delete = models.CASCADE
)
aggregator = models.ForeignKey(
"authentication.User",
verbose_name=("aggregator"),
on_delete = models.CASCADE
)
created_at = models.DateTimeField(_("Date of creation"),default=timezone.now)
updated_at = models.DateTimeField(_("Updated date"),default=timezone.now)
Did you use permission_classes = (IsAuthenticated,) in your views.py (at FarmerViewset). And also did you add to settings.py the following line ?
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}`
Form in forms.py when rendering HTML have required attr but in form don't have. Fields in models.py can be null execpt primary key and foreign key. I want delete required attr in HTML
models.py
class UserInfor(models.Model):
GENDERS = (
('nam', "Nam"),
('nữ', "Nữ"),
('khác', "Khác")
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
date_of_birth = models.DateField(null=True)
gender = models.CharField(choices=GENDERS, max_length=10, null=True)
address = models.CharField(max_length=255, null=True)
phone_number = models.CharField(max_length=10, null=True)
def __str__(self):
return self.user.username
forms.py
class ProfileForm(ModelForm):
class Meta:
model = UserInfor
fields = ['date_of_birth', 'gender', 'address', 'phone_number']
widgets = {
'date_of_birth': forms.DateInput(attrs={'placeholder': 'Date of Birth', 'class': 'form-control'}),
'address': forms.TextInput(attrs={'type': 'text', 'placeholder': 'Address', 'class': 'form-control'}),
'phone_number': forms.TextInput(attrs={'type': 'text', 'placeholder': 'Phone Number', 'class': 'form-control'}),
}
labels = {
'date_of_birth': "Ngày sinh",
'gender': "Giới tính",
'address': "Địa chỉ",
'phone_number': "Số điện thoại",
}
profile.html
<div class="col-lg-10">
<div class="form-group">
<label for="id_date_of_birth"><h6>Ngày sinh</h6></label>
<input type="text" name="date_of_birth" value="1998-09-26" placeholder="Date of Birth" class="form-control" required id="id_date_of_birth">
</div>
</div>
You should only need to set blank=true on your ModelForms fields:
models.py
class UserInfor(models.Model):
GENDERS = (
('nam', "Nam"),
('nữ', "Nữ"),
('khác', "Khác")
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
date_of_birth = models.DateField(null=True, blank=true)
gender = models.CharField(choices=GENDERS, max_length=10, null=True, blank=true)
address = models.CharField(max_length=255, null=True, blank=true)
phone_number = models.CharField(max_length=10, null=True, blank=true)
def __str__(self):
return self.user.username
I have three model. Product, ShoppingCart and CartDetails. when i add a product to cart i want to save data in ShoppingCart and CartDetails.ShoppingCart (id) is related with CartDetails (cart_id).And CartDetails (product_id) is related with Product(id). Now when i am posting data it shows the error "Column 'product_id' cannot be null". I think i am missing a silly thing. But cannot find out the silly thing. I am new to django rest framework.I am using angular for front end. I don't understand what i am doing wrong.Thanks in advance.
models.py
class Product(models.Model):
product_name = models.CharField(max_length=200)
cat_id = models.ForeignKey('Category', on_delete=models.CASCADE, db_column='cat_id')
description = models.TextField()
image_url = models.ImageField(upload_to='images/product_name/%Y/%m/%d/')
sell_price = models.IntegerField()
cost_price = models.IntegerField()
discount_price = models.IntegerField()
active = models.BooleanField()
create_date = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.product_name
class Meta:
db_table = "products"
class ShoppingCart(models.Model):
create_date = models.DateTimeField(default=datetime.now)
amount = models.IntegerField(default=0)
def __int__(self):
return self.id
class Meta:
db_table = "shopping-cart"
class CartDetails(models.Model):
cart = models.ForeignKey(ShoppingCart, related_name='cart_details', on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
qty = models.IntegerField(default=0)
amount = models.IntegerField(default=0)
create_date = models.DateTimeField(default=datetime.now)
def __int__(self):
return self.id
class Meta:
db_table = "cart-details"
serializers.py
class ProductSerializer(serializers.ModelSerializer):
image_url = Base64ImageField(max_length=None, use_url=True)
class Meta:
model = Product
fields = ('id', 'product_name', 'description', 'image_url', 'sell_price', 'cost_price',
'discount_price', 'active', 'cat_id')
class CartDetailSerializer(serializers.ModelSerializer):
class Meta:
model = CartDetails
fields = ('product', 'qty', 'amount')
class ShoppingCartSerializer(serializers.ModelSerializer):
cart_details = CartDetailSerializer()
class Meta:
model = ShoppingCart
fields = ('id', 'amount', 'cart_details')
def create(self, validated_data):
carts_data = validated_data.pop('cart_details')
# cart = ShoppingCart.objects.create(**validated_data)
# for data in carts_data:
# CartDetails.objects.create(cart=cart, **carts_data)
return validated_data
views.py
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
class ShoppingCartViewSet(viewsets.ModelViewSet):
queryset = ShoppingCart.objects.all()
serializer_class = ShoppingCartSerializer
class CartDetailsViewSet(viewsets.ModelViewSet):
queryset = CartDetails.objects.all()
serializer_class = CartDetailSerializer
This is angular service to post data
private create(product) {
const cart = {
amount: product.sell_price,
cart_details: {
qty: 1,
product: product.id,
amount: product.sell_price
}
};
return this.http.post(this.globalService.baseUrl + 'shopping-cart/', cart);
}
If i am not wrong, problem is here
product_id = ProductSerializer(read_only=True, source='product.id')
as you make this as read_only field, so product_id is not writing on instance creation. read_only should be removed.
product_id = ProductSerializer(source='product.id')
In serializer:
class EventUserRegisterSerializer(ModelSerializer):
first_name = serializers.CharField(write_only=True)
last_name = serializers.CharField(write_only=True)
email = serializers.EmailField(validators=
[UniqueValidator(queryset=User.objects.all())], write_only=True)
views:
try:
user = User.objects.get(phone_number=phone_number,
email=email)
user.first_name = first_name
user.last_name = last_name
except User.DoesNotExist:
user =
User.objects.create(username=username,first_name=first_name,
last_name=last_name, phone_number=phone_number,
email=email)
model:
class User(AbstractUser):
first_name = models.CharField(max_length=200, blank=True,
default="")
last_name = models.CharField(max_length=200, blank=True,
default="")
phone_number = models.CharField(max_length=20, unique=True,
default="")
timestamp = UnixDateTimeField(auto_now=True)
#property
def unique_id(self):
return self.first_name + self.timestamp
I have a partial payment system so i have to done multiple 'post' ,but validation error occurs