How to use JSON in Django functions - python

i'm doing a django project for adding and updating things with a mysql database, but i was told that it's not safe to add and update thing directly without JSON, is this possible? how can i do that?
here's my create function:
form = RoomForm()
if request.method == 'POST':
form = RoomForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form}
return render(request, 'tasks/room_form.html', context)```

Related

(django)I created a todo app in django but everytime I update the task. It creates a new object

It creates new object everytime I update the task.
I tried alot but it still does mot work correctly .Help me please
Models.py contains only a charfield for title, boolean field for task status(task completed or not completed) , a dattime field with auto_add_now=True and an str function returning title
def index(request):
task = Task.objects.all().order_by('-created_on')
form= TaskForm()
if request.method=='POST':
form= TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect ('/')
return render(request('task/list.html',{'task':task,'form':form})
def update_task(request,pk):
task =Task.objects.get(id=pk)
form= TaskForm(instance= task)
if request.method=='POST':
form= TaskForm(request.POST,instance=task)
if form.is_valid():
form.save()
return redirect('/')
return render(request,'task/update_task.html', {'form': form})
Try this:
def update_task(request,pk):
task =Task.objects.get(id=pk)
form= TaskForm(instance= task)
if request.method=='POST':
form= TaskForm(request.POST,instance=task)
if form.is_valid():
f = form.save(commit=False)
f.save()
return redirect('/')
return render(request,'task/update_task.html', {'form': form})
It could be the problem with your primary key if it isn't the AutoField() or is not defined. As you could be changing your primary key in the form.
Another approach is you could check out which fields are changed, then manually change their values in the task instance.
def update_task(request,pk):
task =Task.objects.get(id=pk)
form= TaskForm(instance= task)
if request.method=='POST':
form= TaskForm(request.POST,instance=task)
if form.is_valid():
if 'some_field_in_task' in form.changed_data:
task.some_field_in_task = form.cleaned_data['some_field_in_task']
task.save()
return redirect('/')
return render(request,'task/update_task.html', {'form': form})
You should post your Models.py here also. The issue seems to come from that, not from the views.py
Your views.py looks pretty good.
I got the same issue in my todo app. In my case the problem was that in my "update.html", i had a slash("/") within form action attribute.
Like:
form method="POST" action="/">
And actually it was redirecing me do my index view(which creates new tasks) and so creating new task.
To solve the problem, just delete this slash and leave it empty.
Check urls.py once
urlpatterns = [
path('updateTask/<str:pk>/', views.updateTask, name="updateTask"),
]

How can I post data to the django database and to a CSV file

I am trying to have an output (csv/txt) from a Django form input in addition to saving in the SQL tables
my code is here
def booking_view(request):
global form
if request.method == 'POST':
form = BookingForm(request.POST, request.FILES)
if form.is_valid():
form.save()
**WRITE TO A CSV FILE**
form = BookingForm()
return render(request, 'booking/sandpit.html', {'form': form})
else:
form = BookingForm()
return render(request, 'booking/sandpit.html', {'form': form})
How can i take the form data and save as CSV/TXT
Thanks in advance
Since you are doing form.is_valid(), the form data is available in a usable state in the dictionary cleaned_data. To access this data, call
val1 = form.cleaned_data['fieldNameOne']
val2 = form.cleaned_data['fieldNameTwo']
With these values you can then write to a csv as needed.
Python has a built-in module named csv, and this is probably what you could use.

Obtaining data from the form with GET data. Django

How can I get data from the form using the GET method?
For example, I have this form:
class LoansSearchForm(forms.Form):
balance = forms.IntegerField(label='', required=False)
In my view display in the form template this way:
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
But i still a error:
'LoansSearchForm' object has no attribute 'cleaned_data'
When trying to get them this way:
word = form['balance']
I receive a field with completed data. How to get the data from my the form correctly?
Is my form written correctly? Should I use something like that?
(sorry if my question is trivial, but I found very little information about GET forms)
if request.method == 'GET':
form = LoansSearchForm(request.GET)
if form.is_valid():
print('Hello World')
else:
form = LoansSearchForm()
Recommended: run form.is_valid() and then you do form.cleaned_data
def search_results(request):
form = LoansSearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
word = cd['balance']
else:
word = None
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it anywhere.
more on cleaned data - documentation
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data # here <------
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
The problem with your code is that forms are not filled on initialization but when you call form.is_valid, if the form is indeed valid, then it populates cleaned_data
You can read more about the related documentation.
I used name=form.data['field_name'], think it answers your answer of obtaining form values on submit.

Why calling method inside views.py after successful submission of forms doesn't clear the form?

Views.py
def form_name_view(request):
form = FormName()
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
return render(request, 'first_app/form_page.html', {'form': form})
When I use HttpResponseRedirect to get back to my index page, then everything works correct, but the concern is if I use calling index method instead of HttpResponseRedirect then the behavior is a little bit insane:
After reaching index page if I hit refresh then alert appears says:
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be
repeated. Do you want to continue?
If i want to get back to the same form page, by calling that same method again like
return form_name_view(request)
The new form is already filled with previous inserted data, with the message on the form
Topic with this Topic name already exists.
The question is what is the reason, calling method results like this?
def form_name_view(request):
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
else:
form = FormName()
return render(request, 'first_app/form_page.html', {'form': form})
use this

simple django code snippet from file upload

sorry for dumb question.
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
what happens really in the background when i bind the request to the Form?
It creates an empty form to be passed to the template upload.html since the previous form in upload.html did not pass the validation. When a form has some error, Validation Error exception is raised, then the form is invalid, or when the view is called and request does not include the method POST therefor you must render it again.

Categories

Resources