Prevent the Repetition of Data in Database - python

Here's the code in view,
def index(request):
data = Model.objects.create(user=request.user, timestamp=timezone.now())
Whenever the view is requested i'm saving the user requesting it & the timestamp at which user has requested the page.
But, It's repeating the same data in database with updated timestamp. How can I prevent the repetition by updating the same instance when the view is requested?
Please helpme!

You can handle using this way. If data is not there then create else update.
def index(request):
data = Model.objects.update_or_create(user=request.user, timestamp=timezone.now())
Alternatively:
def index(request):
data = Model.objects.get(user=request.user)
if not data:
data = Model.objects.create(user=request.user, timestamp=timezone.now())
else:
data = Model.objects.update(user=request.user, timestamp=timezone.now())

Related

Flask & Python: Remember form data after POST

I'm trying to let the user create a "meeting" with several settings on a website.
User fills out a form
Form is send via POST
Website shows a summary page with the data entered by the user
User can go back and edit that data or press the "okay" button
Data from user is added to the database
I'm stuck at step 4.
session_create.html contains the form. I can submit the form and the data gets validated (wtforms). If the form data is validated, I display it on the session_summary.html page. The data is displayed there correctly.
The routes file:
#app.route('/create', methods=['GET','POST'])
#login_required
def create():
form = CreateSessionForm()
if form.validate_on_submit():
data = {}
data["title"] = form.title.data
data["description"] = form.description.data
data["date"] = form.date.data
data["time"] = form.time.data
data["sessiontype"] = form.sessiontype.data
data["host"] = current_user.username
if form.duration.data:
data["duration"] = form.duration.data
else:
data["duration"] = 0
return render_template('session_summary.html', title='Create a session', data=data)
return render_template('session_create.html', title='Create a session', form=form)
But my problem is that from here on I don't know how to access the data if the user confirms that the data entered was correct. Do I need to send all data in a hidden form to session_summary.html?
I'm sorry for not being more precise. I can't seem to wrap my head around it.

How to export csv file after search data in Django 2?

I have a search function that returns json via ajax, but I also want to export the data to a csv file.
It occurred to me to do another function to export the data, which brings the search function
I'm doing it like this:
def search(request):
date = request.GET.get('date')
queryset = List.objects.filter(date=date)
data = serializers.serialize('json', queryset)
return HttpResponse(data, content_type='application/json')
def export_to_csv(request):
data = search(request)
# But that does not bring the search data
print(data)
# <HttpResponse status_code=200, "application/json">
I hope you understand my question, some ideas or suggestions?
Maybe you can try with simply extracting the logic which retrieves and serializes the data into a helper function, which can be a part of your views.py (or, probably a better approach, moved to a helper/utility module) e.g.:
def get_search_data(date=None):
queryset = List.objects.all()
if date:
queryset = queryset.filter(date=date)
return serializers.serialize('json', queryset)
def search(request):
data = get_search_data(request.GET.get('date'))
return HttpResponse(data, content_type='application/json')
def export_to_csv(request):
data = get_search_data()
...
print(data)
# <HttpResponse status_code=200, "application/json">

Saving django form as excel file with saving to db also in Django

I have code like this. It's working example of saving data specified in forms.py, and some data taken from current logged user.
#login_required
def save(request):
if request.method == 'POST':
form = ExcelForm(data=request.POST)
if form.is_valid():
name = request.user.first_name
lastname = request.user.last_name
date = datetime.datetime.now().date()
valid_form = form.save(commit=False)
valid_form.firstName = name
valid_form.lastName = lastname
valid_form.date = date
valid_form.save()
return redirect('account:panel')
else:
form = ExcelForm(data=request.POST)
return render(request, 'account/panel.html', {'form': form})
This form is saved to sqllite db. My main goal is to save this form as excel file. How can I deal with this problem ? How to pass data to the sheet and with clicking submit button in my html file saving to excel file and to database in the same time ? thanks for all answers in the future.
Rather than storing the data in excel, you can create a new view to export the data as excel format. You can try like this using django-import-export. Example of writing a view:
from django.http import HttpResponse
from .resources import PersonResource
def export(request):
person_resource = PersonResource()
dataset = person_resource.export()
response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="persons.xls"'
return response
You can check this medium post as well for exporting data using view.

