Recover data from a Django Form - python

It's my first time doing a Django Form challenge.
The challenge for now is just from a HTML Template get the last_name information and store into DB from views. So I have a scenario below:
models.py:
class Person(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
an HTML template, I will put below only the form part:
<form action="{% url 'store' %}" method="post">
{% csrf_token %}
<div class="form-group row">
<label for="last_name" class="col-sm-2 col-form-label">Last Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="last_name" placeholder="Last Name">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Send Last Name</button>
</div>
</div>
</form>
And the views.py itself... I created a InsertLastName ModelForm to store the data from the form, but didn't work. For some reason, when I tryed to call form.cleaned_data I reveived an error about the is_valid() verification. Seens like that I'm not getting the information from label.
class InsertLastName(forms.ModelForm):
class Meta:
model = Person
fields = ['last_name']
exclude = ['first_name']
def index(request):
persons = Person.objects.all()
context = {'persons': persons}
return render(request, '/index.html', context)
def store(request):
form = InsertLastName(request.POST or None)
print(form.cleaned_data['last_name'])
return HttpResponse("Storing a new Last Name object into storage")
What is the correct way to get the information from last_name label in my form?
I'm following that documentation and coding from a challenge template.

Your just set attr name for your input html tag
Example:
<input type="text" name="first">
And for get input in function store in view.py:
request.POST.get("first")
Add this to your html template in your form
{{persons}}

Related

Show An Alert message Before Submitting the Page Django

I want to create a alert message before submitting the page , my
form.py
class NameForm(forms.ModelForm):
translated_names = TranslationField()
class Meta:
fields = "__all__"
model = models.Name
admin py
class NameAdmin(MasterDataBaseAdmin):
form = forms.NameForm
inlines = [AddressInline, RegistrationTypeInline]
queryset = models.Name.objects.prefetch_related(
"names", "name__id", "registrationstype"
)
views.py
class NameViewSet(viewsets.ReadOnlyModelViewSet):
queryset = models.Country.objects.supported().prefetch_related("names",
"registrationstype")
serializer_class = serializers.NameSerializer
I want to just add this meesage in the Message Box
"Are You Sure You Want To Save The Page!"
Try this in your HTML
<input type="submit" onclick="return confirm('Are you sure?')" />
In your html you probably have something like that
<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" onclick="return confirm('Are you sure?')" />
</form>
onclick="return confirm('Are you sure?')" here is your massage box

Django Form processing files

So I have the following code:
# the view
class UpdateDateView(LoginRequiredMixin, UpdateView):
model = Date
form_class = DateForm
template_name = 'app/form/date_edit_form.html'
def save_photos(self, date) -> None:
photos = self.request.FILES.getlist('photo')
current_photos = self.request.FILES.getlist('custom-photo-name') # this is not working
for photo in photos:
Photo.objects.create(date=date, photo=photo)
def form_valid(self, form):
date = form.save()
self.save_photos(date)
return super().form_valid(form)
# the form
class DateForm(forms.ModelForm):
photo = forms.ImageField(required=False)
class Meta:
model = Date
exclude = ('user',)
# the Edit form
<form action="{% url 'app:edit-date' date.slug %}" method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="form-container">
...
<tr>
<th><label for="id_photo">Image:</label></th>
<td>
<input type="file" name="photo" accept="image/*" id="id_photo" multiple>
</td>
</tr>
<div class="current-photos">
{% for photo in date.photos.all %}
<div class="photo-wrapper-{{ forloop.counter }}">
<img src="{{ photo.photo.url }}" width="200px"><a class="delete-photo" id="{{ forloop.counter }}">Delete</a>
<input type="file" name="custom-photo-name" value="{{ photo }}" class="hide" id="photo_{{ forloop.counter }}">
</div>
{% endfor %}
</div>
</div>
<div class="buttons">
<input type="submit" value="Save" class="create-button redirection no_decoration">
Back
</div>
</form>
# js (jquery)
$('.delete-photo').on('click', function() {
const id = $(this).attr('id');
const div_class = `.photo-wrapper-${id}`;
$(div_class).remove()
});
I have a CreateView and UpdateView. The ImageField is not required, it is optional.
Let's assume I have created a new date with photos. Then I wanted to edit its pictures (delete some and add some new). When I click on tag (Delete), the div wrapper for that photo is being removed. When I try to save my edits, I want to access 2 different lists with photos (ones which were added in the past, and the new photos).
This self.request.FILES.getlist('custom-photo-name') seems to do nothing with current photos. Please help, maybe my code logic is bad in general? What I am missing here? What html form looks for when I submit the form, whether for the tag or maybe name attribute? Huge thanks in advance!

Updating user profile - Django

I've created a template for updating account profiles using a Bootstrap snippet (from https://www.bootdey.com). With the django default format (like {{ form.as_p }}), updating accounts works (for example, when I modify the first name, it changes in the database). When I use the bootstrapp snippet, it doesn't update: it goes straight to 'homepage' without updating (as explained in views.py).
In forms.py
class EditAccountForm(UserChangeForm):
class Meta:
model = Account
fields = ('email','first_name','last_name')
In views.py
def EditProfile(request):
context= {}
if request.POST:
form = EditAccountForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
email = form.cleaned_data.get("email")
raw_password = form.cleaned_data.get("password1")
account = authenticate(email=email,password=raw_password)
return redirect('profile_page')
else:
context['edit_form'] = form
return redirect('homepage')
else:
form = EditAccountForm(instance=request.user)
context['edit_form'] = form
return render(request,'Account/edit_page.html',context)
the template: edit_profile.html (I only show the first_name part as example)
<form method = "POST" class="form" novalidate="">
{% csrf_token %}
<div class="row">
<div class="col">
<div class="row">
<div class="col">
<div class="form-group">
<label>First name</label>
<input class="form-control" type="text" name="firstna" value={{ edit_form.first_name.value }}>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col d-flex justify-content-end">
<button class="btn btn-primary" type="submit">Save Changes</button>
PS: I've preferred to use those snippets instead of the Django style since I find them more attractive and offer more freedom.
Please check you are taking same value if you are changing the data in views like if you are using (name="firstna") in template so for First Name you have to take same in views.
Same question is asked here you can go and follow below link
[How to update user profile in Django

Django save data from forms to database

Hi i am relatively new to Django. I am currently trying to store values into database. Timesheet.html is basically my form and i have tried to do the validation but it doesn't work. I have searched everything i can but the data being filled out wont be saved into database. Is there anywhere to check that the checkbox has been ticked before user can submit it ?
timesheet.html
<form method="POST" onsubmit="return validation()" action="">
{% csrf_token %}
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Student ID: {{timesheet.studentID}}</p>
<input id="sid" type="field" name="studentid">
</div>
</div>
<div class="sub-content">
<div>
<p>Student Name: {{timesheet.studentName}}</p>
<input id="sname" type="field" name="studentname">
</div>
</div>
<div class="sub-content">
<div>
<p>Start Date: {{timesheet.startDate}}</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date: {{timesheet.endDate}}</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>
<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements to continue receiving my scholarship
allowance.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" class="button" name="submit" value="submit" >
</div>
</div>
</div>
</form>
models.py
class Timesheet(models.Model):
studentID = models.CharField("Student ID", max_length=8, primary_key=True, default="")
studentName = models.CharField("Student Name", max_length=500, default="")
startDate = models.DateField("Start Date", max_length=8)
endDate = models.DateField("End Date", max_length=8)
def __str__(self):
return self.studentID
class TimesheetForm(forms.ModelForm):
class Meta:
model = Timesheet
fields = '__all__'
views.py
def timesheet(request):
if request.method == "POST":
form = TimesheetForm(request.POST)
if form.is_valid():
timesheet = form.save(commit=False)
timesheet.studentID = request.POST.get('studentID')
timesheet.studentName = request.POST.get('studentName')
timesheet.startDate = request.POST.get('startDate')
timesheet.endDate = request.POST.get('endDate')
timesheet.save()
return HttpResponseRedirect(reverse('hrfinance/timesheet.html'))
#if the form is not valid, redirect the student to the same page
else:
form = TimesheetForm()
return render(request, 'hrfinance/timesheet.html', {'form': form})
else:
form = TimesheetForm()
return render(request, 'hrfinance/timesheet.html', {'form': form})
There are lots of very strange things here.
Firstly, there is no need to set the fields manually on save. That is exactly what form.save() does in the first place. (And if you ever did need to set something manually, you should always get it from form.cleaned_data rather than request.POST.)
Secondly, you re-instantiate the form if it fails validation. That means that the users can never see the errors that are preventing it from validating.
Thirdly, you should show errors in the template. Along with that, you should let Django itself output your fields so that they are automatically prepopulated when the form is invalid.
Finally, you should add your checkbox as a field on the form, so that it is validated along with everything else.
class TimesheetForm(forms.ModelForm):
checkbox = forms.BooleanField()
class Meta:
model = Timesheet
fields = '__all__'
...
def timesheet(request):
if request.method == "POST":
form = TimesheetForm(request.POST)
if form.is_valid():
timesheet = form.save()
return HttpResponseRedirect(reverse('hrfinance/timesheet.html'))
else:
form = TimesheetForm()
return render(request, 'hrfinance/timesheet.html', {'form': form})
...
<form method="POST" onsubmit="return validation()" action="">
{% csrf_token %}
{{ form.errors }}
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Student ID: {{timesheet.studentID}}</p>
{{ form.studentID }}
</div>
</div>
</div>
.... etc...
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements to continue receiving my scholarship
allowance.</p>
{{ form.checkbox }}
</div>

How to get logged in user id in Django

I am very new in Python and Django. A am trying to make app but I have an issue.
Can anyone help me, please xD
I can't get id of authenticated user...
I tried it in this way, and many other ways...
views.py
class CreateProfile(CreateView):
template_name = 'layout/add_photo.html'
model = Profile
fields = ['image', 'user']
html
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="username"> #Here has to be field filled in with logged in user
<input type="file" name="image">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Save Changes</button>
</div>
</div>
</form>
And when I'm starting app, and want to change/add picture, I can do it for anyone from my database, not only for logged in user.
enter image description here
Thanks for patience and help!
In the Django ClassBasedViews you can get your user's id as self.request.user.id and in your template as {{ user.id }}
To check if someone is authenticated you can use self.request.user.is_authenticated() and in your template {% if user.is_authenticated %} .. {% endif %}
class CreateProfile(CreateView):
template_name = 'layout/add_photo.html'
model = Profile
fields = ['image', 'user']
# For example, if you want to return to a certain user
# profile (which requires url adjustments to take a Primary Key)
def get_success_url(self):
user_id = self.request.user.id # Get user_id from request
return reverse_lazy('git_project:user_profile', kwargs={'id': user_id})

Categories

Resources