Getting values ​from django database - python

I'm just learning python and django.
I am writing a thing that reads the values ​​in the xlsx file, and if the values ​​​​are similar to those in the database, then the value in the adjacent column in the xlsx file changes to the one I specify
models.py
class imgUpload(models.Model):
title = models.CharField(max_length=100)
img = models.ImageField(upload_to='img')
def __str__(self):
return self.title
views.py
def upload_xlsx(request):
if request.method == 'POST':
form = xlsxForm(request.POST, request.FILES)
if form.is_valid():
form.save()
fileName = xlsxUpload.objects.last()
fileNameStr = str(fileName.file)
book = load_workbook(fileNameStr)
sheet: worksheet = book.worksheets[0]
for row in range(2, sheet.max_row + 1):
a = sheet[row][0].value
fileNameImg = imgUpload.objects.all()
fileNameImgStr = fileNameImg.filter(title=a)
if a == fileNameImgStr:
sheet[row][1].value = str(fileNameImgStr)
book.save(fileNameStr)
book.close()
return redirect('xlsx_list')
else:
form = xlsxForm()
return render(request, 'img/upload_xlsx.html', {
'form': form
})
I have achieved that it takes all the values, but does not compare them

Related

Read a csv file and fill in database with it's data in django application

in my Django application, i created a form which permit user to upload csv file.
What i want is when user upload the csv file, the contained data is read and database is filled in with them.
It works but not correctly. data are saved as tuples.
Here's my code
forms.py
class SupplierCSVForm(forms.ModelForm):
class Meta:
model = SuplierCsv
fields = '__all__'
exclude = ('slug',)
views.py
#login_required
def l_supplier(request):
suppliers_list = Supplier.objects.all()
paginator = Paginator(suppliers_list, 3, 2)
page = request.GET.get('page')
suppliers = paginator.get_page(page)
# Supplier csv form
if request.method == 'POST':
form = SupplierCSVForm(request.POST, request.FILES)
if form.is_valid():
uploaded_file = request.FILES['csvfile']
with open('f.csv', 'wb') as destination:
for chunk in uploaded_file.chunks():
destination.write(chunk)
destination.close()
#csvfile = io.TextIOWrapper(open('f.csv', 'rb'))
with open('f.csv', 'r') as the_source:
source_reader = csv.reader(sthe_source)
next(source_reader)
for Name, Email, Contact, City, Website, Activity, Cc, slug in source_reader:
new_supplier = Supplier()
new_supplier.name=Name,
new_supplier.email=Email,
new_supplier.contact=Contact,
new_supplier.city=City,
new_supplier.website=Website,
new_supplier.activity=Activity,
new_supplier.cc=Cc,
new_supplier.slug=slug,
new_supplier.save()
return redirect('good:l_good')
else:
form = SupplierCSVForm()
context = {
'suppliers': suppliers,
'form': form,
}
return render(request, 'supplier/l_supplier.html', context)
Remove the commas where you are assigning the new_supplier objects. Python converts your string objects into tuples if there are any trailing commas.
You have unnecessary commas at the end of your lines:
new_supplier.name=Name,
should be
new_supplier.name=Name
Python thinks that you are creating a tuple
i.e. x, == (x,)

Lines before form.save() are not saving the right values

I have a view with model form, the ModelForm doesn't really contain all fields in the model. other fields I've used the methods of form.field = value before form.save(), but all of this fields being saved as default. none take the value am trying to give. here are the code :
def PostAd(request):
ad_post_form = AdPostForm()
if request.user.is_authenticated:
obj = Account.objects.get(user=request.user)
if request.method == "POST":
ad_post_form = AdPostForm(request.POST, request.FILES)
if ad_post_form.is_valid():
ad_post_form.created_by = request.user
if obj.role == 'admin':
ad_post_form.is_active = True
ad_post_form.save()
return redirect('home')
else:
ad_post_form = AdPostForm(request.POST, request.FILES)
else:
if request.method == "POST":
ad_post_form = AdPostForm(request.POST, request.FILES)
if ad_post_form.is_valid():
otp_number = random.randint(100000, 999999)
ad_post_form.otp = otp_number
ad_post_form.is_activated = False
ad_post_form.save()
current_id = ad_post_form.id
current_contact_email = request.POST.get('contact_email')
email_url_active = str(settings.URL_LOCAL) + 'new_ad/adidnumberis' + str(
current_id) + '/needactivate/activate/' + str(otp_number) + '/'
email_msg = "Please Confirm adding the Ad to Jehlum. Click link " + email_url_active
email = EmailMessage('Active Email', email_msg, to=[current_contact_email])
email.send()
return redirect('home')
else:
ad_post_form = AdPostForm()
context = {
'ad_post_form': ad_post_form,
}
return render(request, 'pages/post-ad.html', context)
the problem is ad_post_form.is_active = True is being saved as False(default)
also ad_post_form.otp = otp_number is being saved as 0 (default) and i need to give the spicific values i assigned here .
You need to get the model instance and set the attributes there. You so this by calling save with commit=False.
if ad_post_form.is_valid():
ad_post = ad_post_form.save(commit=False)
ad_post.created_by = request.user
...
ad_post.save()

