views.py
def when(request):
user = request.user
report = Report.objects.get(user=request.user)
reportform = ReportForm(instance=report)
settings = Settings.objects.get(user=request.user)
settingsForm = SettingsForm(instance=settings)
settings=Settings.objects.get(user=2)
if settings.date_format == '0':
date=datetime.datetime.strptime('10/31/2012','%m/%d/%Y').strftime('%d/%m/%Y')
else:
date=datetime.datetime.strptime('31/10/2012','%d/%m/%Y').strftime('%m/%d/%Y')
if request.method == 'POST':
reportform = ReportForm(instance=report,data=request.POST)
if reportform.is_valid():
report = reportform.save(commit=False)
report.user = request.user
report.save()
return redirect('/member/media/')
return render_to_response('incident/when.html',{
'newreport_menu': True,
'form': reportform,
'date':date,
},
context_instance=RequestContext(request))
models.py
class Report(models.Model):
user = models.ForeignKey(User, null=False)
manual_date = models.DateField('Another date', null=True, blank=True)
template.html
{{ form.manual_date }}{{ form.manual_date.errors }}{{ date }}
The above views rendering the hardcoded date values in template as variable.Instead of hardcode is it possible to show the date from manual_date field in models.And how to pass it in reportform.
I think you want this, instead of using hardcoded date use report.manual_date:
if settings.date_format == '0':
date = report.manual_date.strftime('%d/%m/%Y')
else:
date = report.manual_date.strftime('%m/%d/%Y')
Related
I have simple cv upload class for users to upload their resume. it works just fine but when they upload a newer one, the previous wont get deleted.
this is my code:
class ResumeDocument(models.Model):
id = models.AutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
cvfile = models.FileField(upload_to="documents", null=True, validators= [validate_file_extension])
#property
def filename(self):
return os.path.basename(self.cvfile.name)
how can I reach the previous id? id = self.id - 1. something like that.
this is my views:
#login_required
def pdf_resume(request):
if request.method == 'POST':
form = DocumentForm(request.POST,request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('pdf_resume')
if 'delete' in request.GET:
return delete_item(ResumeDocument, request.GET['id'])
else:
form = DocumentForm()
documents = ResumeDocument.objects.filter(user=request.user)
if documents:
form = DocumentForm(instance=documents[0])
context = {
'form':form,
'documents':documents,
}
return render(request, 'reg/pdf_resume.html', context)
and this is also my HTML code:
<form id="document-form" method="POST" enctype="multipart/form-data" action="{% url 'pdf_resume' %}" autocomplete="off" class="ant-form ant-form-horizontal">
{% csrf_token %}
<p>{{ form }}</p>
<div class="ant-row-flex" style="margin-left: -10px; margin-right: -10px;"></div>
<button id="btn_submit" type="submit"
class="ant-btn ant-btn-primary"
ant-click-animating-without-extra-node="false" style="float: left;"><span>upload</span></button>
</form>
One possible solution is to save all uploaded CVs for each user and track the last uploaded CV with field uploaded_on. You may refer to the below high-level example:
class CVFile(models.Model):
file_name = models.CharField(max_length=200)
cv_file = models.FileField(upload_to="documents", null=True, validators=[validate_file_extension])
uploaded_on = models.DateTimeField(default=timezone.now, blank=True)
class ResumeDocument(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
cv_file = models.ForeignKey(CVFile, on_delete=models.CASCADE)
You will need to amend your HMTL and views.py accordingly.
models.py
class ResumeDocument(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
cvfile = models.FileField(upload_to="documents", null=True, validators=
[validate_file_extension])
views.py(i just look is there any resumedocuments for that user if yes so i give him
the form just if he was editing the existing file)
#login_required
def pdf_resume(request):
if request.method == 'POST':
form = DocumentForm(request.POST,request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('pdf_resume')
if 'delete' in request.GET:
return delete_item(ResumeDocument, request.GET['id'])
else:
form = DocumentForm()
documents = ResumeDocument.objects.filter(user=request.user)
if documents:#new
form = DocumentForm(instance=documents[0])
context = {
'form':form,
'documents':documents,
}
return render(request, 'reg/pdf_resume.html', context)
now inside your pdf_resume.html your can just pass the 'form' because you already check if that user has a document or not.
I'm trying to make a booking system (for apartments). The idea is that users can pick a start date and an end date and book the apartment if it isnt alrdy booked.
I have a Reservation model with a "start_date" and a "end_date" that I use to determine the dates for the apartment booking.
Users the JQuery Ui Date Picker (a small calendar) to pick dates. The "unavailable" dates are grayed out.
This is how I did that :
<script type="text/javascript">
var unavailableDates = ['{{ reservation.all.0.start_date|date:"d-m-Y" }}', '{{ reservation.all.0.end_date|date:"d-m-Y" }}'];
console.log(unavailableDates);
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
$(function () {
$("#datepicker").datepicker({
dateFormat: 'MM-dd-yy',
beforeShowDay: unavailable
});
});
</script>
I am using ...
{{ reservation.all.0.start_date|date:"d-m-Y" }}
...to gray out the date in the calendar.
My reservation model looks like this:
class Reservation(models.Model):
apartment = models.ForeignKey(Apartment, related_name='reservations',
on_delete=models.CASCADE, blank=True, null=True)
start_date = models.DateField(blank=True, null=True, unique=True)
end_date = models.DateField(blank=True, null=True, unique=True)
name = models.CharField(default="", max_length=200, unique=True)
def __str__(self):
return self.name
And in my view I have:
def apartment_view(request, apartment_id):
reservation = Reservation.objects.filter(apartment__pk=apartment_id)
apartment = get_object_or_404(Apartment, pk=apartment_id)
context = {'apartment': apartment, }
form = ReservationForm()
if request.method == 'GET':
form = ReservationForm()
elif request.method == 'POST':
form = ReservationForm(request.POST)
if form.is_valid():
reservation = form.save(commit=False)
reservation.apartment = apartment
reservation.save()
form.save()
return HttpResponseRedirect('/booking/')
args = {}
args['form'] = form
args['apartment'] = context
args['reservation'] = reservation
return render(request, 'booking/apartment.html', args)
Since I need my reservations to be filtered to the correct apartment.
My question is, how can I query for ALL dates related to an apartment, both start and end dates ?
So I need all dates for apartment 1, then all dates for apartment2...etc.
I'm not sure how to go on about this, I apologize if the post is confusing.
Thanks !!!
Later edit:
After looking at your JS code you might wanna do something like this in your view:
import itertools
unavailable_dates = apartment.reservations.values_list('start_date', 'end_date')
context['unavailable_dates'] = list(itertools.chain(*unavailable_dates)) # to convert _list_ of tuples to simple list
You can get start/end dates for reservations linked to an apartment like this:
apartment = get_object_or_404(Apartment, pk=apartment_id)
context['appartment_reservations_dates'] = apartment.reservations.values_list('start_date', 'end_date')
If you want to work with the entire Reservation object directly in your HTML template you can do it like this:
{% for reservation in apartment.reservation.all %}
{{ reservation.start_date }} - {{ reservation.end_date }}
{% endfor %}
Your view might look like this:
def apartment_view(request, apartment_id):
context = dict()
context['apartment'] = get_object_or_404(Apartment, pk=apartment_id)
context['reservations'] = apartment.reservations.all() # if you want all existing reservations for this specific appartment
form = ReservationForm()
if request.method == 'GET':
form = ReservationForm()
elif request.method == 'POST':
form = ReservationForm(request.POST)
if form.is_valid(): # you can add extra validation here making sure whoever tries to book is booking for an available time interval
reservation = form.save(commit=False)
reservation.apartment = apartment
reservation.save()
form.save()
return HttpResponseRedirect('/booking/')
context['form'] = form
return render(request, 'booking/apartment.html', args)
I'm using Django. I need a form that shows the 3 fields of a class that I have created, the idea is that every time you want to add a new day and time to start and end, show a new new section, so that each teacher can be found in more of a day and time of beginning and end (the three fields go together)
I still do not logo to make it work, if someone has any idea they would be grateful.
Models.py
class Profesor(Person):
legajo = models.IntegerField(blank=True, null=True)
type = models.CharField(max_length=30)
matter = models.CharField(max_length=100, blank=True, null=True)
calendar = models.ForeignKey('calendar', on_delete=models.DO_NOTHING)
user = models.CharField(max_length=20, blank=True, null=True)
class calendar(models.Model):
day = models.DateTimeField(default=date.today().isoweekday())
hs_init = models.DateTimeField(default=datetime.now().hour)
hs_end = models.DateTimeField(default=datetime.now().hour)
Forms.py
class addProfesorForm(ModelForm):
calendar = forms.ModelChoiceField(queryset=calendar.objects.all(), widget=forms.HiddenInput())
class Meta:
model = Profesor
TYPES = (
('Motiv', 'Motiv'),
('Academic', 'Académic'),
('Otro', 'Otro')
)
help_texts = {
'matter': 'message'
}
fields = ['id', 'type', 'matter']
widgets = {
'type': Select2Widget(choices=typeS)
}
class calendarForm(ModelForm):
class Meta:
model = calendar
fields = ['day','hs_init','hs_end']
Views.py
def agregarTutor(request):
if request.method == 'POST':
form = addProfesorForm(request.POST['calendar'])
calendar=calendar.objects.all()[0]
if form.is_valid():
id = form.cleaned_data['id']
try:
person_Sysatem = SysatemPerson.objects.get(pk=id)
alumn_Sysatem = SysatemAlumn.objects.get(pk=id)
except SysatemPerson.DoesNotExist:
return render(request, 'menu/new-Profesor.html',
{'new_manual': True, 'not_found': True, 'nbar': 'profesors', 'id': id})
new_Profesor = Profesor(
nombre=person_Sysatem.nombre.rstrip(),
id=person_Sysatem.numerodocu,
legajo=alumn_Sysatem.legajo,
telefono=person_Sysatem.telefono.rstrip(),
mail=person_Sysatem.mail.rstrip(),
type=form.cleaned_data['type'],
calendar=form.cleaned_data['calendar'],
matter=form.cleaned_data['matter'],
user=id,
)
Profesor.save(new_Profesor)
contrasena = 'id'+str(id)[0:5]
user = User.objects.create_user(id, person_Sysatem.mail.rstrip(), contrasena)
user.first_name = person_Sysatem.nombre.rstrip()
user.save()
form = addProfesorForm(initial={'calendar':calendar})
return render(request, 'menu/new-Profesor.html', {'form': form, 'Profesor': new_Profesor, 'success': True, 'nbar': 'profesors'})
else:
return render(request, 'menu/new-Profesor.html', {'form': form, 'error_form': True, 'nbar': 'profesors'})
else:
form = addProfesorForm()
return render(request, 'menu/new-Profesor.html', {'form': form, 'nbar': 'profesors'})
Template.html
<h2>new Profesor</h2>
<div class="row">
<div class="col">
<form method="post">{% csrf_token %}
{% include 'common/form_template.html' with form=form %}
<button type="submit" style="margin-top: 10px; float: right;" class="btn btn-primary">Add</button>
</form>
</div>
</div>
I have a website which allows Users to pick a few hobbies they enjoy. Currently the website loads these hobbies from a Model and lists them with a Checkbox. What I want to do is when a User saves the form, it should also save these Checkbox values to the database - i.e if they tick Football, the database should save the fact that this User enjoys football. I am new to Django and Python so not too sure how to accomplish this. Here is the code I am using. This is the Models.py file for the Hobbies:
TYPES = (
("Football", "Football"),
("Cricket", "Cricket"),
("Swimming", "Swimming"),
("Cycling", "Cycling")
)
class Hobby(models.Model):
myfield = models.CharField(max_length=50, choices = TYPES, default=TYPES[0], null=True)
football = models.BooleanField(default = False)
cricket = models.BooleanField(default = False)
swimming = models.BooleanField(default = False)
cycling = models.BooleanField(default = False)
This is the relevant views.py file:
def profile(request, user):
# use this for debugging:
# import pdb; pdb.set_trace()
if 'email' in request.POST:
email = request.POST['email']
gender = request.POST['gender']
dob = request.POST['dob']
## hobby = request.POST['hobby']
if user.profile:
user.profile.email = email
user.profile.gender = gender
user.profile.dob = dob
## user.profile.hobby = hobby
user.profile.save()
else:
profile = Profile(email=email, gender=gender, dob=dob)
profile.save()
user.profile = profile
user.save()
context = {
'appname': appname,
'username': user.username,
'profile' : user.profile,
'all_hobbies': [hobby[0] for hobby in TYPES],
'loggedin': True
}
return render(request, 'mainapp/profile.html', context)
And lastly the HTML/JS code to display the information:
<span class="fieldname">Hobbies</span>
{% for hobby in all_hobbies %}
<input type="checkbox" name={{hobby}} value={{hobby}}> {{hobby}}<br>
{% endfor %}
<input type='submit' value='Save'>
What I want is a way to check whether the checkboxes have been ticked, and if so to change the value of the BooleanField in the database/model to either True or False. However, I am not sure where to do this, in the views or the JS code. Can someone help me out here? Many thanks.
For this case to list all hobbies and update them again. You need to use a Form Class. Example. I just want to mention a single thing, the code below its just a guideline of what you should do. Because Its kind of confusing the logic you want to approach. Since you are not handleing a user as a session but just a plain key.
model.py
my_choices = (
(0, "None"),
(1, "Football"),
(2, "Cricket"),
(3, "Swimming"),
(4, "Cycling"),
)
class Hobby(models.Model):
user = models.ForeignKey(Profile, on_delete=models.DO_NOTHING)
field = models.integerField(choices=my_choices, default=0)
forms.py
class HobbyForm(ModelForm):
class Meta:
model = Hobby
fields = ["field"]
views.py
def profile(request,user):
try:
profile_object = Profile.get(id=user)
if request.method.POST:
form = HobbyForm(request.POST)
if form.is_valid():
profile_object.field = form.cleaned_data["field"]
profile_object.save()
context = {
"form": form,
"profile": profile_object,
}
return render(request, 'mainapp/profile.html', context)
else:
context = {
"form": form,
"profile": profile_object,
}
return render(request, 'mainapp/profile.html', context)
else:
context = {
"form": form,
"profile": profile_object,
}
return render(request, 'mainapp/profile.html', context)
except Profile.DoesNotExists:
context = {
"form": form,
"profile": profile_object,
}
return render(request, 'mainapp/profile.html', context)
profile.html
<form action="myurl/{{profile.id}}/" method="post">
{% csrf_token %}
{% form.as_p %}
<input type="submit" value="OK">
</form>
I want to save a leave in database applied from employee but when i was submit i faced this error ----LeaveApplyForm' object has no attribute 'save'---
**models.py**
class All_Leaves(models.Model):
leave_types = models.ForeignKey(Leave_Types, on_delete=models.CASCADE, related_name="all_leave")
user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name="all_leave")
reason = models.CharField(('Reason'), max_length=120)
start_date = models.DateTimeField(('Start Date'),auto_now = True)
end_date = models.DateTimeField(('End Date'),auto_now = True)
class Meta:
verbose_name = ("All Leave")
verbose_name_plural = ("All Leaves")
**View.py**
def apply_leave(request):
print("user",request.user)
print("data",request.POST)
leave_type_data = Leave_Types.objects.all()
if request.method =="POST":
form = LeaveApplyForm(request.POST, None)
print("form status",form.is_valid())
if form.is_valid():
form.save(leave_types=request.POST['leave_types'], user=request.user)
print("form in")
return render(request, 'dashboard.html',{"var_leave":"false","leave_type_data":leave_type_data})
else:
print("form errors",form.errors)
return render(request, 'dashboard.html',{"var_leave":"false","leave_type_data":leave_type_data,"form":form})
forms.py
class LeaveApplyForm(forms.Form):
start_date = forms.DateTimeField(required=True, error_messages={'required': 'Please Choose Start Date.'})
end_date = forms.DateTimeField(required=True, error_messages={'required': 'Please Select End Date.'})
reason = forms.CharField(required=True, error_messages={'required': 'Please Enter Your Reason.'})
class Meta:
model = All_Leaves
fields = ('start_date','end_date','reason')
You've inherited from forms.Form instead of forms.ModelForm.