Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django asynchronous tasks locally
I have a web application that runs locally only (does not run on a remote server). The web application is basically just a ui to adjust settings and see some information about the main application. Web UI was used as opposed to a native application due to portability and ease of development. Now, in order to start and stop the main application, I want to achieve this through a button in the web application. However, I couldn't find a suitable way to start a asynchronous and managed task locally. I saw there is a library called celery, however that seems to be suitable to a distributed environment, which mine is not. My main need to be able to start/stop the task, as well as the check if the task is running (so I can display that in the ui). Is there any way to achieve this? -
Django view doesn't accept POST from html
I am making a login view, but I get an error indicating that POST method is not allowed. This is the view class: class LogIn(View); def get(self, request): if request.method == 'POST': username = request.POST.get('email') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('control_center')) else: return HttpResponse('Account not active!') else: return HttpResponse('Invalid user/name!') else: return render(request, 'UserManagerApp/login.html', {}) And this is the html form: <form action="{% url 'UserManagerApp:login' %}" method="post"> {% csrf_token %} <div class="card-body"> <label for="email">Email address</label> <input type="email" class="form-control" name="email" placeholder="example@attractora.com"> <label for="password" style="padding-top: 10px">Password</label> <input type="password" class="form-control" name="password"> </div> <div class="card-footer text-center"> <button type="submit" class="btn btn-primary" value="Login">Accept</button> <button type="cancel" class="btn btn-danger">Cancel</button> </div> </form> And this is the error I get: [01/Feb/2018 21:00:45] "GET /user_manager/login/ HTTP/1.1" 200 1686 Method Not Allowed (POST): /user_manager/login/ [01/Feb/2018 21:11:25] "POST /user_manager/login/ HTTP/1.1" 405 0 I am following some online directions but, evidently, I went astride at some point. -
How to write test for django FileBrowser - python
I used FileBrowser in my django project in one of models. class Person(models.Model): name = models.CharField(max_length=50) avatar = FileBrowseField( max_length=200, directory='pics/', extensions=['.jpg', '.jpeg', '.png', '.gif'], ) How can I write test for it? -
Design/Tool Suggestions Moving towards Remote Processing with Python
As the title suggests, I've made a desktop application and I'm looking to move towards re-implementing it with remote processing capability (as an example, utilizing something like Amazon Web Services). What I've got now is a master/slave setup with several machines on a local network. I use NFS, Redis, RabbitMQ, and Celery for distributed processing. However, at this point in time, some of my processing takes place during run time of my application, on the user's machine. I'd like to move towards a system where the user's machine isn't required to do any processing. In other words, I'd like to completely segment the system into back-end/front-end sections. Another reason I'm making this transition is to keep all back-end source code, containing all personally developed algorithms and methods, away from the users eyes. In a word: Security. From my reading, I've learned that the only real way to secure python source code is to implement my software as a service. First question: Is the type of system I'm suggesting SaaS (Software as a Service)? I'm wary to call it that since I'm not looking to build a webpage. The user will still install the UI portion of my system on a … -
Users can authenticate with DRF, but no permissions on POST
If i run: curl --user test:incorrectpass -d '{"name":"testplatform"}' -X POST http://localhost:8080/api/v1/platforms I get an error that says invalid credentials (as I should). If I pass in the correct credentials, this error goes away but I get a "you do not have permission" The user that I'm authenticating was created from the django admin panel and granted all permissions from the admin panel. Not sure if there is something else I need to do on the DRF side to enable permissions... class AuthOnPostOnly(permissions.BasePermission): def has_permission(self, request, view): # only accept POST request with correct token if request.method == 'POST': username = request.META.get('USERNAME') password = request.META.get('PASSWORD') if not username and password: return None try: authenticate(username=username, password=password) except User.DoesNotExist: raise exceptions.AuthenticationFailed('invalid credentials') else: return True This is a very barebones permission and more of a POC, ultimately I just want to check if user/pass are a match and if so move on, if not, raise an error. -
Reverse for 'restaurants_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Need help unable to rectify this error : NoReverseMatch at /myrestaurants/ Reverse for 'restaurants_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Request Method: GET Request URL: http://127.0.0.1:8000/myrestaurants/ Django Version: 1.8.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'restaurants_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Exception Location: /usr/lib/python2.7/dist-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 495 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/vaibhav/Desktop/projects/myrecommendations', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/vaibhav/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0'] Server time: Fri, 2 Feb 2018 02:02:23 +0000 My index.html looks like this : {% block content %} <nav class="nav nav-bar"> <div class="pull-right" style="padding: 20px;"> {% if user.is_anonymous %} <a href="{% url 'account_login' %}">Sign In</a> <a href="{% url 'account_signup' %}">Sign Up</a> {% else %} <a href="{% url 'account_logout' %}">Sign Out</a> {% endif %} </div> </nav> <div class="container"> <h1 class="app-font">Welcome to Food-orders</h1> <form method="GET" class="form-inline" action="{% url 'restaurants_list' %}"> <input type="text" id="locator" class="form-control"> {% buttons %} <button type="submit" class="btn btn-success"/> {% bootstrap_icon "glyphicon glyphicon-search" %} SEARCH FOR RESTAURANTS </button> {% endbuttons %} </form> </div> {% endblock %} My myrestaurants/urls.py looks like this : from django.utils import timezone from django.conf.urls import url from django.views.generic import ListView, DetailView, UpdateView import myrestaurants … -
Using Model class name names in DRF serializer
I have been given an example JSON output which I must reproduce uisng Django Rest Framework. Ths is the output: "results": [ { "Brand": [ { "BrandName": "20/20", "Store": [ { "ID": "4", "Languages": [ "eng" ], etc However, I don't see how DRF/Django can models this. For example, Brand and Store appear to me to be a 'model class name' (i.e. Brand) and NOT a feild name, right? Can this be done or have a missed something with models? For example, this is what I tried to do below and gives a whole different JSON output. class Brand(models.Model): BrandName = models.CharField( max_length=50, unique=True, ) class Store(models.Model): Languages = fields.ArrayField( models.CharField(max_length=50, blank=True) ) Brand = models.ForeignKey("Brand", models.CASCADE, null=False, blank=False, related_name="stores") class BrandSerializer(serializers.ModelSerializer): stores = Storeserializer() class Meta: """ Serializer configuration. """ model = Brand fields = ("BrandName", "stores") Which gives me "results": [ { "BrandName": "Test", "stores": {} } ] } -
Django filter() Query giving extra result in data
I have 2 objects contacts, companies_contact, I am using distinct() to get distinct value from contact the code looks like this: contacts = Contact.objects.filter(campaign=campaign) companies_contact = contacts.distinct('website') So, when I iterate the companies_contact I'm getting the following output... >>>for i in companies_contacts: i.created_at, i.website (datetime.datetime(2018, 1, 9, 10, 57, 40, 447445, tzinfo=<UTC>), 'www.creamstone.com') (datetime.datetime(2018, 1, 19, 6, 27, 32, 758898, tzinfo=<UTC>), 'www.facebook.com') (datetime.datetime(2018, 1, 18, 6, 20, 41, 145358, tzinfo=<UTC>), 'www.heteja.com') (datetime.datetime(2018, 1, 9, 12, 11, 17, 390755, tzinfo=<UTC>), 'www.kfc .com') (datetime.datetime(2018, 1, 31, 6, 44, 40, 916231, tzinfo=<UTC>), 'www.mvg.com') (datetime.datetime(2018, 1, 11, 12, 20, 55, 409986, tzinfo=<UTC>), 'www.subway.com') (datetime.datetime(2018, 1, 9, 9, 14, 58, 607180, tzinfo=<UTC>), 'www.websit.com') (datetime.datetime(2018, 1, 9, 6, 29, 53, 270203, tzinfo=<UTC>), 'www.website.com') (datetime.datetime(2018, 1, 9, 9, 22, 22, 869395, tzinfo=<UTC>), 'www.websitest.com') So, according to my understating companies_contact consists of this much data only but when I'm applying filter() on companies_contact with the different date which is not in above output then also it gives me the result. companies_contacts.filter(created_at__startswith='2018-02-01') The above query giving me the result but this created_at value is not there when I have iterate companies_contact I don't know why it is giving result and why it is working but I don't want result … -
Angular Django CSRF integration
I have a separate angular app and Django application running on different localhost ports with CORS enabled. My angular app sends its post requests to Django service endpoints to receive JSON response. I have attached the screenshot of angular project structure below. I need to know where I should integrate Django's CSRF token in my angular app assuming that I have one of my post request in Django.service.ts and what is the best practice that I need to follow? -
Connect Django to a table owned by a specific user in Oracle Database
I would like to have my Django connect to an already existing oracle database. This database contains multiple users and tables by each of them. How do I access the tables by a user and where do I need to provide this piece of code. -
ModuleNotFoundError: No module named 'login'
I have created application "login" django-admin.py startapp login In settings.py, I added the app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login', ] my views.py file content #views.py from login.forms import * from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.views.decorators.csrf import csrf_protect from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template import RequestContext @csrf_protect def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user( username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email'] ) return HttpResponseRedirect('/register/success/') else: form = RegistrationForm() variables = RequestContext(request, { 'form': form }) return render_to_response( 'registration/register.html', variables, ) def register_success(request): return render_to_response( 'registration/success.html', ) def logout_page(request): logout(request) return HttpResponseRedirect('/') @login_required def home(request): return render_to_response( 'home.html', { 'user': request.user } ) urls.py from django.conf.urls import patterns, include, url from login.views import * urlpatterns = patterns('', url(r'^logout/$', logout_page), url(r'^register/$', register), url(r'^register/success/$', register_success), url(r'^home/$', home), ) When i start the app, (project) H:\Django\myapp>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x05CDD9C0> Traceback (most recent call last): File "C:\Users\kalu\Envs\project\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\kalu\Envs\project\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Users\kalu\Envs\project\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Users\kalu\Envs\project\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\kalu\Envs\project\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper … -
django- how would I create a sort for a query to put one specific element first, then remaining by some field?
Specifically, I am looking to get a query of users. My User model has a first_name and last_name field. What I need to do is order the request.user at the top of the results, and the remaining users in alphabetical order by last_name, first_name. The last part is easy: q = User.objects.all().order_by('last_name', 'first_name') However I am not sure how to ensure that the request.user is the first result in the query. This is all being done for a django rest framework view, and thus (I believe) I need to have it done through a query which is passed on to the serializer. -
Which Layer does API access sit in?
I ma trying to wrap my head round the Django Framework and mapping it out on an architecture diagram. I am struggling to understand where the API calls are place (Model or View) and would like some guidance on this. -
Django go live with Nginx
I followed this tutorial to test going live with a django website. I don't have a DigitalOcean droplet but a local machine I have that eventually could be used as a server. Therefore, in the steps where I had to put the domain name I used the local machine IP address (it's the same IP address I use to login with ssh). All steps were ok and I have a response from whitin the local machine, i.e., if I open a browser in the local machine and with the IP address, the Django app runs ok. However, the same does not happen if I open it from an external computer. I'm not sure if it was suppose to work like that. Is it? If not what extra steps do I need to do to go public? -
Correctly doing a POST request via AJAX to a Django view
I'm a JS newbie coming from a server-side dev background. Currently I'm learning to perform a POST request via AJAX to a Django (Python) view. I'm running into the error AttributeError: 'NoneType' object has no attribute 'has_header'. Full traceback: Internal Server Error: /pcp/ Traceback (most recent call last): File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 499, in wrapper return wrapped(*args, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 76, in _cache_controlled patch_cache_control(response, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/utils/cache.py", line 59, in patch_cache_control if response.has_header('Cache-Control'): AttributeError: 'NoneType' object has no attribute 'has_header' I need help solving this. The AJAX request includes an image object. Here's how I'm setting it up: function overwrite_default_submit(e) { e.preventDefault(); var form = new FormData(); form.append("image", to_send, img_name); var xhr = new XMLHttpRequest(); xhr.open('POST', e.target.action); xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken')); xhr.send(form); } function get_cookie(name) { if (!name) { return null; } var value = "; " + document.cookie; var parts = value.split("; " + name + "="); if (parts.length >= 2) return parts.pop().split(";").shift(); } It seems the object being passed is empty. Which is strange because to_send has a value of Blob { size: 138223, type: "image/jpeg" } whereas img_name … -
Django nginx invalid HTTP_HOST header
I am getting emails every day from bots hitting my server with the wrong http_header. I followed the steps here: Django ERROR: Invalid HTTP_HOST header: u'/run/myprojectname/gunicorn.sock:' And I thought that would solve it. The problem is now that if you try to go to https://35...***/ I can still get it to trigger an Invalid HTTP_HOST email to myself. I tried solving this by adding listen 443 default_server;: server { listen 443 default_server; listen 80 default_server; return 444; } But now legit traffic to my site is also blocked. Here's my full config. Any help is much appreciated. server { # default server listen 80 default_server; return 444; } server { listen 80; server_name mysite.com www.mysite.com; root /home/ubuntu/web/troopers/; location /static/ { # if asset versioning is used if ($query_string) { expires max; } } access_log /home/ubuntu/web/logs/troopersAccess.log; error_log /home/ubuntu/web/logs/troopersError.log; location / { uwsgi_pass unix:///home/ubuntu/web/troopersuwsgi.sock; include uwsgi_params; } # what to serve if upstream is not available or crashes error_page 400 /400.html; error_page 403 /403.html; error_page 404 /404.html; error_page 500 502 503 504 /500.html; # Compression gzip on; gzip_http_version 1.0; gzip_comp_level 5; gzip_proxied any; gzip_min_length 1100; gzip_buffers 16 8k; gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript; # Some version of IE … -
Python Django - render OrderedDict in view like json
I'm new in Django and Python. I'm in HTML printing data from python using {{ body.example }} Some data is render ok in plain text, but there one that is printing like this: [OrderedDict([(u'value', u'5650.00'), (u'operation_number', 130990), (u'comments', u'TESTE'), (u'date', OrderedDict([(u'start', 20160519), (u'end', 20160519)]))])] How can I render this type of data like json(becouse the result from api is json): { "value": "5650.00", "operation_number": "130990", "comments": "TESTE", "date": { "start": "20160519", "end": "20160519" } } -
'list' object has no attribute 'prefixed_order_by_field' Django-tables2
In order to show plural tables in a view using Django-tables2, I assigned plural tables to a table variable and use RequestConfig as follows, tables = [ScheduleTable(qs_t2),ScheduleTable(qs_t2125),ScheduleTable(qs_gst)] RequestConfig(request).configure(tables) export_format = request.GET.get('_export', None) "'list' object has no attribute 'prefixed_order_by_field" was the error message when I ran this program. Do you know why? -
clear limit on Django QuerySet
It's possible to limit the results on a QuerySet by doing something like this: qs = MyModel.objects.all()[:3] Since the QuerySet is usually evaluated lazily, is it possible to remove this limit from the qs before it's iterated over? I was hoping for something straight forward like qs = qs[:] or qs = qs[0:] but neither work. So far the only thing I can get to work is qs.query.clear_limits() but I'm not really sure if that's part of the public API (I had to wade through Django source code to find it). -
leaflet with django says openPopup is undefined
I am writing a simple map application and I want to open a popup when the mouse is released over a marker on my map. Here is my code (index.html): {% load leaflet_tags %} <html> <head> {% leaflet_js %} {% leaflet_css %} <style> .leaflet-container { height: 100%; } </style> <script type="text/javascript"> var popup = L.popup(); function onMouseUp(e){ popup .setLatLng(e.latlng) .setContent("HAHA") .openOn(yourmap); } function map_init_basic (map, options) { var marker = L.marker([59.3, 18]).addTo(map); marker.on('mouseup', onMouseUp); } </script> </head> <body> <h1>Stockholm Issues</h1> {% leaflet_map "yourmap" callback="window.map_init_basic" %} </body> </html> I get the error: openOn — leaflet.js:2446 TypeError: t.openPopup is not a function. (In 't.openPopup(this)', 't.openPopup' is undefined) If I just do a bindPopup it works fine. What am I missing? -
Call method on Django fields
class Colour(models): ... def colour_preview(self): return format_html(...) class ColourTheme(models): colour1 = models.ForeignKey(Colour) colour2 = models.ForeignKey(Colour) colour3 = models.ForeignKey(Colour) ... def preview(self): for field in self._meta.get_fields(include_parents=False): if (field.related_model == Colour): field.colour_preview() I have a ColourTheme model with multiple Colour foreign keys, and I want to call a function on each of the Colour objects referred to by those fields. The last line of code above fails. I would like to call colour_preview on all Colour fields without hardcoding them (self.colour1.colour_preview() works but not ideal). How might I achieve this? -
search api returns empty list using drf haystack for elastic search
I have following models, class ProductKeyword(models.Model): name = models.CharField(max_length=100) product = models.ManyToManyField(Product, related_name="products") date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.name) and search index, class ProductKeyWordIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr="name") product = indexes.CharField(model_attr="product") autocomplete = indexes.EdgeNgramField() @staticmethod def prepare_autocomplete(obj): return " ".join(( obj.name, obj.product )) def get_model(self): return ProductKeyword def index_queryset(self, using=None): return self.get_model().objects.filter( date_created__lte=timezone.now() ) and the viewset, class ProductKeywordSearchView(HaystackViewSet): index_models = [ProductKeyword] serializer_class = ProductKeywordSerializer and the url configuration, router = routers.DefaultRouter() router.register(r'prod_key', ProductKeywordSearchView, base_name="prod-key- search") # The API URLs are now determined automatically by the router. urlpatterns = [ url(r'^', include(router.urls)) ] and the settings.py (haystack configuration) HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://localhost:9200/', 'INDEX_NAME': 'bhkhata', 'INCLUDE_SPELLING': True, 'TIMEOUT': 300, }, } i saved data through django shell, and checked that the data are successfully saved in the ProductKeyword model. trying to get result using following search api, http://localhost:8090/api/hs/prod_key/?name=sayaabintel but its returning a empty list with 200 status. i am new in elastic search, so not sure what causing this above api to return a empty list, there could be one possibility that the object i am trying to search, not been indexed in elastic search, so i have … -
uWSGI sometimes stuck and send 502 error
Hello i am using no config file, just use systemd with next command to run uwsgi and very simple config --socket /var/uwgi/uwsgi.socket --module boost.wsgi_django --chmod-socket=666 -p 64 And sometimes i receive 502 like uwsgi is down but all is ok and no errors even log. It look like server is down for a half of a second and then all is ok again. -
FileField does not uploada anything django
please, drop me any advice. I will actually appreciate everything. Whenever I succesfully pass the entire flow uploading a field with the usage of django-based web application, nothing really happen. Proper records are being inserted into the database, but files by itselves are not copied to the server's filesystem. models.py from django.db import models from django.forms import ModelForm from .choices import * from .validators import validateExtensionOfTheFile from django.contrib.auth.models import User class MusicFile(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) image = models.FileField(upload_to="music_images/%Y/%m/%d", null=True, blank=True, validators=[validateExtensionOfTheFile]) forms.py from django import forms from .choices import * from .models import MusicFile class MusicFileForm(forms.ModelForm): class Meta: model = MusicFile fields = '__all__' exclude = ('owner') def __init__(self, *args, **kwargs): super(MusicFileForm, self).__init__(*args, **kwargs) self.fields['image'].required = False views.py @login_required def new_upload(request): if request.method == 'POST': form = MusicFileForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.owner = User.objects.get(username=request.user.username) post.save() return HttpResponseRedirect('/success/confirmed/') else: form = MusicFileForm() return render(request, 'new_upload.html', {'form': form}) new_upload.html {% extends 'base.html' %} {% block content %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary btn-block">Log in</button> </form> {% endblock %} @EDIT setting.py: TEMPLATES = [ { ... ... ... 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, … -
Safe way to have globally accessible JWT token in Django
There's a lot out there on how to issue JWT tokens to clients from Django, but I'm looking for a way to store a JWT token that is issued to the Django app for authentication against an external API. The setup: Django requests and receives token from external API. It is good for 24 hours. Every time a client a makes a request, the app must make an authenticated call to the external API. Ideally, if 3 clients make 2 requests each, we should only need to request a single JWT. 24 hours later, a fourth client makes a request. Django sees that the token is invalid and requests a new one. The problems here: Requests from multiple clients should not each require their own token. The token must be able to be changed (this rules out sticking it in the settings) The token must be stored securely. Ideas so far: Stick in the database with a field listing the expiry time. This seems questionable from a security standpoint. Implement some kind of in memory storage like this https://github.com/waveaccounting/dj-inmemorystorage . This seems like overkill. Any suggestions as to a better way to do this?