Getting the error: This field is required when update user - django

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?

Related

django form errors not showing on template

I'm using the basic django registration form and I'm not getting any errors displayed. I've seen a bunch of answers and nothing is working for me. I'm not sure if it's because I have custom css for the page or bootstrap or something else. Basically how do I display the errors in this particular case.
Here's my form:
<div class="form-content">
<h1>Sign Up</h1>
{% if user.is_authenticated == False %}
<form method="POST">
{% csrf_token %} {{form.as_p}}
<button class="btn form-btn">Sign Up</button>
<h4><span>or</span></h4>
<a
class="btn google-btn"
href="{% provider_login_url 'google' %}"
role="button"
style="text-transform: none; width: 100%"
>
<img
width="20px"
style="margin-bottom: 3px; margin-right: 5px"
alt="Google sign-in"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png"
/>
Sign up with Google
</a>
</form>
{% else %}
<p>You're already registered...</p>
{% endif %}
</div>
Here's my view:
class UserRegistration(generic.CreateView):
form_class = RegisterForm
template_name = 'registration/registration.html'
def form_valid(self, form):
user = form.save()
form.registration_notification()
login(self.request, user, backend='django.contrib.auth.backends.ModelBackend')
return redirect(self.request.GET.get('next'))
and form:
class RegisterForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
def registration_notification(self):
email = self.cleaned_data['email']
username = self.cleaned_data['username']
if self.is_valid():
registration_notification_task.delay(email, username)
I'm not sure where to return the errors or where to validate the form and no answers for other questions have helped my situation. Now when I submit an invalid form there are no errors the page just doesn't submit. There's not even an error in the network tab so it's probably happening on the html side.
Updating my post following comments below:
**forms.py** (dont forget the import bit)
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ["username", "email", "password1", "password2",]
views.py
def register_user(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
new_user = form.save()
new_user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],)
login(request, new_user)
messages.success(request,("Registration succesful!"))
return HttpResponseRedirect("/home")
else:
form = RegisterForm()
return render(request,'main/registration/register_user.html',{'form':form})
registration template
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-5 mx-auto">
<div id="second">
<div class="myform form ">
<div class="logo mb-3">
<div class="col-md-12 text-center">
<h1 >Signup</h1>
</div>
</div>
<form method="POST" action = "{% url 'register_user' %}" class="form-group">
{% csrf_token %}
{{ form| crispy }}
<div class="col-md-12 text-center mb-3">
<button type="submit" class=" btn btn-block mybtn btn-primary tx-tfm">Let's do it!</button>
</div>
<div class="col-md-12 ">
<div class="form-group">
<p class="text-center">Already have an account?</p>
</div>
</div>
</div>
</form>
</div>
</div>
{% endblock %}

Profile isn't updating or updates aren't showing up in django

I am trying to make a page in django where users can look at their profiles and edit and save the changes, but everytime i click on the save button, nothing happens and when I refresh the page, the information doesn't get updated. What am I doing wrong?
This is my models.py:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User,null= True ,on_delete= models.CASCADE)
profile_pic = models.ImageField(null = True, blank= True)
first = models.CharField(max_length=500, null=True)
last = models.CharField(max_length=500, null=True)
email = models.CharField(max_length=500, null=True)
mobile_number = models.IntegerField(null=True)
location = models.CharField(max_length= 500, null= True)
postal = models.IntegerField(null=True)
def __str__(self):
return self.first
This is my forms.py:
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = '__all__'
exclude = ['user']
widgets = {
'profile_pic': forms.FileInput()
}
This is my views.py:
#login_required(login_url='Login')
def Profile(request):
profile = request.user.profile
form = ProfileForm(instance=profile)
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILE, instance=profile)
if form.is_valid():
form.save()
return HttpResponseRedirect(reversed('Profile'))
context = {'form': form}
return render(request, 'profile.html', context)
This is my template:
<div class="col-lg middle middle-profile-con">
<div class="img-cir profile-img">
<img src="{{request.user.profile.profile_pic.url}}" alt="" width="100px" height="100px" class="pro-img">
</div>
<form method='POST' action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="">
<p class="my-name-pro">{{request.user.profile.first}}
<p>
<p class="my-email-id-pro">{{request.user.profile.email}} <br> {{form.profile_pic}}</p>
</div>
<div class="">
<div class="pro-fn-div">
<label class="pro-fn-label">First name</label>
<div class="pro-fn-input"> {{form.first}} </div>
</div>
<div class="pro-ln-div">
<label class="pro-fn-label">Last name</label>
<div class="pro-fn-input"> {{form.last}} </div>
</div>
<div class="pro-email-div">
<label class="pro-fn-label">Email ID</label>
<div class="pro-fn-input"> {{form.email}} </div>
</div>
<div class="pro-pn-div">
<label class="pro-fn-label">Phone Number</label>
<div class="pro-fn-input"> {{form.mobile_number}} </div>
</div>
<div class="pro-lo-div">
<label class="pro-fn-label">Location</label>
<div class="pro-fn-input"> {{form.location}} </div>
</div>
<div class="pro-pc-div">
<label class="pro-fn-label">Postal Code</label>
<div class="pro-fn-input"> {{form.postal}} </div>
</div>
<button type="button" name="Update Information" class="btn btn-dark btn-sm pro-btn-save">Save Changes</button>
</form>
</div>
I don't understand where I'm going wrong. Do I need to add something in the template? Maybe in the save button or something?
You forgot to register your url so for example :
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('profile/', views.profile, name="profile"),
]
In your template, edit your form
<form method='POST' action="{% url 'profile' %}" enctype="multipart/form-data">
Note that variable in Python are lowercase, following the convention is best

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>

