<FallbackStorage: request=<WSGIRequest: GET ''>> - django

Hi I have following setup:
Views.py
def employerSignupView(request):
if request.method =="POST":
form = EmployerSignupForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request,'Hooray !! you have account with us now!!')
return redirect('home')
else:
messages.success(request, 'There has been problem registering new account with us. Please try again')
form=EmployerSignupForm()
form=EmployerSignupForm()
return render(request, 'employerSignup.html', {'form': form})
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('signup/employer/', views.employerSignupView, name='employerSignup'),
path('signup/jobSeeker/', views.jobSeekerSignupView, name='jobSeekerSignup'),
path('login/', views.user_login, name ='login'),
path('logout/', views.user_logout, name='logout'),
path('myaccount/',views.myaccount, name='myaccount'),
]
forms.py
class EmployerSignupForm(forms.ModelForm):
username= forms.CharField(max_length=200, widget=forms.TextInput({"placeholder": "Username", "class": "form-control", "type": "text"}))
email= forms.EmailField(widget=forms.TextInput({"placeholder": "Your email", "class": "form-control", "type": "email"}))
first_name = forms.CharField(max_length=50, widget=forms.TextInput({"placeholder": "Buisness Name", "class": "form-control", "type": "text"}))
last_name =forms.CharField(max_length=50, widget=forms.TextInput({"placeholder": "Type", "class": "form-control", "type": "text"}))
password1 =forms.CharField(widget=forms.TextInput({"placeholder": "Password", "class": "form-control", "type": "password"}))
password2 =forms.CharField(widget=forms.TextInput({"placeholder": "Re-type Password", "class": "form-control", "type": "password"}))
streetAddress = forms.CharField(widget=forms.TextInput({"placeholder": "Street Address", "class": "form-control", "type": "text"}))
suburb = forms.CharField(widget=forms.TextInput({"placeholder": "Suburb", "class": "form-control", "type": "text"}))
postcode = forms.CharField(widget=forms.TextInput({"placeholder": "Postcode", "class": "form-control", "type": "text"}))
phoneNumber = forms.CharField(widget=forms.TextInput({"placeholder": "Phone Number", "class": "form-control", "type": "tel"}))
website = forms.CharField(widget=forms.TextInput({"placeholder": "Website", "class": "form-control", "type": "url"}))
class Meta:
model= Employer
fields= ('first_name', 'last_name','username' ,'email', 'streetAddress', 'suburb', 'postcode', 'phoneNumber', 'password1', 'password2' )
models.py
class User(AbstractUser):
class Role(models.TextChoices):
ADMIN = 'ADMIN', 'Admin'
EMPLOYER = 'EMPLOYER', 'Employer'
JOBSEEKER = 'JOBSEEKER', 'Job Seeker'
base_role = Role.ADMIN
role= models.CharField(max_length=20, choices=Role.choices, null=False)
streetAddress = models.CharField(max_length=100)
suburb = models.CharField(max_length=50)
postcode = models.CharField(max_length=10)
phoneNumber = models.CharField(max_length=15)
def save(self, *args, **kwargs):
if not self.pk :
self.role=self.base_role
return super().save(self, *args, **kwargs)
class Employer(User):
last_name = None
role= User.Role.EMPLOYER
website = models.CharField(max_length=100, null=True)
class JobSeeker(User):
role= User.Role.JOBSEEKER
birthDate = models.DateField()
resume = models.FileField(upload_to='static/resume')
I am unable to create an account. and there is a weird thing whenever I hit submit button on the page it pops <FallbackStorage: request=<WSGIRequest: GET ''>> instead of the message that I had setup when error occurs.
Screenshot of error message
jobSeekerSignup.html
{%extends 'navbar.html'%}
{%block content%}
{%if messages%}
{% for message in messages%}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
{{messages}}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{%endfor%}
{%endif%}
<div class="container login-container">
<div class="row">
<div class="col-md-6">
<h3>Create an account with us!! </h3>
<form action="" method="post">
{%csrf_token%}
<div class="row">
<div class="form-group col-lg-6">
{{form.first_name}}
</div>
<div class="form-group col-lg-6">
{{form.last_name}}
</div>
</div>
<div class="form-group">
{{form.username}}
</div>
<div class="form-group">
{{form.email}}
</div>
<div class="form-group">
{{form.streetAddress}}
</div>
<div class="row">
<div class="form-group col-lg-6">
{{form.suburb}}
</div>
<div class="form-group col-lg-6">
{{form.postcode}}
</div>
</div>
<div class="form-group">
{{form.phoneNumber}}
</div>
<div class="form-group">
{{form.resume}}
</div>
<div class="form-group">
{{form.password1}}
</div>
<div class="form-group">
{{form.password2}}
</div>
<div class="form-group">
<input type="submit" class="btn btnSubmit btn-primary" value="Sign up" />
</div>
<div class="form-group">
<p>Already user? Log in</p>
</div>
</form>
</div>
</div>
</div>
{%endblock content%}
Could you help with this??

