Im having trouble on uploading multiple files. The uploaded files are pdf and only one is saved.
views.py
def attachments(request):
to = TravelOrder.objects.order_by('-date_filling').last()
if request.method == 'POST':
form = AttachmentsForm(request.POST, request.FILES)
if form.is_valid():
for f in request.FILES.getlist('attachment'):
file_instance = Attachements(travel_order=to, attachment=f)
file_instance.save()
print('YEY')
return redirect('attach')
else:
form = AttachmentsForm()
context = {
'form': form
}
return render(request, 'employee/attachments.html', context)
models.py
class TravelOrder(models.Model):
created_by = models.CharField(max_length=255)
start_date = models.DateField(auto_now=False)
end_date = models.DateField(auto_now=False)
wfp = models.CharField(max_length=255, verbose_name='Wfp Where to be charged')
purpose_of_travel = models.CharField(max_length=255)
region = models.ForeignKey(Region, on_delete=models.CASCADE)
venue = models.CharField(max_length=255)
date_filling = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=15)
def __str__(self):
return self.purpose_of_travel
class Attachements(models.Model):
at_id = models.AutoField(primary_key=True)
travel_order = models.ForeignKey(TravelOrder, on_delete=models.CASCADE)
attachment = models.FileField(upload_to='attachment/')
I think you are returing before the loop finishes.
for f in request.FILES.getlist('attachment'):
file_instance = Attachements(travel_order=to, attachment=f)
file_instance.save()
print('YEY')
return redirect('attach')
Take the return outside loop, so that the redirect happens only after saving all files. That means
for f in request.FILES.getlist('attachment'):
file_instance = Attachements(travel_order=to, attachment=f)
file_instance.save()
print('YEY')
return redirect('attach')
Related
Model.py
class Branch(models.Model): # Branch Master
status_type = (
("a",'Active'),
("d",'Deactive'),
)
name = models.CharField(max_length=100, unique=True)
suffix = models.CharField(max_length=8, unique=True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.name
class Vendor(models.Model):
status_type = (
("a",'Active'),
("d",'Deactive'),
)
branch = models.ManyToManyField(Branch)
company = models.CharField(max_length=200)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=11, unique = True)
email = models.EmailField(max_length=254, unique = True)
gst = models.CharField(max_length=15, unique = True)
pan_no = models.CharField(max_length=10, unique = True)
add_1 = models.CharField(max_length=50, null=True, blank = True)
add_2 = models.CharField(max_length=50, null=True, blank = True)
add_3 = models.CharField(max_length=50, null=True, blank = True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.company
form.py
i want save like created_by field
class VendorForm(ModelForm):
class Meta:
model = Vendor
fields = 'all'
exclude = ['created_by', 'branch']
widgets = {
'company':forms.TextInput(attrs={'class':'form-control'}),
'name':forms.TextInput(attrs={'class':'form-control'}),
'phone':forms.TextInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
'gst':forms.TextInput(attrs={'class':'form-control'}),
'pan_no':forms.TextInput(attrs={'class':'form-control'}),
'add_1':forms.TextInput(attrs={'class':'form-control'}),
'add_2':forms.TextInput(attrs={'class':'form-control'}),
'add_3':forms.TextInput(attrs={'class':'form-control'}),
'Remark':forms.Textarea(attrs={'class':'form-control','rows':'2'}),
'status':forms.Select(attrs={'class':'form-control'}),
}
Views.py
I have pass branch in session.
I want to save with branch which is many to many field
def Add_Vendor(request): # for vendor add
msg = ""
msg_type = ""
branch_id = request.session['branch_id']
branch_data = Branch.objects.get(id = branch_id)
form = ""
if request.method == "POST":
try:
form = VendorForm(request.POST)
if form.is_valid:
vendor_add = form.save(commit=False)
vendor_add.created_by = request.user
vendor_add.instance.branch = branch_data.id
vendor_add.save()
form.save_m2m() # for m to m field save
msg_type = "success"
msg = "Vendor Added."
form = VendorForm(initial={'branch':branch_id})
except:
msg_type = "error"
msg = str(form.errors)
print(msg)
else:
form = VendorForm(initial={'branch':branch_id})
context = {
'form':form,
'branch_data':branch_data,
'msg_type':msg_type,
'msg':msg,
'btn_type':'fa fa-regular fa-plus',
'form_title':'Vendor Form',
'tree_main_title':'Vendor',
'v_url':'vendor_page',
'tree_title':'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html',context)
I would advise not to work with commit=False in the first place:
def Add_Vendor(request): # for vendor add
branch_id = request.session['branch_id']
branch_data = get_object_or_404(Branch, pk=branch_id)
if request.method == 'POST':
form = VendorForm(request.POST, request.FILES)
if form.is_valid():
form.instance.created_by = request.user
form.instance.branch = branch_data.id
vendor_add = form.save()
vendor_add.branch.add(branch_data)
return redirect('name-of-some-view')
else:
form = VendorForm()
context = {
'form': form,
'branch_data': branch_data,
'btn_type': 'fa fa-regular fa-plus',
'form_title': 'Vendor Form',
'tree_main_title': 'Vendor',
'v_url': 'vendor_page',
'tree_title': 'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html', context)
You can simplify your form by automatically adding form-control to each widget:
class VendorForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
attrs = field.widget.attrs
attrs['class'] = attrs.get('class', '') + ' form-control'
class Meta:
model = Vendor
exclude = ['created_by', 'branch']
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: You can set a field editable=False [Django-doc]. Then the field does not show up in the ModelForms and ModelAdmins by default. In this case for example with created_by.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: Please do not pass messages manually to the template. Django has the messages framework [Django-doc], which allows to add messages to the request, which will then be delivered the next time a template renders these messages. This makes delivering multiple messages convenient, as well as setting different log levels to the messages.
I have this error and cant really to identify the error.In dynamic url routing I identify the url predifining the app name(main) then the url.
<a class="btn btn-info" href="{% url 'main:teacher' teacher.fname %}">View</a>
Could this be related with the error of inline form sets?
Models:
class Teacher(models.Model):
teacher_id = models.AutoField(primary_key=True,blank=True)
fname = models.CharField(max_length=200)
lname = models.CharField(max_length=200)
tsc_no = models.CharField(max_length=200,blank=True,unique=True)
email = models.CharField(max_length=200,blank=True,unique=True)
password = models.CharField(max_length=200,blank=True)
profile_picture = models.ImageField(verbose_name='profile_picture',upload_to='photos/%Y/%m/%d',blank=True)
national_id = models.CharField(max_length=200,unique=True)
dob = models.DateField(blank=True)
phone_number = PhoneNumberField()
status = models.CharField(max_length=200)
clas_teacher = models.CharField(max_length=200,blank=True)
date_of_join = models.DateField(blank=True)
timetable_color = models.CharField(max_length=200)
class Course(models.Model):
course_id = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
teacher = models.ManyToManyField(Teacher)
class Meta:
ordering = ['course_name']
def __str__(self):
return self.course_name
The view:
def addmoreteacher(request,pk_test):
teacher = Teacher.objects.get(fname=pk_test)
CourseFormSet = inlineformset_factory(Teacher,Course,fields = ('course_name','description'))
formset = CourseFormSet(instance=teacher)
#form = CourseForm(initial = {'teachers_teaching':teacher})
if request.method == 'POST':
#form = TeacherForm(request.POST)
#print(form)
formset = CourseFormSet(request.POST,instance=teacher)
if formset.is_valid():
formset.save()
print("saved")
return redirect('/')
else:
print(formset.errors)
context = {'formset': formset}
return render(request = request,template_name='main/addmoreteacher_form.html',context=context)
Change models.py's Course class's teacher field,
From,
teacher = models.ManyToManyField(Teacher)
To,
models.ForeignKey(Teacher, on_delete=models.CASCADE)
Good days guys need help for my ForeignKey Relationship in my models,
i want my foreignkey values is equal to the user choose
Here's my model view
class ProjectNameInviToBid(models.Model):
ProjectName = models.CharField(max_length=255, verbose_name='Project Name', null=True)
DateCreated = models.DateField(auto_now=True)
def __str__(self):
return self.ProjectName
have relations to ProjectNameInviToBid
class InviToBid(models.Model):
today = date.today()
ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE, null=True)
NameOfFile = models.CharField(max_length=255, verbose_name='Name of File')
Contract_No = models.IntegerField(verbose_name='Contract No')
Bid_Opening = models.CharField(max_length=255, verbose_name='Bid Opening')
Pre_Bid_Conference = models.CharField(max_length=255, verbose_name='Pre Bid Conference')
Non_Refundable_Bidder_Fee = models.CharField(max_length=255, verbose_name='Non Refundable Fee')
Delivery_Period = models.CharField(max_length=255, verbose_name='Delivery Period')
Pdf_fileinvi = models.FileField(max_length=255, upload_to='upload/invitoBid', verbose_name='Upload Pdf File Here')
Date_Upload = models.DateField(auto_now=True)
This is my form view
class invitoBidForm(ModelForm):
class Meta:
model = InviToBid
fields = ('ProjectName','NameOfFile', 'Contract_No', 'Bid_Opening',
'Pre_Bid_Conference', 'Non_Refundable_Bidder_Fee',
'Delivery_Period',
'Pdf_fileinvi')
and Lastly this my view Forms
def project_name_details(request, sid):
majordetails = ProjectNameInviToBid.objects.get(id=sid)
if request.method == 'POST':
form = invitoBidForm(request.POST, request.FILES)
if form.is_valid():
majordetails = form.ProjectName
form.save()
messages.success(request, 'File has been Uploaded')
else:
form = invitoBidForm()
args = {
'majordetails': majordetails,
'form': form
}
return render(request,'content/invitoBid/bacadmininvitoBid.html', args)
but im have a error,, hope you can help me. thank you in advance
I've this in my views and trying to get new truck_name assigned to a new Product.
When user with truck_name as None and no instance of Product, the script goes to
try:
truck_name = Product.objects.get(user=request.user)
and skips to the except:
#login_required
def profile_edit(request):
owner = TruckOwnerStatus.objects.get(user=request.user)
truck_form = RegisterTruckForm()
i = owner.id
print i
try:
truck_name = Product.objects.get(user=request.user)
if request.method == 'GET':
if truck_name is not None:
truck_form = RegisterTruckForm(instance=truck_name)
else:
truck_form = RegisterTruckForm()
context = {
'truck_form': truck_form,
'truck_name': truck_name,
}
return render(request, 'accounts/profile_edit.html', context)
elif request.method == 'POST':
if truck_name is not None:
truck_form = RegisterTruckForm(request.POST, request.FILES, instance=truck_name)
else:
truck_form = RegisterTruckForm(request.POST, request.FILES)
#once clicked save
if truck_form.is_valid():
truck_name = truck_form.save(commit=False)
truck_name.product = Product.objects.get(user=request.user)
truck_form.save_m2m()
truck_name.save()
messages.success(request, "Successfully Saved!!")
return HttpResponseRedirect('/')
return render_to_response('accounts/profile_edit.html', {'truck_form': truck_form}, context_instance=RequestContext(request))
except:
print "hii"
if request.method == 'POST':
truck_form = RegisterTruckForm(request.POST, request.FILES)
truck_owner = request.user
if truck_owner is not None:
truck_form = RegisterTruckForm(request.POST, request.FILES, instance=truck_owner)
else:
truck_form = RegisterTruckForm(request.POST, request.FILES)
if truck_form.is_valid():
truck_owner = truck_form.save(commit=False)
truck_owner.profile = Product.objects.create(user=request.user)
truck_form.save_m2m()
truck_owner.profile.save()
messages.success(request, "Successfully Saved!!")
return HttpResponseRedirect('/')
else:
messages.error(request, "Please recheck")
# return render(request, context, 'accounts/profile_edit.html',)
context = {"truck_form": truck_form}
return render(request, 'accounts/profile_edit.html', context)
It does the job of saving the form but does not assign the truck_name from the form to the request user. Hence nothing gets assigned to the new Product
I tried putting
truck_name = Product.objects.get(user=request.user) in the except but it returns an error because there is no instance of Product for this user and therefore no truck_name.
I can see the entry in admin but can't view it because there is no truck_name. But if I were to run the entire profile_edit for the same user and fill the the form, the truck_name gets assigned.
How do I get it assigned?
Below is my Product model.
class Product(models.Model):
user = models.OneToOneField(User)
owner_name = models.CharField(max_length=120)
email = models.EmailField(max_length=120)
contact_number = models.IntegerField(max_length=15, null=True, blank=True)
foodtruck_name = models.CharField(max_length=120)
logo = models.ImageField(upload_to='foodtruck/logo/', null=True, blank=True)
slogan = models.TextField(max_length=250, null=True, blank=True)
about_us = models.TextField(max_length=500, null=True, blank=True)
operating_state = models.CharField(max_length=120, choices=STATE_CHOICES)
bsb = models.IntegerField(max_length=15, null=True, blank=True)
account_number = models.IntegerField(max_length=15, null=True, blank=True)
availability_link = models.CharField(max_length=300, null=True, blank=True)
slug = models.SlugField(unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
update_defaults = models.BooleanField(default=False)
def __unicode__(self):
return self.foodtruck_name
class Meta:
unique_together = ('foodtruck_name', 'slug')
def get_price(self):
return self.price
def get_absolute_url(self):
return reverse("single_product", kwargs={"slug": self.slug})
I have the following models that I need to create a form which allows for the updating of an existing Response (generated previously with a slug and then emailed to the respondent) and the creation of a Rating for each CV in CV.objects.all(). What's the easiest way to do this in Django. Currently I have a class-based UpdateView for Response and that's it.
class Response(models.Model):
first_name = models.CharField(max_length=200, null=True, blank=True)
last_name = models.CharField(max_length=200, null=True, blank=True)
email = models.EmailField(max_length=254)
slug = models.SlugField(max_length=32)
submited = models.BooleanField(default=False)
submit_time = models.DateTimeField(null=True, blank=True)
creation_time = models.DateTimeField(auto_now_add=True)
class CV(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to=content_file_name)
class Rating(models.Model):
cid = models.ForeignKey('CV')
rid = models.ForeignKey('Response')
score = models.IntegerField()
comment = models.TextField()
I eventually worked out how to do this. My code was as follows in case anyone is interested.
def add_response(request):
CVs = CV.objects.all()
if request.method == "POST":
ResForm = ResponseForm(request.POST, instance=Response())
RatForms = [RatingForm(request.POST, prefix=str(cv.id), instance=Rating(cid=cv)) for cv in CVs]
if ResForm.is_valid() and all([rf.is_valid() for rf in RatForms]):
new_response = ResForm.save(commit=False)
new_response.submit_time = datetime.now()
new_response.submited = True
new_response.save()
for rf in RatForms:
new_rating = rf.save(commit=False)
new_rating.rid = new_response
new_rating.save()
return HttpResponseRedirect('/thanks/')
else:
for i, _ in enumerate(RatForms):
RatForms[i].cv = CV.objects.filter(id=int(RatForms[i].prefix))[0]
print RatForms[i].cv
return render(request, 'response.html', {'response_form': ResForm, 'rating_forms': RatForms})
else:
ResForm = ResponseForm(instance=Response())
RatForms = [RatingForm(prefix=str(cv.id), instance=Rating(cid=cv)) for cv in CVs]
for i, _ in enumerate(RatForms):
RatForms[i].cv = CV.objects.filter(id=int(RatForms[i].prefix))[0]
print RatForms[i].cv
return render(request, 'response.html', {'response_form': ResForm, 'rating_forms': RatForms})