How to upload PDF files in django - django-media

model
class CustomerInfo(models.Model):
customer_name = models.CharField(max_length=50)
customer_letter= models.FileField(upload_to='/media/',null= True, blank=model
class CustomerInfo(models.Model):
customer_name = models.CharField(max_length=50)
customer_letter= models.FileField(upload_to='/media/',null=True,blank= True)
representative_name = models.CharField(max_length=50)
representative_letter = models.FileField(upload_to='/media/', null=True, blank=True)
ministry_approval = models.FileField(upload_to='/media/', null=True, blank=True)
date = models.DateField()
def __str__(self):
return self.customer_name + ' - ' + self.customer_letter + ' - ' + self.represntative_name + ' - ' + self.representative_letter + ' - ' + self.ministry_approval + ' - ' + self.date
def custmoer(request):
if request.method == 'POST':
form = CustomerForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/login/custmoer/')
else:
return HttpResponseRedirect('/login')
else:
form= CustomerForm()
return render(request, "custmoer.html", {'form':form})
form.py
class CustomerForm(forms.ModelForm):
class Meta:
model = CustomerInfo
fields = ('customer_name', 'customer_letter', 'representative_name', 'representative_letter', 'ministry_approval', 'date')

Related

If the user has this role, so display the message. How to do it? Discord.py

If the user has this role, so display the message.
But nothing works and this is part of my code:
role_girl = 72850048118554 #ID ROLE
role_boy = 72849957361759 #ID ROLE
role_nonepol = 72850091485547 #ID ROLE
#client.command( aliases = [ 'test' ] )
async def __test( ctx, member: discord.Member ):
if role_girl in member.roles:
preff = ' youre a girl '
if role_boy in member.roles:
preff = ' youre a boy '
if role_nonepol in member.roles:
preff = ' is not specified '
await ctx.send( f'{ member.mention } { preff }' )
member.roles returns a list of classes so you need to specify if you want the role name or id. You can do it two ways:
By comparing each roles with your IDs:
role_girl = 72850048118554
role_boy = 72849957361759
role_nonepol = 72850091485547
#client.command( aliases = [ 'test' ] )
async def __test( ctx, member: discord.Member ):
for role in member.roles:
if role.id == role_girl:
preff = ' youre a girl '
elif role.id == role_boy:
preff = ' youre a boy '
elif role.id == role_nonepol:
preff = ' is not specified '
await ctx.send( f'{ member.mention } { preff }' )
By checking if the user has a role with the get method (you'll have to replace name="..." with the exact role name):
from discord.utils import get
#client.command( aliases = [ 'test' ] )
async def __test( ctx, member: discord.Member ):
if get(member.roles, name='girl'):
preff = ' youre a girl '
elif get(member.roles, name='boy'):
preff = ' youre a boy '
elif get(member.roles, name='nonpol'):
preff = ' is not specified '
await ctx.send( f'{ member.mention } { preff }' )

Flask-Admin: How to filter selectable data of a field based on values entered in the previous field, with search conditions in another table

in flask-admin model view I want to filter a dropdown menu in the edit/create view of field that is a relationship, based on values entered in the previous field.
In the specific case, I would like to see only the ones in the "posto" that are displayed in another table belonging to the selected 'categoria'
class Tag(db.Model):
__tablename__ = 'tags'
nr_TAG = db.Column(db.Integer, primary_key=True)
categoria_id = db.Column(db.Integer, db.ForeignKey('categorie.id'), nullable=False)
categoria = db.relationship('Categoria', backref='tags')
posto_id = db.Column(db.Integer, db.ForeignKey('stalli.id'), nullable=False)
posto = db.relationship('Stallo', backref='tags')
cognome = db.Column(db.String(30), nullable=False)
nome = db.Column(db.String(30))
auto = db.Column(db.String(20))
targa = db.Column(db.String(10))
recapito = db.Column(db.String(80))
stato = db.Column(db.Integer)
posto_occ = db.Column(db.Integer)
orario = db.Column(db.Integer)
fuoriposto = db.Column(db.String(10))
parcheggio = db.Column(db.String(40))
class TagsAdmin(sqla.ModelView):
can_edit = True
can_create = True
column_list = ['nr_TAG', 'categoria', 'posto', 'cognome', 'targa',
'stato', 'orario', 'fuoriposto', 'parcheggio']
can_view_details = True
details_modal = True
form_columns = ['nr_TAG', 'categoria', 'posto', 'cognome', 'nome', 'auto', 'targa', 'recapito']
Any idea?
Thanks
I came up with following solution, maybe it's not perfect but it does the job:
master.html
function populateSelectField(to_populate, options, select) {
$('#s2id_' + to_populate + ' > a > span').text('');
var el = $('select[name$="' + to_populate + '"]');
el.children().remove();
option = '<option value=""></option>';
el.append($(option));
options.forEach(function(row) {
var option_id = row.id,
option_title = row.title;
if (select && option_id == select) {
option = '<option value="' + option_id + '" selected>' + option_title + '</option>';
$('#s2id_' + to_populate + ' > a > span').text(option_title);
} else {
option = '<option value="' + option_id + '">' + option_title + '</option>';
}
el.append($(option));
});
}
function getOptions(el, to_populate, url, select) {
var item_id = el.val(),
url = window.location.origin + url + item_id + '/';
$.get(url).done(function(options) {
populateSelectField(to_populate, options, select);
}).fail(function(err) {
console.error(err.message);
return false;
});
}
function selectFieldManipulation(from_populate, to_populate, url) {
var main_select = $('select[name$="' + from_populate + '"]'),
to_populate_el = $('select[name$="' + to_populate + '"]');
getOptions(main_select, to_populate, url, to_populate_el.val());
main_select.change(function(e) {
getOptions(main_select, to_populate, url, null);
});
}
create.html / edit.html
$(document).ready(function() {
selectFieldManipulation('from_populate', 'to_populate', '/api/route_to_view/');
});

How to process this function-based-view using class-based views?

I'm following this tutorial about ajax and crud. The tutorial uses function-based-views approach, instead, I want to use class-based-views, particularly for this view.
def book_create(request):
data = dict()
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
form.save()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
data['form_is_valid'] = False
else:
form = BookForm()
context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
context,
request=request
)
return JsonResponse(data)
This is the example of the class based view based on your case.
from django.views import View
class BookCreateView(View):
def post(self, request):
form = BookForm(request.POST)
if form.is_valid():
form.save()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
context,
request=request
)
return JsonResponse(data)
def get(self, request):
data = dict()
form = BookForm()
context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
context,
request=request
)
return JsonResponse(data)