{%if messages%}
{% for message in messages%}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
**{{messages}}**
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{%endfor%}
{%endif%}
Here in the code, you are using {{messages}} instead of {{message}}, so that was it you will see your code working.

Related

Getting the error: This field is required when update user

I'm trying to update a user profile using two forms the problem is that when I click to update I get the following error:
“<ul class="errorlist">
<li>username<ul class="errorlist"><li>This field is required.</li>
</ul>
”
My model module is the following:
# user.models
from django.contrib.auth.models import AbstractUser
from django.db import models
from model_utils.models import TimeStampedModel
from localflavor.br.models import BRPostalCodeField, BRStateField, BRCNPJField, BRCPFField
class User(AbstractUser):
class Roles(models.IntegerChoices):
SUPER = 0
COMPANY = 1
UNITY = 2
STAFF = 3
picture = models.ImageField(blank=True, null=True)
role = models.IntegerField(choices=Roles.choices, default=Roles.STAFF)
class Staff(TimeStampedModel):
user: User = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
unity = models.ForeignKey(Unity, related_name="staff", on_delete=models.CASCADE)
cpf = BRCPFField("CPF")
class Meta:
verbose_name: str = 'Staff'
verbose_name_plural: str = 'Staff'
ordering = ("-created",)
def __str__(self):
if f"{self.user.first_name} {self.user.last_name}".strip():
return f"{self.user.first_name} {self.user.last_name}"
return str(self.user.username)
And my user forms looks like:
#user.forms
class UserModelForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'is_active']
class StaffModelForm(forms.ModelForm):
class Meta:
model = Staff
fields = ['cpf', 'unity']
widget = {
'cpf': forms.TextInput(attrs={'class': "form-control", 'placeholder': 'Primeiro Nome', }),
'unity': forms.EmailInput(attrs={'class': "form-control", 'placeholder': 'meu#email.com', }),
}
with the following view:
#views
…
def update_staff(request: HttpRequest, pk: int) -> HttpResponse:
instance: Staff = get_object_or_404(Staff, pk=pk) # get staff instance
template_name = 'pages/staff_update_form.html' # use this template
if request.method == "POST":
profile_form = user_forms.StaffModelForm(request.POST, instance=instance)
user_form = user_forms.UserModelForm(request.POST, request.FILES, instance=instance.user)
print(user_form.is_valid())
print(user_form.errors)
print(profile_form.is_valid())
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, 'Your profile is updated successfully')
return redirect(to='pages:dashboard')
context = dict(profile_form=user_forms.StaffModelForm(instance=instance),
user_form=user_forms.UserModelForm(instance=instance.user))
return render(request, template_name=template_name, context=context)
Print output:
False
<ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul
></li></ul>
True
and HTML:
{% load crispy_forms_tags %}
{% if user_form.errors %}
<div class="alert alert-danger alert-dismissible" role="alert">
<div id="form_errors">
{% for key, value in user_form.errors.items %}
<strong>{{ value }}</strong>
{% endfor %}
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
<div class="py-5 text-center">
<span class="material-icons" style="height: 48px; width: auto; font-size: 48px;">people_alt</span>
<h1 class="h3 mb-3 fw-normal">Atualize aqui os dados do usuário!</h1>
</div>
<form class="form-signin" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="row g-8 my-auto mx-auto" style="padding-left: 12%; padding-right: 12%;">
<div class="col-md-8 col-lg-12">
{% crispy profile_form %}
</div>
</div>
<div class="row g-8 my-auto mx-auto" style="padding-left: 12%; padding-right: 12%;">
<div class="col-md-8 col-lg-12">
{% crispy user_form %}
</div>
</div>
<div class="col-md-12 col-lg-12">
<br>
<div class="modal-footer">
Cancel
<button class="btn btn-primary mb-2" type="submit">Update</button>
</div>
</div>
</div>
</form>
<div class="py-5 text-center">
<p class="mt-5 mb-3 text-muted">© 2022-2023</p>
</div>
So I have no idea what the source of this problem is. Everything seems fine to me, can anyone help me?