Trying to Save Multiple Files in Django: didn't return an HttpResponse object. It returned None instead

Please help out. I'm trying to save multiple files in Django using CreateView. But I'm only able to save the last file on the list selected. Then i changed my views to a function view matching most of the explanation i saw in here .. Now i'm getting Value Error.
Below are the two views. The CreateView(CBV) and the function View.
Thanks
CreateView
#method_decorator(login_required, name='dispatch')
class UpdateMatterCreateView(CreateView):
form_class = UpdateMatterForm
model = MatterUpdates
template_name = 'matter/matter_instance_create.html'
success_url = reverse_lazy('matter_list')
def form_valid(self, form):
form = UpdateMatterForm(self.request.POST, self.request.FILES)
with transaction.atomic():
form.instance.client_id = self.kwargs['client_id']
form.instance.firm_id = self.kwargs['firm_id']
form.instance.matter_id = self.kwargs['matter_id']
form.instance.user_id = self.request.user.id
files = self.request.FILES.getlist('files')
for f in files:
docs_path = Documents.objects.create(matter_update_id=self.kwargs['matter_id'], file_path=f)
docs_path.save()
return super(UpdateMatterCreateView, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(UpdateMatterCreateView, self).get_context_data(**kwargs)
context['object'] = Matter.objects.get(id=self.kwargs['matter_id'])
return context
Function Views
def update_matter_instance(request, firm_id, client_id, matter_id):
if request.method == 'POST':
form = UpdateMatterForm(request.POST, request.FILES)
if form.is_valid():
title = form.instance.title
content = form.instance.content
created_date = form.instance.created_date
created_time = form.instance.created_time
matter_update_link = MatterUpdates.objects.create(firm_id=firm_id, client_id=client_id,
matter_id=matter_id, title=title, content=content,
created_date=created_date, created_time=created_time,
user_id=request.user.id, )
matter_update_link.save()
files = request.FILES.getlist('files')
for f in files:
docs_path = Documents.objects.create(matter_update_id=matter_id, file_path=f)
docs_path.save()
return redirect('matter_list')
else:
form = UpdateMatterForm()
return render(request, 'matter/matter_instance_create.html', {'form': form})
forms.py
class UpdateMatterForm(forms.ModelForm):
class Meta:
model = MatterUpdates
exclude = ['matter', 'client', 'firm', 'sys_date', 'user']
widgets = {
'title': forms.TextInput(
attrs={'class': 'form-control', 'placeholder': 'Enter Title'}),
'content': RichTextFormField(),
'created_date': forms.DateInput(
attrs={'class': 'form-control', 'placeholder': 'mm/dd/yyyy'}),
'created_time': forms.TimeInput(
attrs={'class': 'form-control', 'id': 'timepicker2', 'type': 'text'}),
'files': forms.ClearableFileInput(attrs={'multiple': True})
}
urls.py
FUCNTION REGEX
url(r'^legal_stallion/stallion_matter_instance_update/(?P<firm_id>[0-9A-Fa-f-]+)/(?P<client_id>[0-9A-Fa-f-]+)/'
r'(?P<matter_id>[0-9A-Fa-f-]+)/$', views.update_matter_instance, name='update_matter_instance'),
CLASS REGEX
url(r'^legal_stallion/stallion_matter_instance_update/(?P<firm_id>[0-9A-Fa-f-]+)/(?P<client_id>[0-9A-Fa-f-]+)/'
r'(?P<matter_id>[0-9A-Fa-f-]+)/$', views.UpdateMatterCreateView.as_view(), name='update_matter_instance'),
Templates
<form class="cmxform form-horizontal " id="commentForm" method="post" action="#" enctype="multipart/form-data">
{% csrf_token %}
{{ form.errors }}
<div class="form-group " style="margin-bottom: 0px; margin-top: 0px">
<label for="cname" class="control-label col-lg-3">Title <span style="color: darkred">*</span></label>
<div class="col-lg-6">
{{ form.title }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Date <span style="color: darkred">*</span></label>
<div class="col-lg-3">
<div class="input-group date">
{{ form.created_date }}
<span class="input-group-addon"><i class="glyphicon glyphicon-th fa fa-calendar"></i></span>
</div>
</div>
<div class="col-sm-3">
<div class="input-group bootstrap-timepicker timepicker">
{{ form.created_time }}
<span class="input-group-addon"><i class="glyphicon glyphicon-time fa fa-clock-o"></i></span>
</div>
</div>
</div>
<div class="form-group " style="margin-bottom: 0px; margin-top: 0px; margin-bottom: 10px">
<label for="cemail" class="control-label col-lg-3">Content </label>
<div class="col-lg-8">
{{ form.content }}
</div>
</div>
<div class="form-group " style="margin-bottom: 0px; margin-top: 0px; margin-bottom: 10px">
<label for="cemail" class="control-label col-lg-3">Select Files </label>
<div class="col-lg-6">
{{ form.files }}
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-3 col-lg-6">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>

Django pre-filling data in form from URL

So i have a button on my detailView page for my model 'patient', and that takes you to a createView for my other model 'appointment'. What i want is the foreign key field of the appointment to be pre-filled depending on what detailView i come from. Here is my code so far:
urls.py:
# /patients/appointment/add
url(r'appointment/add/$', views.appointmentCreate.as_view(), name='appointment-create'),
models.py:
class patient(models.Model):
TITLE_CHOICES = (
('Mr', 'Mr'),
('Mrs', 'Mrs'),
('Ms', 'Ms'),
('Miss', 'Miss'),
)
Title = models.CharField(max_length=100, blank=True, choices=TITLE_CHOICES)
First_Name = models.CharField(max_length=250, default='')
Surname = models.CharField(max_length=250, default='')
DOB = models.DateField()
class appointment(models.Model):
Patient = models.ForeignKey(patient, on_delete=models.CASCADE)
views.py:
class appointmentCreate(LoginRequiredMixin, CreateView):
model = appointment
fields = ['Patient', 'Date', 'Time', 'Duration', 'Location', 'Clinician', 'AppointmentType']
form-template.html:
<body>
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2">{{ field.label_tag }}</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
</body>
appointment_form.html:
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<h3>Add new appointment</h3>
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'patients/form-template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
The button from the detailView of patient to create appointment:
<ul class="nav nav-pills" style="margin-bottom: 10px;">
<li role="presentation" class="active">View All</li>
<li role="presentation">Add New Appointment</li>
</ul>
For example, the url might be /appname/appointment/add/?Patient=pk , where the end part determines what the value of Patient will be. I have looked into the get_initial function but do not understand how it can help me achieve this. Any help is appreciated. I am relatively new to django so please nothing too complex.
Edit: I have added this code to my model, thanks to Dimitris Kougioumtzis:
def get_context_data(self, **kwargs):
context = super(appointmentCreate, self).get_context_data(**kwargs)
context['patient_id'] = self.request.GET.get('patient')
return context
How do i implement this code?
first you create a modelForm:
from django import forms
from your_app.models import appointment
class AppointmentForm(forms.ModelForm):
class Meta:
model = appointment
fields = ['Patient', 'Date', 'Time', 'Duration', 'Location', 'Clinician', 'AppointmentType']
Then you pass the model form in your CreateView:
class appointmentCreate(LoginRequiredMixin, CreateView):
model = appointment
form_class = AppointmentForm
def get_initial(self):
patient = self.request.GET.get('patient')
return {
'patient': patient,
}
and Your patient choicefield will be populated based on the request get parameter