Related
I am making a Django project. I want that my users table field should automatically update when they register for an event. I Have used ForeignKey in my Events model to achieve this. But the problem here is, I can select only 1 user in the events model when creating a new event or editing it(since the relationship is manyToOne). What I want is my events model should show every user that has registered for that event (Something like this).
Am I using the right relationship?
If Not, what should be the correct relationship that I should use?
I am attaching my models for Users and Events.
Kindly Look it through.
accounts/models.py
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(db_index=True, unique=True, max_length=254)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255, null=True, blank=True)
mobile = models.CharField(max_length=50, null=True, blank=True)
address = models.CharField(max_length=200, null=True, blank=True)
short_description = models.CharField(max_length=180, null=True, blank=True)
instagram_url = models.URLField(null=True, blank=True)
linkedin_url = models.URLField(null=True, blank=True)
# is_member = models.BooleanField(default=False)
is_staff = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name']
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
models.py
class Event(models.Model):
banner_image = models.ImageField(upload_to="Events/", max_length=400)
event_name = models.CharField(max_length=150, null=False)
organiser_of_event = models.CharField(max_length=200)
format_of_event = models.CharField(max_length=300, null=True, blank=True)
date_of_event = models.DateField(auto_now_add=False)
registration_fees = models.IntegerField(default=0, help_text="Enter Registration Fees For The Event in Rupees")
registration_link = models.URLField(null=True, blank=True)
details = models.TextField(null=True, blank=True)
is_draft = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# user = models.ForeignKey(User, on_delete=models.SET_NULL)
def __str__(self):
return self.event_name
Custom User model authentication not work for me
i need to override default password field with my define emp_password field because in database i have already created users with their passwords field name as emp_password.
I try to map my username and password with employee table emp_password field.I try this last 2 days so still stuck in this issue.
Please help me thank you in advance.
Let share with you code
models.py
Hello everyone, Custom User model authentication not work for me
i need to override default password field with my define emp_password field because in database i have already created users with their passwords field name as emp_password.
I try to map my username and password with employee table emp_password field and then if everything work then make login api for employee login
Let share with you code
models.py
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.hashers import make_password
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, emp_email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not emp_email:
raise ValueError('The Email must be set')
email = self.normalize_email(emp_email)
user = self.model(emp_email=email, **extra_fields)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, emp_email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
user = self.create_user(
emp_email,
password=password,
**extra_fields
)
user.is_superuser = True
user.is_admin = True
user.save(using=self._db)
return self.create_user(emp_email, password, **extra_fields)
class Factory(models.Model):
factory_id = models.BigAutoField(primary_key=True)
factory_name = models.CharField(max_length=100)
address = models.TextField()
email = models.CharField(max_length=100)
account_name = models.CharField(max_length=200, null=True, blank=True)
account_number = models.CharField(max_length=200, null=True, blank=True)
bank = models.CharField(max_length=300, null=True, blank=True)
branch = models.CharField(max_length=300, null=True, blank=True)
branch_contact_no = models.CharField(max_length=50, null=True, blank=True)
swift_code = models.CharField(max_length=100, null=True, blank=True)
iban = models.CharField(max_length=100, null=True, blank=True)
phone = models.CharField(max_length=20, null=True, blank=True)
fax = models.CharField(max_length=20, blank=True, null=True)
po_box = models.CharField(max_length=15, null=True, blank=True)
description = models.TextField()
operational_head = models.CharField(max_length=100)
logo = models.TextField()
website = models.CharField(max_length=100, null=True, blank=True)
company_color = models.CharField(max_length=100, null=True, blank=True)
tin = models.CharField(max_length=100, null=True, blank=True) # Taxpayer Identification Number
pan = models.CharField(max_length=100, null=True, blank=True) # Permanent Account Number
reg_date = models.DateField()
status = models.PositiveBigIntegerField(default="0")
reg_no = models.CharField(max_length=150, null=True, blank=True)
license_issue_date = models.DateField(null=True, blank=True)
license_expiry_date = models.DateField(null=True, blank=True)
trash = models.IntegerField(default=0)
reference_num_count = models.IntegerField(default=0)
reference_num_year = models.IntegerField(null=True, blank=True)
short_name = models.CharField(max_length=255, null=True, blank=True)
class Meta:
managed = True
db_table = 'factory'
class Employee(AbstractBaseUser, PermissionsMixin):
emp_password = models.CharField(max_length=100)
username = models.CharField(max_length=50, unique=True)
emp_id = models.BigAutoField(primary_key=True)
factory = models.ForeignKey(Factory, on_delete=models.CASCADE, default=1)
user_type = models.CharField(max_length=50)
emp_first_name = models.CharField(max_length=100)
emp_last_name = models.CharField(max_length=100)
emp_gender = models.CharField(max_length=15, null=True, blank=True)
emp_image = models.CharField(max_length=100)
emp_address = models.CharField(max_length=50, null=True, blank=True)
emp_per_address = models.TextField()
emp_city = models.CharField(max_length=15, null=True, blank=True)
emp_postal_code = models.CharField(max_length=10, null=True, blank=True)
emp_email = models.CharField(max_length=100, blank=True, null=True)
emp_thumb_no = models.CharField(max_length=20, blank=True, null=True)
emp_designation = models.CharField(max_length=100, blank=True, null=True)
act_designation = models.CharField(max_length=100, blank=True, null=True)
emp_mobile = models.CharField(max_length=30, blank=True, null=True)
emp_guardian_mobile = models.CharField(max_length=30, blank=True, null=True)
emp_joining_date = models.DateField(null=True, blank=True)
emp_salary = models.FloatField(null=True, blank=True)
basic_salary = models.FloatField(default='0')
emp_bank_ac_no = models.CharField(max_length=100 ,null=True, blank=True)
currency = models.CharField(max_length=50 ,null=True, blank=True)
emp_dob = models.DateField(null=True, blank=True)
emp_marital_status = models.CharField(max_length=20 ,null=True, blank=True)
emp_blood_group = models.CharField(max_length=20 ,null=True, blank=True)
emp_status = models.PositiveSmallIntegerField(default=0) #'0 -> Active,1 -> Deactive'
training_status = models.PositiveSmallIntegerField(default=0) # '0 -> traing persuing,a->trainign complete'
trash = models.PositiveSmallIntegerField(default=0)
share_factory = models.CharField(max_length=50, default="1")
emp_father_name = models.CharField(max_length=60, null=True, blank=True)
nationality = models.CharField(max_length=50, default="0")
religion = models.CharField(max_length=60, null=True, blank=True)
country = models.CharField(max_length=60, null=True, blank=True)
drivinglicense = models.CharField(max_length=10, null=True, blank=True)
experience_years = models.CharField(max_length=25, null=True, blank=True)
dateofapplication = models.CharField(max_length=150, null=True, blank=True)
salary_expectation = models.CharField(max_length=20, null=True, blank=True)
previouscompanyname = models.CharField(max_length=200, null=True, blank=True)
remarks = models.TextField()
acco_allow = models.CharField(max_length=50, null=True, blank=True)
trans_allow = models.CharField(max_length=50, null=True, blank=True)
over_time = models.CharField(max_length=50, null=True, blank=True)
bank_name = models.CharField(max_length=200, null=True, blank=True)
bank_branch = models.CharField(max_length=200, null=True, blank=True)
acc_type = models.CharField(max_length=50, null=True, blank=True)
joining_date = models.CharField(max_length=60, null=True, blank=True)
leave_information = models.CharField(max_length=255, null=True, blank=True)
laborcontractperiod = models.CharField(max_length=50, null=True, blank=True)
visaperiod = models.CharField(max_length=50, null=True, blank=True)
passport_period = models.CharField(max_length=50, null=True, blank=True)
passport_number = models.CharField(max_length=200, null=True, blank=True)
company_email = models.CharField(max_length=100, null=True, blank=True)
company_mobile = models.CharField(max_length=15, null=True, blank=True)
company_activity = models.CharField(max_length=200, null=True, blank=True)
terminated_by = models.CharField(max_length=50, null=True, blank=True)
last_modified = models.DateTimeField(auto_now_add=True, null=True, blank=True)
modified_by = models.CharField(max_length=80, null=True, blank=True)
block = models.PositiveSmallIntegerField(default=0) # 'Deactive employee . He can not login after block',
shared_status = models.PositiveSmallIntegerField(default=0)
login_active = models.PositiveSmallIntegerField(default=1) #'0 -inactive , 1 active'
created = models.DateTimeField(auto_now_add=True)
created_by = models.CharField(max_length=200, null=True, blank=True)
annual_leave_count = models.IntegerField(default=0)
sick_leave_count = models.IntegerField(default=0)
annual_leave_count_date = models.DateField(null=True, blank=True)
sick_leave_count_date = models.DateField(null=True, blank=True)
last_working_date = models.DateField(null=True, blank=True)
group_name = models.CharField(max_length=255, null=True, blank=True) #'Sales Team, ECS, Management'
objects = CustomUserManager()
EMAIL_FIELD = 'emp_email'
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ["emp_email"]
class Meta:
managed = True
db_table = 'employee'
def clean(self):
super().clean()
self.emp_email = self.__class__.objects.normalize_email(self.emp_email)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = "%s %s" % (self.emp_first_name, self.emp_last_name)
return full_name.strip()
def get_short_name(self):
"""Return the short name for the user."""
return self.emp_first_name
settings.py
AUTH_USER_MODEL = "login_app.Employee"
Remember tables already created
urls.py
from django.contrib import admin
from django.urls import path
from .views import ExampleView, UserLoginApiView
urlpatterns = [
path('api/',ExampleView.as_view()),
path('', UserLoginApiView.as_view()),
]
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.settings import api_settings
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.views import ObtainAuthToken
class ExampleView(APIView):
# authentication_classes = [SessionAuthentication, BasicAuthentication]
# permission_classes = [IsAuthenticated]
authentication_classes = [TokenAuthentication]
def get(self, request, format=None):
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
def post(self, request, format=None):
print("request,", request['username'])
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
class UserLoginApiView(ObtainAuthToken):
""" user login api """
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
I'm building an app in which I have a model with several manytomany fields and some foreignkey fields, and I need a view that allows me to create all in one page and let me enter multiply times for the manytomanyfields, but I don't know how to deal with a lot of forms in the same page/view.
main model
class Client(models.Model):
company_name = models.CharField(max_length=255, blank=True, null=True)
payment_method = models.CharField(max_length=64, null=True, blank=True)
owner = models.CharField(max_length=100, blank=True, null=True)
operation = models.CharField(max_length=50, blank=True, null=True)
value = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
currency = models.CharField(max_length=55, null=True, blank=True)
address = models.ManyToManyField(Address, blank=True)
contact = models.ManyToManyField(Contact, blank=True)
relationship = models.ManyToManyField(Relationship, blank=True)
attachment = models.ManyToManyField(Attachment, blank=True)
billing = models.ForeignKey(Billing, null=True, blank=True, on_delete=models.CASCADE)
delivery = models.ForeignKey(Delivery, null=True, blank=True, on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True)
note = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.company_name
others models
class Address(models.Model):
address = models.CharField(max_length=256, null=True, blank=True)
number = models.PositiveIntegerField(null=True, blank=True)
district = models.CharField(max_length=32, null=True, blank=True)
city = models.CharField(max_length=32, null=True, blank=True)
country = models.CharField(choices=COUNTRY_CHOICES, max_length=64, null=True, blank=True)
def __str__(self):
return self.address
class Contact(models.Model):
name = models.CharField(max_length=256, blank=False, null=True)
sector = models.CharField(max_length=64, blank=True, null=True)
email = models.EmailField(max_length=256, blank=True, null=True)
phone = PhoneField(blank=True, null=True)
cellphone = PhoneField(blank=True, null=True)
role = models.CharField(max_length=155, blank=True, null=True)
nfe = models.BooleanField(verbose_name='NFE', default=False)
def __str__(self):
return self.name
class Relationship(models.Model):
company = models.CharField(max_length=256, blank=False, null=True)
agent = models.ForeignKey(Vendedor, on_delete=models.DO_NOTHING, blank=True, null=True)
type = models.CharField(choices=TYPE_CHOICES, max_length=32, blank=True, null=True)
contact = models.CharField(max_length=128, blank=True, null=True)
def __str__(self):
return self.company
class Attachment(models.Model):
file = models.FileField(upload_to='post/img/%Y/%m/%d', blank=True, null=True)
note = models.CharField(verbose_name='Observação', max_length=256, blank=True, null=True)
author = models.ForeignKey(User, on_delete=models.DO_NOTHING)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.note
class BankAccount(models.Model):
bank = models.CharField(max_length=64, blank=False, null=True)
type = models.CharField(max_length=32, blank=False, null=True)
payment_method = models.CharField(max_length=64, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.bank
class Billing(models.Model):
name = models.CharField(max_length=256, blank=True, null=True)
address = models.ForeignKey(Address, null=True, blank=True, on_delete=models.CASCADE)
email = models.EmailField(max_length=256, blank=True, null=True)
phone = PhoneField(blank=True, null=True)
contact = models.CharField(max_length=256, blank=True, null=True)
def __str__(self):
return self.name
class Delivery(models.Model):
name = models.CharField(max_length=256, blank=True, null=True)
address = models.ForeignKey(Address, null=True, blank=True, on_delete=models.CASCADE)
email = models.EmailField(max_length=256, blank=True, null=True)
phone = PhoneField(blank=True, null=True)
contact = models.CharField(max_length=256, blank=True, null=True)
def __str__(self):
return self.name
does anyone know what is the best way to deal with this?
Make a python file forms.py and make model forms for all the models you have. Then in views make a function with all the forms. Then in the html file call the different forms together using jinja2. Here is a simple example:
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
Your_website = models.URLField(blank = True)
profile_pic = models.ImageField(upload_to="profile_pics", blank = True)
def __str__(self):
return self.user.username
This model is connected to the django user model by OneToOneField.
Then in forms.py I have created all the model forms for the models.
from django import forms
from django.contrib.auth.models import User
from basic.models import UserProfileInfo
from django.core import validators
class userform(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
re_enter_password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ("username", "email", "password")
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model = UserProfileInfo
fields = ('Your_website', "profile_pic")
Then make the view with both the model forms.
def register(request):
registered = False
if request.method == 'POST':
user_form = forms.userform(data = request.POST)
profile_form = forms.UserProfileInfoForm(data = request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
else:
user_form = forms.userform()
profile_form = forms.UserProfileInfoForm()
In the html file call both the forms like this:
<div class="container">
<form method="post" enctype="multipart/form-data" class="all_forms">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" class="btn btn-primary" value="Register Now!">
</form>
</div>
This way you don't have to create multiple forms for the models, the user will be asked only one form where all the models will get their separate response from one form.
I am using a custom User model. And I have another Customer model. I want the user field will only show the staff user no other type of user in the field will show in the registration form. In my case, it is showing all types of users whether it is staff or customer or a service user.
Models.py
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=254, unique=True)
name = models.CharField(max_length=254, null=True)
email = models.EmailField(max_length=254, null=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_Customer = models.BooleanField(default=False)
is_Service_Provider = models.BooleanField(default=False)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'username'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % self.pk
def get_username(self):
return self.username
class Customer(models.Model):
user = models.OneToOneField('accounts.User', on_delete=models.SET_NULL, null=True)
email = models.EmailField(max_length=254, null=False)
date_Of_Birth = models.DateField(null=False)
country = models.ForeignKey('accounts.Country', null=True, on_delete=models.SET_NULL, related_name='Country')
state = models.ForeignKey('accounts.State', null=True, on_delete=models.SET_NULL, related_name='State')
city = models.ForeignKey('accounts.City', null=True, on_delete=models.SET_NULL, related_name='city')
address = models.CharField(max_length=254, null=False)
refernce_by_person_name = models.CharField(max_length=254, null=True)
refernce_by_person_contact_no = models.IntegerField(null=True)
phone_no = models.IntegerField(null=False)
alternate_no = models.IntegerField(null=False)
hobbies = models.CharField(max_length=254)
def __str__(self):
return self.user.username
views.py
def form(request):
forms = CustomerRegistrationForm()
if request.method == "POST":
forms = CustomerRegistrationForm(request.POST)
if forms.is_valid():
forms.save()
return redirect('/customer/show')
context = {
'forms' : forms,
}
return render(request,'customer/form.html', context)
forms.py
class CustomerRegistrationForm(forms.ModelForm):
class Meta:
model = Customer
fields = '__all__'
You can filter the staff users in the form like this.
class CustomerRegistrationForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.filter(is_staff=True))
class Meta:
model = Customer
fields = ['user','email','date_of_birth',...]
I want to create two user registration using one custom user.
Here is my
MODELS.PY:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True )
phone_number = PhoneNumberField(_("Phone number"),unique=True, blank=True, null=True)
username = models.CharField(_("Username"),max_length=254,unique=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(auto_now=True)
date_joined = models.DateTimeField(auto_now_add=True)
full_name = models.CharField(_("Full Name"), max_length=50, null=True)
date_of_birth = models.DateField(_("Birth date"), auto_now=False, auto_now_add=False, null=True, blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username',]
class Aesthete(models.Model):
basicuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
is_verified = models.BooleanField(_("Verified"), default=False)
class Artist(models.Model):
basicuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
is_verified = models.BooleanField(_("Verified"), default=True)
debutsong = AudioField(upload_to='songsfile', blank=True,
ext_whitelist=(".mp3", ".wav", ".ogg"),
help_text=("Allowed type - .mp3, .wav, .ogg"))
How can I create registration serializer and view? Please help. Thank you.