Django Boolean Checkbox Input Field printing value='False'

I have a number of Boolean Field checkbox inputs within a form and I have noticed the following Boolean Fields (avaialble, bfbw, asp and tours) are printing a default value of 'False' whilst the remainder of the Boolean Fields (para_athlete, working_with_children) do not.
When the value of False is there I cannot toggle the checkbox between on/off (True/False)
Is there something obvious that I am missing as I am struggling to see any difference between the fields?
Thanks in advance for any help I can get on this.
Below is the code.
Model
athlete_ref = models.CharField(max_length=10, default=1)
athlete_name = models.CharField(max_length=80)
email = models.EmailField()
phone_number = models.CharField(max_length=120)
home = models.CharField(max_length=120)
education = models.CharField(max_length=120)
sport = models.CharField(max_length=120, choices=sports, default='Shooting')
notes = models.TextField()
gender = models.CharField(max_length=120, choices=genders, default='Not Specified')
para_athlete = models.BooleanField(blank=True)
working_with_children = models.BooleanField(blank=True)
expiry_date = models.DateField(blank=True, null=True)
available = models.BooleanField(blank=True)
available_from = models.DateField(blank=True, null=True)
bfbw = models.BooleanField(blank=True)
latest_bfbw_session = models.DateField(blank=True, null=True)
number_bfbw_sessions = models.CharField(blank=True, null=True, max_length=10)
asp = models.BooleanField(blank=True)
latest_asp_session = models.DateField(blank=True, null=True)
number_asp_sessions = models.CharField(blank=True, null=True, max_length=10)
tours = models.BooleanField(blank=True)
latest_tours_session = models.DateField(blank=True, null=True)
number_tours_sessions = models.CharField(blank=True, null=True, max_length=10)
Form
class EditAthleteForm(forms.ModelForm):
class Meta():
model = Athlete
fields = ('__all__')
widgets = {
'athlete_ref': TextInput(attrs={'id':'athlete_ref', 'name': 'athlete_ref', 'hidden': 'hidden'}),
'athlete_name': TextInput(attrs={'class': 'form-control', 'id': 'edit_athlete_name', 'name': 'edit_athlete_name', 'placeholder': 'John Doe'}),
'email': TextInput(attrs={'class': 'form-control', 'id': 'edit_athlete_email', 'name': 'edit_athlete_email', 'placeholder': 'name#example.com'}),
'phone_number': TextInput(attrs={'class': 'form-control', 'id': 'edit_athlete_phone_number', 'name': 'edit_athlete_phone_number', 'placeholder': '0400 000 000', 'pattern': '^((\+61\s?)?(\((0|02|03|04|07|08)\))?)?\s?\d{1,4}\s?\d{1,4}\s?\d{0,4}$'}),
'home': TextInput(attrs={'class': 'form-control', 'id': 'edit_athlete_home', 'name': 'edit_athlete_home', 'placeholder': 'Home Address'}),
'education': TextInput(attrs={'class': 'form-control', 'id': 'edit_athlete_education', 'name': 'edit_athlete_education', 'placeholder': 'Education'}),
'sport': Select(attrs={'class': 'form-select', 'id': 'edit_athlete_sports', 'name': 'edit_athlete_sports'}),
'notes': Textarea(attrs={'class': 'form-control', 'id': 'edit_athlete_notes', 'name': 'edit_athlete_notes'}),
'gender': Select(attrs={'class': 'form-select', 'id': 'edit_athlete_gender', 'name': 'edit_athlete_gender'}),
'para_athlete': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'edit_athlete_para_athlete', 'name': 'edit_athlete_para_athlete'}),
'working_with_children': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'edit_athlete_wwc_input', 'name': 'edit_athlete_wwc_input'}),
'expiry_date': DateInput(attrs={'type': 'date','class': 'form-control', 'id': 'edit_athlete_expiry_datepicker', 'name': 'edit_athlete_expiry_datepicker'}),
'available': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'edit_athlete_available_input', 'name': 'edit_athlete_available_input'}),
'available_from': DateInput(attrs={'type': 'date','class': 'form-control', 'id': 'edit_athlete_datepicker', 'name': 'edit_athlete_datepicker'}),
'bfbw': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'edit_athlete_bfbw_input', 'name': 'edit_athlete_bfbw_input'}),
'latest_bfbw_session': DateInput(attrs={'type': 'date','class': 'form-control', 'id': 'edit_athlete_bfbw_datepicker', 'name': 'edit_athlete_bfbw_datepicker'}),
'number_bfbw_sessions': TextInput(attrs={'class': 'form-control', 'id': 'edit_athlete_bfbw_number_input', 'name': 'edit_athlete_bfbw_number_input'}),
'asp': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'edit_athlete_asp_input', 'name': 'edit_athlete_asp_input'}),
'latest_asp_session': DateInput(attrs={'type': 'date','class': 'form-control', 'id': 'edit_athlete_asp_datepicker', 'name': 'edit_athlete_asp_datepicker'}),
'number_asp_sessions': TextInput(attrs={'class': 'form-control', 'id': 'edit_athlete_asp_number_input', 'name': 'edit_athlete_asp_number_input'}),
'tours': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'edit_athlete_tour_input', 'name': 'edit_athlete_tour_input'}),
'latest_tours_session': DateInput(attrs={'type': 'date','class': 'form-control', 'id': 'edit_athlete_tour_datepicker', 'name': 'edit_athlete_tour_datepicker'}),
'number_tours_sessions': TextInput(attrs={'class': 'form-control', 'id': 'edit_athlete_tour_number_input', 'name': 'edit_athlete_tour_number_input'}),
View
def update_athlete(request):
if request.method == 'POST':
athlete_ref_id = request.POST.get('athlete_ref')
ath_data = Athlete.objects.get(id=athlete_ref_id)
ath_data.athlete_name = request.POST['athlete_name']
ath_data.email = request.POST['email']
ath_data.home = request.POST['home']
ath_data.education = request.POST['education']
ath_data.sport = request.POST['sport']
ath_data.notes = request.POST['notes']
ath_data.gender = request.POST['gender']
ath_data.para_athlete = request.POST.get('para_athlete') == 'on'
ath_data.working_with_children = request.POST.get('working_with_children') == 'on'
ath_data.expiry_date = request.POST.get('expiry_date')
ath_data.available = request.POST.get('available') == 'on'
ath_data.available_from = request.POST.get('available_from')
ath_data.bfbw = request.POST.get('bfbw') == 'on'
ath_data.latest_bfbw_session = request.POST.get('latest_bfbw_session')
ath_data.number_bfbw_sessions = request.POST.get('number_bfbw_sessions')
ath_data.asp = request.POST.get('asp') == 'on'
ath_data.latest_asp_session = request.POST.get('latest_asp_session')
ath_data.number_asp_sessions = request.POST.get('number_asp_sessions')
ath_data.tours = request.POST.get('tours') == 'on'
ath_data.latest_tours_session = request.POST.get('latest_tours_session')
ath_data.number_tours_sessions = request.POST.get('number_tours_sessions')
ath_data.save()
print(ath_data.available)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
HTML
<!-- EDIT Athlete Modal -->
<form method="post" action="update_athlete/" id="edit_athlete_form">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.source.errors }}
{{ form.source }}
<div class="modal fade" id="edit_athlete_modal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header card-header">
<h5 class="modal-title"><i class="fa fa-pencil mx-1"></i> Edit Athlete Details</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="card text-dark bg-light mb-3">
<div class="card-body">
<div class="form-floating mb-3">
{{edit_ath_form.athlete_name}}
<label for="edit_name">Name & Last Name</label>
</div>
<div class="form-floating mb-3">
{{edit_ath_form.email}}
<label for="edit_email">Email address</label>
</div>
<div class="form-floating mb-3">
{{edit_ath_form.phone_number}}
<label for="edit_athlete_phone_number">Phone number</label>
</div>
<div class="form-floating mb-3">
{{edit_ath_form.home}}
<label for="edit_home">Home</label>
</div>
<div class="form-floating mb-3">
{{edit_ath_form.education}}
<label for="edit_education">Education</label>
</div>
<div class="form-floating mb-3">
{{edit_ath_form.sport}}
<label for="edit_sports">Sports</label>
</div>
<div class="form-floating mb-3">
{{edit_ath_form.notes}}
<label for="edit_notes">Notes</label>
</div>
<div class="form-floating mb-3">
{{edit_ath_form.gender}}
<label for="edit_gender">Gender</label>
</div>
<div class="form-check form-switch">
{{edit_ath_form.para_athlete}}
<label class="form-check-label" for="edit_athlete_para_athlete">Para athlete</label>
</div>
</div>
</div>
<div class="card text-dark bg-light mb-3">
<div class="card-body">
<div class="form-check form-switch">
{{edit_ath_form.working_with_children}}
<label class="form-check-label" for="edit_athlete_wwc_input">Has WWC</label>
</div>
<div class="form-floating mb-3">
{{edit_ath_form.expiry_date}}
<label for="edit_athlete_expiry_datepicker">Expires on</label>
</div>
<div class="form-check form-switch">
{{edit_ath_form.available}}
<label class="form-check-label" for="edit_athlete_available_input">Available</label>
</div>
<div class="form-floating mb-3">
{{edit_ath_form.available_from}}
<label for="edit_athlete_datepicker">Available from</label>
</div>
<div class="form-check form-switch">
{{edit_ath_form.bfbw}}
<label class="form-check-label" for="edit_athlete_bfbw_input">BFBW</label>
</div>
<div class="row">
<div class="col-6">
<div class="form-floating mb-3">
{{edit_ath_form.latest_bfbw_session}}
<label for="edit_athlete_bfbw_datepicker">Latest BFBW Session</label>
</div>
</div>
<div class="col-6">
<div class="form-floating mb-3">
{{edit_ath_form.number_bfbw_sessions}}
<label for="edit_athlete_bfbw_number_input">Number of BFBW Sessions</label>
</div>
</div>
</div>
<div class="form-check form-switch">
{{edit_ath_form.asp}}
<label class="form-check-label" for="edit_athlete_asp_input">ASP</label>
</div>
<div class="row">
<div class="col-6">
<div class="form-floating mb-3">
{{edit_ath_form.latest_asp_session}}
<label for="edit_athlete_asp_datepicker">Latest ASP Session</label>
</div>
</div>
<div class="col-6">
<div class="form-floating mb-3">
{{edit_ath_form.number_asp_sessions}}
<label for="edit_athlete_asp_number_input">Number of ASP Sessions</label>
</div>
</div>
</div>
<div class="form-check form-switch">
{{edit_ath_form.tours}}
<label class="form-check-label" for="edit_athlete_tour_input">VIS Tours</label>
</div>
<div class="row">
<div class="col-6">
<div class="form-floating">
{{edit_ath_form.latest_tours_session}}
<label for="edit_athlete_tour_datepicker">Latest VIS Tour</label>
</div>
</div>
<div class="col-6">
<div class="form-floating mb-3">
{{edit_ath_form.number_tours_sessions}}
<label for="edit_athlete_tour_number_input">Number of Tours</label>
</div>
</div>
</div>
</div>
</div>
</div>
{{edit_ath_form.athlete_ref}}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="save_edit_athlete">Save Changes</button>
</div>
</div>
</div>
</div>
</form>
<!-- END EDIT Athlete Modal -->
Fixed - Was a issue with JavaScript adding the false value.