Two forms one view: model variable loses value

Here's my code
#login_required
def upload(request):
form_type = ''
transcript = Transcript()
transcript.file_path = ''
if request.method == 'POST':
if 'file_form' in request.POST:
file_form = FileForm(request.POST, request.FILES)
if file_form.is_valid():
path = handle_uploaded_file(request.FILES['file'], request.user)
transcript.file_path = path
transcript.user = request.user
export_form = InfoForm()
form_type = 'info_form'
elif 'info_form' in request.POST:
if transcript.file_path:
info_form = InfoForm(request.POST)
if info_form.is_valid():
transcript.user = request.user
transcript.title = info_form.cleaned_data.get('title')
transcript.instructions = info_form.cleaned_data.get('instructions')
transcript.save()
return HttpResponseRedirect('thanks')
else:
raise ValueError('Transcript object has no file path attribute')
else:
export_form = FileForm()
form_type = 'file_form'
return render(request, 'transcription/upload.html', {'form': export_form, 'form_type': form_type})
always, the file-form is called before the info-form, so the code in the if statement
if transcript.file_path:
#...
should always execute. But the ValueError always gets raised, meaning transcript.file_path is reset. How does this happen, and how can it be fixed?
file_form and info_form in POST are names of the different submit buttons, so I know which form I am dealing with.
def handle_uploaded_file(file, user):
id = randint(0, 10000)
user_dir = settings.MEDIA_ROOT + '/' + str(user.id).replace(".", "") + '/'
path = user_dir + file.name.replace(".mp3", str(id) + ".mp3")
if not os.path.exists(user_dir):
os.makedirs(user_dir)
with open(path, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
file = File(destination)
info = {'path': path, 'file': file}
return path
So it was a rookie mistake.
I didn't know that during each post request the whole view gets called again.
So I just initialized my variables
form_type = ''
transcript = Transcript()
transcript.file_path = ''
outside the view and voila!

Not saving data to Database from Form

When i have this view, It only change username a password from first Form, but it would save any data from second form. Why?
if request.method == 'POST': # If the form has been submitted...
username_a_heslo = UserCreationForm(request.POST, prefix = "začátek")
přidat_údaje = UcitelZmenaForm(request.POST, prefix = "konec")
if username_a_heslo.is_valid() and přidat_údaje.is_valid(): # All validation rules pass
změnajména = request.user
změnajména.username = username_a_heslo.cleaned_data["username"]
změnajména.save()
zmenahesla=request.user.set_password(username_a_heslo.cleaned_data["password1"])
# primary = username_a_heslo.save()
cast_form = Ucitel.objects.all().filter(user=request.user)
form = UcitelZmenaForm(přidat_údaje.cleaned_data, instance=cast_form[0])
form.save
#b = přidat_údaje.save()
return HttpResponseRedirect('/hlavni_stranka/')
else:
username_a_heslo = UserCreationForm(prefix = "začátek")
přidat_údaje = UcitelZmenaForm(prefix = "konec")
return render(request, 'registration/prihlasen.html', {'prvni_prihlaseni':prvni_prihlaseni,'první_form': username_a_heslo,'druhý_form':přidat_údaje})
You did not call the function on the second one, you only have form.save when you need form.save().

Django populating initial data in formset

This may be a rather simple problem. But I am trying to populate my form with initial data taken from a database. I don't really know where to start. Any advice would help.
Some background: I have a disease with multiple indicators. In my form I am pulling disease_id = 2 then wanting to populate the indicators currently in the database, so they may be edited.
views.py
def drui(request):
disease_id = request.GET.get('disease_id', '2')
if request.method == "POST":
disease = get_object_or_404(Disease, pk=disease_id)
diseaseForm = DiseaseForm(request.POST, instance=disease)
if diseaseForm.is_valid():
new_disease = diseaseForm.save(commit=False)
indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=new_disease)
if indicatorInlineFormSet.is_valid():
new_disease.save()
indicatorInlineFormSet.save()
return HttpResponseRedirect(reverse(somewhere))
else:
diseaseForm = DiseaseForm()
indicatorInlineFormSet = IndicatorFormSet(instance=Disease())
return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet},context_instance=RequestContext(request))
Just put disease object out in the request POST
def drui(request):
disease_id = request.GET.get('disease_id', '2')
disease = get_object_or_404(Disease, pk=disease_id)
if request.method == "POST":
diseaseForm = DiseaseForm(request.POST, instance=disease)
if diseaseForm.is_valid():
new_disease = diseaseForm.save(commit=False)
indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES,
instance=new_disease)
if indicatorInlineFormSet.is_valid():
new_disease.save()
indicatorInlineFormSet.save()
return HttpResponseRedirect(reverse(somewhere))
else:
diseaseForm = DiseaseForm(instance=disease)
indicatorInlineFormSet = IndicatorFormSet(instance=disease)
return render_to_response("drui.html", {
'diseaseForm': diseaseForm,
'indicatorInlineFormSet': indicatorInlineFormSet
},context_instance=RequestContext(request))

Categories

Resources