Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Refreshing Table View Efficiently
I am using Django as my backend and inside my iOS application , I am fetching data through API's. I have a UITableView where I am fetching a list of places which also have a rating value with them. After implementing the refresh control I noticed that whenever I used to refresh, it used to append the new data in the array and created duplicity. I thought of a very simple solution which is that we can actually empty our array when refreshing so that we can avoid duplicity. Is it the most efficient way to do this? I am concerned because right now I have 3 places in my backend which I am trying to fetch and what about when there will be hundreds , will we have any performance impact ? -
Strange message in my Django Development server
This night, my Django development server displayed several messages : [29/Aug/2017 02:14:08] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00+&à\x00\x00\x00\x00\x00Cookie:') [29/Aug/2017 02:14:08] "+&àCookie: mstshash=hello" 400 - [29/Aug/2017 02:24:17] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00+&à\x00\x00\x00\x00\x00Cookie:') [29/Aug/2017 02:24:17] "+&àCookie: mstshash=hello" 400 - [29/Aug/2017 02:34:15] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00+&à\x00\x00\x00\x00\x00Cookie:') [29/Aug/2017 02:34:15] "+&àCookie: mstshash=hello" 400 - [29/Aug/2017 02:44:11] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00+&à\x00\x00\x00\x00\x00Cookie:') [29/Aug/2017 02:44:11] "+&àCookie: mstshash=hello" 400 - "+&àCookie: mstshash=hello" 400 - [29/Aug/2017 02:44:11] "+&àCookie: mstshash=hello" 400 - "+&àCookie: mstshash=hello" 400 - Any idea of what is it ? A kind of attack ? Thanks -
Django, extract kwargs from url
Suppose I have a url pattern url(r'^/my_app/class/(?P<class_id>\d+)/$', my_class.my_class, name='my_class') For a given url http://example.com/my_app/class/3/, I'd like to get class_id. I can do this with regex myself. I am wondering if there's a utility function for this since Django is already doing this to resolve url to a view. -
How to display a image from Input File
Is there a way to show the image that the user has chosen from the InputFile. <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {{ form.image }} # the InputFile </form> <img src="{{ form.image.url }}"/> -
How to set secured path settings using Python
I need one help. I am uploading file into folder and for that I have set constant in settings.py file using Python. I am explaining my code below. settings.py: FILE_PATH = os.getcwd()+'/upload/' views.py: report = Reactor.objects.all() filename = str(uuid.uuid4()) + '.csv' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+filename with open(settings.FILE_PATH + filename, 'w') as csv_file: file_writer = csv.writer(csv_file) response_writer = csv.writer(response) file_writer.writerow(['Name', 'Status', 'Date']) response_writer.writerow(['Name', 'Status', 'Date']) for rec in report: if rec.status == 1: status = 'Start' if rec.status == 0: status = 'Stop' if rec.status == 2: status = 'Suspend' file_writer.writerow([rec.rname, status, rec.date]) response_writer.writerow([rec.rname, status, rec.date]) return response Here I need the secured file path to upload the downloaded file into folder using Python and Django. -
Django timezone.now() not returning current datetime when script running using supervisor
I am running python script using supervisor. Script has function timezone.now(). This always returns date when I started supervisor. I am not able to find out why timezone giving the wrong date. Can anyone help? -
Is there a way to use Django's default password reset without sending reset link via email?
Is there a way to use django's inbuilt password reset function without sending reset links via email or without the email option. I am currently developing a simple system with a few number of users on which sending emails are not needed.Thanks in advance -
Django unique URL access per user
urlpatterns = [ url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), ] With this url pattern, what would be the best way to define in the view that this url should only be accessed once by the current user, and that to read another news the first one should be closed? -
Django- Concurrent request handling with db.sqlite3 models, need best approach
I have developed my first Django web app which pulls data from RTC and displays content in the dash board. I'm storing the data in to sqlite3 db and from there fetching the data on to the web page. As this data will get changed frequently, I want to use cron job to periodically (after each 10 min) delete the existing content in the Models and write the latest data. Also, as this will be used by multiple users I wanted to know the best approach to handle concurrency in sqllite3. There might be chances that users will access the web at the time of deleting and rewriting new content in the models. I realized that select_for_update() will do only row level locking which will only work in other db's like oracle, mysql etc but didn't find sqlite3 there. Moreover in my scenario Do I need table level locking ? how would I do it ? I had been through the link https://medium.com/@hakibenita/how-to-manage-concurrency-in-django-models-b240fed4ee2 Where it is given about two approaches Pessimistic(which has row level locking mentioned) and optimistic( Don't think it works in case of multi user , in my scenario) Pls throw some light on the best approach to … -
The view savedb.views.cost didn't return an HttpResponse object. It returned None instead
In view.py from django.shortcuts import render from savedb.models import Cost from savedb.forms import CostForm from django.http import HttpResponseRedirect def cost(request): if request.method == 'POST': form=CostForm(request.POST) if form.is_valid(): date = request.POST.get('date', '') cost = request.POST.get('cost', '') cost_obj = Cost(date=date, cost=cost) cost_obj.save() return HttpResponseRedirect(reverse('savedb:cost')) else: form = CostForm() return render(request,'savedb/cost.html',{'form':form,}) And error is The view savedb.views.cost didn't return an HttpResponse object. It returned None instead. how to solve this error ...please help me ....thank in advance. -
How to detect the path traversal injection using Python
I have one doubt. I am downloading some file and storing it inside the project folder using Python. I am explaining my code below. report = Reactor.objects.all() filename = 'status.csv' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+filename with open(settings.FILE_PATH + filename, 'w') as csv_file: file_writer = csv.writer(csv_file) response_writer = csv.writer(response) file_writer.writerow(['Name', 'Status', 'Date']) response_writer.writerow(['Name', 'Status', 'Date']) for rec in report: if rec.status == 1: status = 'Start' if rec.status == 0: status = 'Stop' if rec.status == 2: status = 'Suspend' file_writer.writerow([rec.rname, status, rec.date]) response_writer.writerow([rec.rname, status, rec.date]) return response Here I am writing the content from database into .csv file and saving it into one folder using Python. I need to know which line might create path traversal vulnerabilities and in which way it can be prevent. -
django: middleware process_request and process_response
question: after django 1.10 is it safe to say that if a middleware's process_request is called then this middleware's process_response will be called no matter what happens? by no matter what happens I mean the machine runs django server is ok at least -
How does csrf_exempt works in django?
I have a server running on JavaScript trying to post username and password to another webpage running django. I understand that django requires you to include csrf tokens. i have control of both server and codes, what I wanted to achieve is instead of manually enter username and password, I wanted to post using JavaScript to django. Let's say the django login page is "https://mayan/authentication/login/?next=/", it has username password text box and a submit button. since I don't have the csrftoken on my JavaScript server, I chose to disable csrf token instead. In "urls.py", the url patterns "url(r'^login/$', csrf_exempt(login_view), name='login_view')". My understanding is this will exempt the login page from csrf authentication? But what I need to be able to login using post, $.post({ url:"https://mayan/authentication/login/", data:"username=admin&password=mypassword&next=/", }); Am I posting wrong? or am I exempting csrf wrongly? -
__init__() got an unexpected keyword argument 'user' when I try to filter
I would like to filter through the restaurants that the request.user has done. following the docs but i keep getting init() got an unexpected keyword argument 'user' when I try to filter forms.py from .models import Restaurant from .models import Item from django import forms class LocationCreate(forms.ModelForm): class Meta: model = Item fields = [ 'restaurant' 'category', 'food_name' ] def __init__(self, user=None, *args, **kwargs): super(ItemCreate, self).__init__(*args, **kwargs) self.fields['restaurant'].queryset = Restaurant.objects.filter(owner=user) models.py class Restaurant(models.Model): restaurant_name = models.CharField(max_length=250) restaurant_photo = models.ImageField(upload_to='roote_image') category = models.ManyToManyField(Category) timestamp = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) owner = models.ForeignKey(User) def get_absolute_url(self): return reverse('post:detail', kwargs={'pk': self.pk}) class Item(models.Model): restaurant= models.ForeignKey(Roote, on_delete=models.CASCADE, null=True) food_name = models.CharField(max_length=1000) category = models.CharField(max_length=250) owner = models.ForeignKey(User) def __str__(self): return self.food_name def get_absolute_url(self): return reverse('post:detail', kwargs={'pk': self.pk}) views.py class ItemCreate(CreateView): model = Item fields = ['restaurant','category ', 'food_name '] success_url = reverse_lazy('post:index') def form_valid(self, form): if form.is_valid(): roote = restaurant.objects.filter(owner =self.request.user) instance = form.save(commit=False) instance.owner = self.request.user return super(ItemCreate, self).form_valid(form) def get_form_kwargs(self): kwargs = super(ItemCreate, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs The form works without the filter but it brings in every instance of a restaurant that has been made in the web site -
Want to create search field but error 'WSGIRequest' object has no attribute 'request'
I am doing a django project, a music app .It contains artist name,album title,genre and image. When I create a search form ,I get this error.I am using django version 1.9.1 view.py from django.views import generic from . models import Album from django.views.generic.edit import CreateView , UpdateView ,DeleteView from django.core.urlresolvers import reverse_lazy from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login from django.views.generic import View from .forms import UserForm from django.db.models import Q def get_queryset(self): query= self.request.GET.get('q') if query: return Album.objects.filter(Q(album_title__icontains=query)) else: return Album.objects.all() form.py <form class="navbar-form navbar-left" method="GET" action=""> <div class="form-group"> <input type="text" class="form-control" name="q" value='{{ request.GET.q }}'> </div> <button type="submit" class="btn btn-default" >search</button> </form> url.py #checking for search url(r'^search/$', views.get_queryset, name='search'), image of error in browser https://ibb.co/ct7sZ5 -
How to have only CSV, XLS, XLSX options in django-import-export?
I have implemented django-import-export for my project. It provides me many file format options by default fro both import and export. How to restrict the file formats to only CSV, XLS and XLSX ? -
Django CMS Landing Page
DjangoCMS page tree is as followed. What is the best practice to not have "landing" as a nav-item but still render as the homepage. Should my base url config be modified or menu.html template? Page Tree Layout Thanks in advance, Greg -
> Unexpected token '<' [duplicate]
This question already has an answer here: unexpected token < in first line of html 2 answers In my project I get the bellow error in browser: Unexpected token '<' But the code seems no error. -
Getting User Information from Django Python Social Auth in the view
First time working with python-social-auth and Django but having trouble figuring out exactly how much information about the user's social account is available to me. When I access the extra_data of the UserSocialAuth object I can get the uid, and the access_token. To get additional details am I to feed those through the social company's (ex facebook) API? I can see that for some social auths like facebook Django's user object is magically populated with the first and last names from the social profile, but for others like LinkedIn that doesn't work. How do i find out which information is available for each social auth without manually probing each one? I'm just trying to get as much "Profile" data from the user and am worried going through the API is the "long way" of achieving this. I have actually read through the documentation but it may be too advanced for me; im not sure how to use the data that is acquired by the pipeline from the view. I'm not even sure if that sentence makes sense! -
change the status being shown when either one of the button has been selected in a table Django
May i know why is my status remain unchanged when either "approve" or "deny" button has been selected for that particular row. How can i pass the value that i change in views.py back to my html file in order to print out the status ? Should i declare the Action field in models.py since action is just 2 buttons with name of approve and deny? .html file <form method="POST" action=""> {% csrf_token %} <table id="example" class="display" cellspacing="0" width="100%" border="1.5px"> <tr align="center"> <th> Student ID </th> <th> Student Name </th> <th> Start Date </th> <th> End Date </th> <th> Action </th> <th> Status </th> </tr> {% for item in query_results %} <tr align="center"> <td> {{item.studentID}} </td> <td> {{item.studentName}} </td> <td> {{item.startDate|date:'d-m-Y'}} </td> <td> {{item.endDate|date:'d-m-Y'}} </td> <td> <input type="submit" name="approve" id="approve" value="approve" > <input type="submit" name="deny" id="deny" value="deny" > </td> <td> {% if not item.action %} Pending {% endif %} </td> </tr> {% endfor %} </table> </form> when i try to print query_results in console, i can't see that the status has been changed views.py def superltimesheet(request): query_results = Timesheet.objects.all() data={'query_results':query_results} supervisor = SuperLTimesheet() if request.POST.get('approve'): supervisor.status = "approved" supervisor.save() return redirect('/hrfinance/superltimesheet/') elif request.POST.get('deny'): supervisor.status = "denied" supervisor.save() return redirect('/hrfinance/superltimesheet/') return … -
How django receive post file from android
I use Django 1.11 and Python 3.5. I have a question about Django receive post file. I found when android post multipart/form-data file, my Django request.POST and request.FILES is null. Please help me how to receive post file. -
Django share requests.session() between views
I make 2-3 calls to an API URL per view and using requests.session() cuts down the connection time by a significant amount. Is there a way to keep the session open between views to avoid the initial setup time? -
django migrate error: django.db.utils.ProgrammingError: must be owner of relation gallery_image
I've done some changes to a site on the local version, pushed models to the server and did a makemigrations (revampenv) sammy@samuel-pc:~/revamp$ python manage.py makemigrations gallery Migrations for 'gallery': 0032_auto_20170829_0058.py: - Create model Area - Create model Color - Create model ThumbnailCache - Add field unique_key_string to image - Alter field example on image - Alter field timeline on image worked fine then I tried to migrate and I get this error (revampenv) sammy@samuel-pc:~/revamp$ python manage.py migrate Operations to perform: Apply all migrations: account, sessions, admin, auth, thumbnail, contenttypes, gallery Running migrations: Rendering model states... DONE Applying gallery.0032_auto_20170829_0058...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/sammy/revamp/revampenv/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards field, … -
Cronned Django command output not posted in tee from bash script
I'm trying to have a bash script that controled by cron to be ran every day and I would like to grep some lines from the python (Django) output and post it with slacktee to my slack channel. But I am only catching some warnings from the script, not my own prints (something to do with std::out and std::err)? But I can't seem to be able to debug it. #!/bin/bash printf "\nStarting the products update command\n" DATE=`date +%Y-%m-%d` source mypath/bin/activate cd some/path/_production/_server ./manage.py nn_products_update > logs/product_updates.log tail --lines=1000 logs/product_updates.log | grep INFO | grep $DATE So for each day, I'm trying to grep messages like these: [INFO][NEURAL_RECO_UPDATE][2017-08-28 22:15:04] Products update... But it doesn't get printed in the tee channel. Moreover, the file gets overwritten everyday and not appended - how to change that, please? The tail command works ok when ran in the shell by itself. How is it possible? (sorry for asking two, but I believe they are somehow related, just cant find an answer) This is just in case the cron entry. 20 20 * * * /bin/bash /path/to/server/_production/bin/runReco.sh 2>&1 | slacktee.sh -c 'my_watch' Many thanks -
How to pass several views return statements to one template in Django?
Currently I have one template file that displays some graph results based on one Django view, however, I would like to display in this same template another set of results from another function view. These are the details: first function view - This works OK, sending values to the second function view and rendering the results into the template. @api_view(['GET','POST',]) def tickets_results_test(request): if request.method == "GET": # ...do stuff... return render(request, template_name, {'form': form}) elif request.method == "POST": template_name = 'personal_website/tickets_per_day_results.html' year = request.POST.get('select_year', None) week = request.POST.get('select_week', None) receive_send_year_week(year,week) ... rest of the code ... data = { "label_number_days": label_number_days, "days_of_data": count_of_days, } my_data = {'my_data': json.dumps(data)} return render(request, template_name, my_data) second function view - I want to return these results into the template file. def receive_send_year_week(year,week): return year, week template file - I want to show the results from the second function view below the You are currently reviewing: {% extends "personal_website/header.html" %} <script> {% block jquery %} var days_of_data = data.days_of_data function setChart(){ ....do stuff to generate graphs... .... } {% endblock %} </script> {% block content %} <div class='row'> <p>You are currently reviewing:</p> </div> <div class="col-sm-10" url-endpoint='{% url "tickets_per_day_results" %}'> <div> <canvas id="tickets_per_day" width="850" height="600"></canvas> </div> …