How to set kendo datepicker (popup date view) to specific year (1435) without set value(want value to be null)

i make custom mvc control with two kendo datepicker to display (gregi and hijri) date in partial view and if i change date of any one it's change the other to equivalent date
cause to kendo limitation to deal with Hijri calender i make some modification to display correct date i use culture and set max date to hijri to 29/12/1600
every thing is ok if i set value(DateTime.Now) to hijri calender
but i want it display null and user select value but if i remove value and when user open calender the year show is 1600 i want to display 1435 and keep value null
her is my code
Controller
public class UserControl_GHDate
{
public DateTime? GregiDate { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime? HijriDate
{
get
{
if (GregiDate==null)
{
return null;//DateTime.Now;
}
else
{
return GregiDate;
}
}
set { }
}
}
Razor
#model MVC_ERP.Models.UserControl_GHDate
<script src="#Url.Content("~/Scripts/jquery.globalize/globalize.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.ar-SA.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.en-US.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/kendo/cultures/kendo.culture.ar-SA.min.js")"></script>
#Html.Kendo().DatePickerFor(model => model.GregiDate).Format("dd/MM/yyyy").Culture("en-US").HtmlAttributes(new { #class = "kendo", style = "width:49%; max-width:280px" }).Events(e => e.Change("GregiChange"))
#Html.Kendo().DatePickerFor(model => model.HijriDate).Value(DateTime.Now).Footer(false).Max("12/29/1600").Culture("ar-SA").Min(new DateTime(1300, 1, 1)).Format("dd/MM/yyyy").HtmlAttributes(new { #class = "kendo", style = "width:49%; max-width:280px" }).Events(e => e.Change("HijriChange"))
<script>
kendo.cultures["ar-SA"].calendars.standard.firstDay =5;
//kendo.cultures["ar-SA"].calendars.standard.months.namesAbbr[0] = "bbb"; //change name of month
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[0] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[1] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[2] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[3] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[4] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[5] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[6] = "";
function GregiChange(e) {
//alert(this.Name())
var GregId = this.element.prop("id");
var arr = GregId.split('_');
var HijId = arr[0] + '_HijriDate';
if ($('#' + GregId).data('kendoDatePicker').value() == null)
{
$('#' + HijId).data('kendoDatePicker').value(null)
return
}
var d = new Date($('#' + GregId).data('kendoDatePicker').value())
//d.setMonth(d.getMonth() + 1);
var j = d.toLocaleDateString("en-US")
//var z = Globalize.cultures["ar-SA"].calendars.standard.convert.toGregorian("1434", "02", "11");
var z = Globalize.cultures["ar-SA"].calendars.standard.convert.fromGregorian(d);
var y = z.toString()
var arrD = y.split(',');
var year = arrD[0]
var month =(arrD[1]==0?1:(eval(arrD[1])+1))
var day = arrD[2]
var dat = day + '/' + month + '/' + year
$('#' + HijId).data('kendoDatePicker').value(dat)
}
function HijriChange() {
var HijId = this.element.prop("id");
var arr = HijId.split('_');
var GregId = arr[0] + '_GregiDate';
if ($('#' + HijId).data('kendoDatePicker').value() == null) {
$('#' + GregId).data('kendoDatePicker').value(null)
return
}
var d = new Date($('#' + HijId).data('kendoDatePicker').value())
var HD = d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear();
HDMY= d.getDate() + '/' + (d.getMonth()+1)
if (d.getDate() == 31 || HDMY == '30/12' || HDMY == '30/10' || HDMY == '30/8' || HDMY == '30/6' || HDMY == '30/4' || HDMY == '30/2')
{
alert(HD + ' not valid hijri date')
return;
}
var z = Globalize.cultures["ar-SA"].calendars.standard.convert.toGregorian(d.getFullYear(), (d.getMonth() + 1), d.getDate());
var u = new Date(z)
var year = u.getFullYear();
var month = (u.getMonth() == 0 ? 12 : u.getMonth());
var day = u.getDate()+1;
var dat = day+ '/' + month+ '/' + year;
$('#' + GregId).data('kendoDatePicker').value(dat)
}
$(".k-datepicker input").val('');
</script>
Thanks
I think kendo date picker has a min value option try specify the min value with a year of 1435

start datetime and end datetime are not recorded in database when an event is dragged-and-dropped in the day view of FullCalendar

I am trying to update the start datetime and the end datetime in the database whenever I drag-and-drop an event in day view in FullCalendar. This is a part of my code:
eventDrop: function(event){
var id = event.id;
var start = event.start;
var end = event.end;
var table = [id, start, end];
$.ajax({
url: '{{asset('bundles/ikprojhome/phptest/moslem16.php')}}',
type: 'POST',
data: {table: table},
});
}
By the way, this is the code of the file moslem16.php :
<?php
$myArray = $_REQUEST['table'];
$a = $myArray[0];
$b = $myArray[1];
$c = $myArray[2];
$con=mysqli_connect("localhost","root","","wkayetdb");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"UPDATE eventsgroupe SET start='".$b."', end='".$c."' WHERE id='".$a."'");
mysqli_close($con);
?>
And this is the structure of the table "eventsgroupe" in the database (the name of the field is on the left and its type is on the right):
id : int(15)
title : varchar(255)
start : datetime
end : datetime
location : varchar(255)
description : varchar(255)
admingroupe_id : int(20)
idgroupe : int(20)
partger : tinyint(1)
The problem is that after a drag-and-drop of an event in the day view, the value of each of the filed "start" and the field "end" in the table "eventsgroupe" becomes the following one: 0000-00-00 00:00:00 .
So my questions are:
What is the wrong in my code?
How to record the correct start datetime and end datetime of the event after dragging-and-dropping it in the day view in FullCalendar?
I solved it!!. I changed the first code as below:
eventDrop: function(event){
var id = event.id;
var start = event.start;
var end = event.end;
var startdate = [[start.getFullYear(), AddZero(start.getMonth() + 1), AddZero(start.getDate())].join("-"), [AddZero(start.getHours()), AddZero(start.getMinutes())].join(":"), start.getHours() >= 12 ? "PM" : "AM"].join(" ");
var enddate = [[end.getFullYear(), AddZero(end.getMonth() + 1), AddZero(end.getDate())].join("-"), [AddZero(end.getHours()), AddZero(end.getMinutes())].join(":"), end.getHours() >= 12 ? "PM" : "AM"].join(" ");
function AddZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
var startdate1 = startdate.substring(0, startdate.length - 3) + ":00";
var enddate1 = enddate.substring(0, enddate.length - 3) + ":00";
var table = [id, startdate1, enddate1];
$.ajax({
url: '{{asset('bundles/ikprojhome/phptest/moslem16.php')}}',
type: 'POST',
data: {table: table},
});
}
And I changed the second code as below:
<?php
$myArray = $_REQUEST['table'];
$a = $myArray[0];
$b = $myArray[1];
$c = $myArray[2];
$con=mysqli_connect("localhost","root","","wkayetdb");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"UPDATE eventsgroupe SET start='".$b."', end='".$c."' WHERE id='".$a."'");
mysqli_close($con);
?>
Now it works correctly!!

Resources