Django and one-time links with data

I think I have a simple case here but I'm not finding good examples of the implementation ( or probably failing to understand).
After the user (not logged in) types his username to a form, Django would generate a unique URL based of this data (encoded in URL?) for the user that can be accessed once and within 5 minutes. Based on that URL (after clicking it) the data (username) would be decoded and ready for use in this one-time view.
Simple scenario if needed: user nimda fills the form and then is redirected (for example) to a view that shows the generated URL. Then nimda clicks the generated URL and a view is shown with the data he or she typed into the form
If you don't need that url you could save data to the session and send the user to a specific url.
The view connected to the url generates content depending on the (anonymous) users session. The user can see the content as long as you sessions last or you implement a time stamp an check this before delivering content.
If you need the url:
Build a model connected with the sessions with url and a time stamp.
Configure the urls.py for the url-model like
url(r'^dataUrl/(?P[0-9]+)/$', PostDelete.as_view()),
Assign the user session and the entered data (saved to the session) with
the url-model.
When delivering the content check for the random-url-part, and the timestamp and deliver the date (or not ;) )
You can access the session in a cvb's like this:
class YourClassName(TemplateView):
template_name = ""
def get_context_data(self, **kwargs):
context = super(YourClassName , self).get_context_data(**kwargs)
DataYouNeed = self.request.session["SessionVariableOfTheUser"]
userDAta = self.request.user #if this is usefull `
or in a createView:
class URLCreate(CreateView):
model = randomUrl
template_name = "entryCreate.html"
success_url = "../xyz/"
form_class = UrlCreateForm
# if you like to change the success-url
def get_success_url(self):
#print dir(self.object.instance)
#print self.object.instance.id
url = "../bringMeTo/%s" % self.object.instance.id
return url
def form_valid(self,form):
form.instance.user = self.request.user
self.request.session["formData"]= form.instance
return super(URLCreate, self).form_valid(form)
pass
This is not a ready solution! Just an inspiration for a start.

How to route form errors to another view using Flask, FlaskWTF

I'm trying to create two views using Flask. The first view show_entries displays a list of entries in a table. It also includes a form to create new entries.
The form gets submitted to a second view new_entry which accepts the POST method and is responsible for adding the new entry to the table using SQLAlchemy. new_entry then redirects back to show_entries.
My problem is that form.errors are not routed to show_entries, so the user never sees them. I'm not sure of the best way to go about this, or if I'm even on the right track with the way I've divided up the views.
Here's what I currently have:
def show_entries():
entryForm = EntryForm()
entries = g.user.entries
return render_template('show_entries.html',
entries=entries,
entryForm=entryForm)
def new_entry():
form = EntryForm()
if form.validate_on_submit():
newEntry = Entry(g.user, form.time.data)
db_session.add(newEntry)
db_session.commit()
flash('New entry was succesfully posted')
return redirect(url_for('show_entries'))
The normal pattern is to have /show_entries as a listing page with new_entry as the form. When you do a GET request to new_entry you get the form, then POST to it to add the entry. That way if there's an error you can just show it next to the form - all the data is available. If you split the views as you have then you'll need some way of moving the error data (and form data) from the new_entry view to the show_entries view.
Something more like (untested):
def show_entries():
entries = g.user.entries
return render_template('show_entries.html',
entries=entries)
def new_entry():
form = EntryForm()
if form.validate_on_submit():
newEntry = Entry(g.user, form.time.data)
db_session.add(newEntry)
db_session.commit()
flash('New entry was successfully posted')
return redirect(url_for('show_entries'))
return render_template('show_new_entry_form.html',
entryForm=form)

Categories