Issue with CreateView ,object not created in model on submit

I have issue might missed something , i have created CreateView view for submitting objects in db , all seems to ok , but when i try to submit i don't get anything happen no error at all except
"POST /create_task/ HTTP/1.1" 200 12972 ,
MY code goes as follows , please advice
Thanks
models.py
class MainTask(models.Model):
task_title = models.CharField(max_length=200)
global_task_info = models.TextField(max_length=500,default=None)
complete = models.BooleanField(default=False)
overall_precent_complete = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(default=datetime.datetime.now())
updated_at = models.DateTimeField(default=datetime.datetime.now())
due_date = models.DateTimeField(default=datetime.datetime.now())
task_location = models.CharField(max_length=400, blank=True, null=True)
global_task_assign = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="global_task_assign",default=1)
TASK_STATUS_CHOICES = [
('ST', 'STARTED'),
('NS', 'NOT STARTED'),
('IP', 'IN PROGRESS'),
('PA', 'PAUSED'),
('CO', 'COMPLETED'),
]
task_status = models.CharField(max_length=2,choices=TASK_STATUS_CHOICES,default='NOT STARTED')
def __str__(self):
return self.task_title
forms.py
class TaskCraetionForm(forms.ModelForm):
TASK_STATUS_CHOICES = [
('ST', 'STARTED'),
('NS', 'NOT STARTED'),
('IP', 'IN PROGRESS'),
('PA', 'PAUSED'),
('CO', 'COMPLETED'),
]
task_title = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Task Title'}))
global_task_info = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Task Description'}))
due_date = forms.DateTimeField(widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
global_task_assign = forms.ModelChoiceField(queryset= UserProfile.objects.all(), widget=forms.Select(attrs={'class':'form-control'} ))
task_status = forms.ChoiceField(label='', choices=TASK_STATUS_CHOICES, widget=forms.Select(attrs={'class':'form-control'}))
class Meta:
model = MainTask
fields = ['task_title',
'global_task_info',
'due_date',
'global_task_assign',
'task_status',
]
views.py
class CreatTaskView(CreateView):
model = MainTask
template_name = "create_newtask.html"
form_class = TaskCraetionForm
success_url = None
def form_valid(self, form):
f = form.save(commit=False)
f.save()
return super(CreatTaskView, self).form_valid(form)
Thank you very much Alasdair you're comment gave me the direction and more added the following to my HTML template shown below and found out i have issue with my datetime picker format needed to added the following
Thanks
INPUTֹTIMEֹFORMATS = [
'%Y/%m/%d %H:%M']
due_date = forms.DateTimeField(input_formats=INPUTֹTIMEֹFORMATS, widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
html temaplate
<form action="" method="POST">
<h3 class="mt-3 text-left">Create New Task</h3>
<hr>
<p class="text-muted text-left">Creat New Itom task</p>
{% csrf_token %}
{% if form.errors %}
<!-- Error messaging -->
<div id="errors">
<div class="inner">
<p>There were some errors in the information you entered. Please correct the following:</p>
<ul>
{% for field in form %}
{% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
{% endfor %}
</ul>
</div>
</div>
<!-- /Error messaging -->
{% endif %}
<div class="input-group mt-3 mb-3 mr-auto">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-book-medical"></i></span>
</div>
{{ form.task_title}}
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-pen"></i></span>
</div>
{{form.global_task_info}}
</div>
<!---date time picker-->
<h6 class="text-left">Task Due Date</h6>
<div class="input-group date mb-3 col-3">
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
{{ form.due_date }}
</div>
<!--end of date time picker-->
<!---user assign-->
<h6 class="text-left">Assign Task to IT member</h6>
<div class="input-group mb-3 mt-3 col-8">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-user-tie"></i></div>
{{form.global_task_assign}}
</div>
</div>
<!--End Of User Assign-->
<h6 class="text-left">Set Task Status</h6>
<div class="input-group mb-3 mt-3 col-4">
<div class="input-group-prepend">
<div class="input-group-text"><i class="far fa-caret-square-right"></i></div>
</div>
{{form.task_status}}
</div>
<div class="col text-left">
<button type="submit" value="Save" class="btn btn-primary btn-lg text-white mt-2"><span><i class="fas fa-database"></i></span> Create Task</button>
</div>
</form>
</div>
</div>

Unusual behavior of form during the creation of a blog post

I'm developing the backend of my personal blog and, using this tutorial for the date and time, I've created a form for the creation of a blog post.
Even if I select one or more tags, they aren't added to the post. The post after the pubblication using this form doesen't have tags. But if I do the same thing via django admin I can't create a post without the tags.
create_post.html
<form class="" method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<div class="form-group mb-4">
<div>{{ form.title }}</div>
<label for="id_title">
<span class="text-info" data-toggle="tooltip" title="{{ form.title.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.title.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.description }}</div>
<label for="id_description">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.description.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.description.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.contents }}</div>
<label for="id_contents">
<span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.contents.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.contents.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div>{{ form.header_image_link }}</div>
<label for="id_header_image">
<span class="text-info" data-toggle="tooltip" title="{{ form.header_image_link.help_text|safe }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.header_image_link.errors }}</small>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="form-group mb-4">
<div class=""><h4>{{ form.post_category.label }}</h4></div>
<div>{{ form.post_category }}</div>
<label for="id_category">
<span class="text-info" data-toggle="tooltip" title="{{ form.post_category.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.post_category.errors }}</small>
</label>
</div>
<div class="form-group mb-4">
<div class=""><h4>{{ form.post_tag.label }}</h4></div>
<div>{{ form.post_tag }}</div>
<label for="id_tag">
<span class="text-info" data-toggle="tooltip" title="{{ form.post_tag.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.post_tag.errors }}</small>
</label>
</div>
<div class="form-inline mb-4 py-0">
<div class="input-group mx-1">
<label for="id_highlighted">{{ form.highlighted.label }}</label>
<div class="ml-1">{{ form.highlighted }}</div>
</div>
<div class="input-group mx-1">
<label for="id_draft">{{ form.draft.label }}</label>
<div class="ml-1">{{ form.draft }}</div>
</div>
</div>
<div class="form-group mb-4">
<div class=""><h4>{{ form.publishing_date.label }}</h4></div>
<div class="input-group date" data-target-input="nearest">
{{ form.publishing_date }}
<div class="input-group-append" data-target="#publishing_date_field" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
<label for="publishing_date_field">
<span class="text-info" data-toggle="tooltip" title="{{ form.publishing_date.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.publishing_date.errors }}</small>
</label>
<script>
$(function () {
$("#publishing_date_field").datetimepicker({
format: 'DD/MM/YYYY HH:mm',
});
});
</script>
</div>
<div class="form-group mb-4">
<div class=""><h4>{{ form.author.label }}</h4></div>
<div>{{ form.author }}</div>
<label for="id_author">
<span class="text-info" data-toggle="tooltip" title="{{ form.author.help_text }}">
<i class="far fa-question-circle"></i>
</span>
<small class="text-danger">{{ form.author.errors }}</small>
</label>
</div>
</div>
</div>
</div>
<hr>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<input type="submit" class="btn btn-info shadow" value="Pubblica">
</div>
</div>
</form>
forms.py
class BlogPostForm(forms.ModelForm):
title = forms.CharField(
max_length=70,
help_text="<small>Write post title here. The title must be have max 70 characters.</small>",
widget=forms.TextInput(
attrs={
"placeholder": "Titolo",
"type": "text",
"id": "id_title",
"class": "form-control form-control-lg",
}
),
)
description = forms.CharField(
max_length=200,
help_text="<small>Write a post short description here. The description must be have max 200 characters.</small>",
widget=forms.Textarea(
attrs={
"placeholder": "Descrizione",
"type": "text",
"id": "id_description",
"class": "form-control",
"rows": "2",
}
),
)
contents = forms.CharField(
help_text="<small>Write your contents here.</small>",
widget=forms.Textarea(
attrs={
"placeholder": "Contenuti",
"type": "text",
"id": "id_contents",
"class": "form-control",
"rows": "20",
}
),
)
publishing_date = forms.DateTimeField(
input_formats=['%d/%m/%Y %H:%M'],
label="Data di pubblicazione",
help_text="<small>Write data and hour of publication. You can use also a past or a future date.</small>",
widget=forms.DateTimeInput(
attrs={
"id": "publishing_date_field",
'class': 'form-control datetimepicker-input',
'data-target': '#publishing_date_field',
}
),
)
draft = forms.BooleanField(
label="Bozza",
widget=forms.CheckboxInput(
attrs={
"type": "checkbox",
"id": "id_draft",
"class": "form-check-input mx-2",
}
),
required=False,
)
author = forms.ModelChoiceField(
label="Autore",
help_text="<small>Select the author.</small>",
widget= forms.Select(
attrs={
"id": "id_author",
"class": "custom-select",
}
),
empty_label=" ",
queryset= User.objects.all(),
)
post_tag =forms.ModelMultipleChoiceField(
label="Tag",
help_text="<small>Select one or more tags. Press CTRL and click on a tag for multiple selection.</small>",
widget= forms.SelectMultiple(
attrs={
"id": "id_category",
"class": "custom-select",
"size": "4",
}
),
queryset= BlogTag.objects.all(),
)
post_category = forms.ModelChoiceField(
label="Categoria",
help_text="<small>Select a category.</small>",
widget= forms.Select(
attrs={
"id": "id_category",
"class": "custom-select",
}
),
empty_label=" ",
queryset= BlogCategory.objects.all(),
)
header_image_link = forms.CharField(
max_length=1000,
help_text="<small>Past here the image link.</small>",
widget=forms.TextInput(
attrs={
"placeholder": "Url dell'immagine di testata",
"type": "text",
"id": "id_header_image",
"class": "form-control",
}
)
)
highlighted = forms.BooleanField(
label="In evidenza",
widget=forms.CheckboxInput(
attrs={
"type": "checkbox",
"id": "id_highlighted",
"class": "form-check-input mx-2",
}
),
required=False,
)
class Meta:
model = BlogPost
fields = [
"author",
"title",
"description",
"contents",
"header_image_link",
"post_tag",
"post_category",
"highlighted",
"draft",
"publishing_date",
]
models.py
class BlogPost(models.Model):
publishing_date = models.DateTimeField(
default=timezone.now,
blank=True,
)
updating_date = models.DateTimeField(
auto_now=True,
)
timestamp = models.DateTimeField(
auto_now=False,
auto_now_add=True,
)
title = models.CharField(
max_length=70,
unique=True,
)
slug_post = models.SlugField(
max_length=70,
unique=True,
)
description = models.TextField(
max_length=200,
blank=True,
)
contents = models.TextField(
blank=True,
)
draft = models.BooleanField(
default=False,
)
author = models.ForeignKey(
User,
related_name = "author_blogpost",
on_delete=models.CASCADE,
)
highlighted = models.BooleanField(
default=False,
)
header_image_link = models.CharField(
max_length=1000,
)
post_category = models.ForeignKey(
BlogCategory,
related_name = "category_blogpost",
on_delete=models.CASCADE,
)
post_tag = models.ManyToManyField(
BlogTag,
related_name = "tag_blogpost",
)
def __str__(self):
return self.title
class Meta:
ordering = ['-publishing_date']
views.py
def createPost(request):
if request.method == "POST":
form = BlogPostForm(request.POST or None)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug_post = slugify(new_post.title)
new_post.save()
return redirect('blogpost_list')
else:
form = BlogPostForm()
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
def updatePost(request, slug_post=None):
update_post = get_object_or_404(BlogPost, slug_post=slug_post)
form = BlogPostForm(request.POST or None, instance=update_post)
if form.is_valid():
update_post = form.save(commit=False)
update_post.slug_post = slugify(update_post.title)
update_post.save()
return redirect('blogpost_list')
context = {
'form': form,
}
template = 'blog/editing/create_post.html'
return render(request, template, context)
What I've wrong?
Many to many relationships have to be manually set. You can either override your ModelForm's save method, this would mean that you can never use "commit=False"
def save(self, commit=True):
if not commit:
raise Exception('Cannot save many to many fields if the blog post is not committed')
instance = super().save()
instance.post_tag.add(*self.cleaned_data['post_tag'])
return instance
or you can add the tags in your view
if form.is_valid():
update_post = form.save(commit=False)
update_post.slug_post = slugify(update_post.title)
update_post.save()
update_post.post_tag.add(*form.cleaned_data['post_tag'])
return redirect('blogpost_list')

How to display 'auto_now_add' fields in django forms?

I wish to know how to display 'auto_now_add' fields (and as disabled fields) in django frontend forms.
I attach some of relevant code:
# models.py
class ModelA(models.Model):
name = models.CharField('Name', max_length=100)
inserted = models.DateTimeField('Inserted ', auto_now_add=True)
# forms.py
class ProcessModelAForm(forms.ModelForm):
class Meta:
model = ModelA
fields = '__all__'
widgets = {
"name": forms.TextInput({
"class": "form-control",
"disabled": True,
}),
"inserted": forms.DateTimeInput({
"class": "form-control",
"disabled": True,
}),
}
# views.py
def process_model_a(request, pk):
instance_model_a = get_object_or_404(ModelA, id=pk)
process_form = ProcessModelAForm(instance=instance_model_a)
if request.method == 'POST':
# ...
return render(request, 'myapp/process_model_a.html', {'process_form ': process_form , 'instance':instance_model_a , } )
# process_model_a.html
<form method="post" class="form-horizontal">
{% csrf_token %}
{% for field in process_form %}
<div class="form-group form-group-lg">
<label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{field.label}}</label>
<div class="col-sm-6">
{{ field }}
</div>
<div class="col-sm-4">
{{ field.errors }}
</div>
</div>
{% endfor %}
<div class="form-group">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary btn-lg center-block">Process</button>
</div>
</div>
</form>
The page "process_model_a.html" shows only "name" fields.
How can I display also "inserted" field?
Thanks.