Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
leaflet route360 using as input point geojson layer?
hello I have read this examples about leaflet route 360 services. is very interests but that examples work with static coordinates,my question is how to can use this services using some point GeoJSON layer ? my GeoJSON layer example: coords = []; var points = new L.GeoJSON.AJAX("{% url 'mylayer' %}",{ onEachFeature:function (feature,layer) { coords.push(feature.geometry.coordinates.reverse()); layer.on('click', function (e) { var field1=document.getElementById('f1'); field1.innerHTML=e.target.feature.properties.name; }); layer.bindPopup(feature.properties.name.toString()) } }); points.addTo(map); leaflet route 360 example : <script> // define a pair of coordinates, where the map should be centered // and should serve a the source for polygonization var latlon = [52.51, 13.37]; // add the map and set the initial center to berlin var map = L.map('map').setView(latlon, 14); map.attributionControl.addAttribution("ÖPNV Daten © <a href='https://www.vbb.de/de/index.html' target='_blank'>VBB</a>"); // initialise the base map r360.basemap({ style: 'basic', apikey: '__your-route360-api-key__' }).addTo(map); // create the marker and add it to the map var marker = L.marker((latlon)).addTo(map); // create the layer to add the polygons var polygonLayer = r360.leafletPolygonLayer().addTo(map); // you need to define some options for the polygon service // for more travel options check out the other tutorials var travelOptions = r360.travelOptions(); // please contact us and request your own key if you don't already have one travelOptions.setServiceKey('__your-route360-api-key__'); // set … -
Django 2.0 - Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name
I'm having this error message after trying to change my app's password. Do you have any idea of what's causing this route to fail? Actually, it is changing the password but it isn't rendering the success template "password_change_done.html". Thanks! app/urls.py from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'account' urlpatterns = [ # path('login/', views.user_login, name='login'), path('', views.dashboard, name='dashboard'), # login / logout urls path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), # change password urls path('password-change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] ERROR MESSAGE # NoReverseMatch at /account/password-change/ # Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. # Request Method: POST # Request URL: http://localhost:8000/account/password-change/ # Django Version: 2.0.4 # Exception Type: NoReverseMatch # Exception Value: # Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. # Exception Location: C:\env\django_social_website\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 # Python Executable: C:\env\django_social_website\Scripts\python.exe # Python Version: 3.6.3 # Python Path: # ['C:\\Projects\\django_social_website', # 'C:\\env\\django_social_website\\Scripts\\python36.zip', # 'C:\\ProgramData\\Anaconda3\\DLLs', # 'C:\\ProgramData\\Anaconda3\\lib', # 'C:\\ProgramData\\Anaconda3', # 'C:\\env\\django_social_website', # 'C:\\env\\django_social_website\\lib\\site-packages', # 'C:\\env\\django_social_website\\lib\\site-packages\\setuptools-28.8.0-py3.6.egg', # 'C:\\env\\django_social_website\\lib\\site-packages\\pip-9.0.1-py3.6.egg'] # Server time: Thu, 5 Apr 2018 … -
Why is my server returning the same response of a previous request? Maybe object lifetime is involved?
I'm developing a chat as the communication interface for human-AI dialog-based interaction. The system does not yet recongices natural human language, in a closer future it will have that feature implemented but, for the moment, I've though that it would be a good idea to use simple command line instructions, allowing some kind of interactions between the user and the AI agent. In order to achieve this, I've defined a very simple syntax for the commands, for example: /topic(Physics) This means "I want to talk about Physics". This command line goes through the chat GUI and it's sended to a REST API via HTTP protocol, using AJAX request. In the development server I have django 1.11.6, python 3.5.0 and the request is processed inside django-rest-framework, using a @api_view function. When the API view function receives that request, it creates an instance of the AI agent to parse and execute the command, returning the answer in the response object. @api_view(['POST']) def send_command(request): if request.method == 'POST': sentence = request.POST['sentence'] conversation_id = request.POST['conversation_id'] try: conversation = Conversation.objects.get(pk=conversation_id) # IA agent = Agent(conversation.user) answer = agent.answer(sentence) # other stuff here return Response(data=answer, status=status.HTTP_202_ACCEPTED) except Conversation.DoesNotExist: return HTTP_404_NOT_FOUND_RESPONSE Inside the agent, the command is … -
Django — improve `startswith` performance
How to improve performance of the following query? class Worker(models.Model): name = models.CharField(max_length=32, db_index=True) # This line is slow: Worker.objects.filter(name__startswith='John') I have already added an index to the model, but... it's simply not used. However, index does kick in when I do ordinary filtering without startswith: # This line is fast: Worker.objects.filter(name='John') Why index is not used with startswith? -
Heroku + Django + Dnsimple - How Do I redirect www request to non-www domain
Hi i have a django site on Heroku with Dnsimple to manage DNS. I am also using Django to force HTTPS. I am trying to follow google protocol so that I only have one domain https://example.com So that if a user visits http://www.example.com or https://www.example.com it will redirect to https://example.com My settings in Dnsimple look like this: ALIAS example.com example.com.herokudns.com CNAME www.example.com example.com.herokudns.com I tried deleting the cname and using the URL redirect in Dnsimple, but it isn't working. Can someone let me know the correct way to do this redirect? I've tried creating a middleware based on another outdated post, but it crashed my site. Looking for the right way to do this. Thanks -
Django DeleteView - send mail after successful deletion
I am using DeleteView exactly like explained in the docs https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-editing/#deleteview What would be the right method to add an extra send_mail() if the deletion was successful? For example, in CreateView i added it to form_valid() Methods can be found here: https://ccbv.co.uk/projects/Django/2.0/django.views.generic.edit/DeleteView/ -
django use ModelForm to validate a Model
Suppose I have a ModelForm for my Model with custom validation logic, and I want to reuse that to validate an existing model instance. Is there any way to do this? I thought I could just do something like MyModelForm(instance=foo).is_valid(), but that doesn't work for multiple reasons. I'd like to reuse the existing form validation to avoid duplication of code, but I can't find any way to do so. -
How to pass a python list of URLs to a Django template and make them clickable?
I have a python list of urls which looks like this: list = ['/abc/1', '/abc/3', '/abc/5', ... ] all these urls follow the url pattern 'abc/n/' which I have defined in urls.py. now I want to pass this list to a django template in such a way that each element of this list becomes clickable and runs the function corresponding to their url pattern on clicking them. I tried hardcoding the anchor tag to each element of this list. for example for i in range (len(list)): list[i] = "<a href = \'" + list[i] + "\'>click me</a>" and then sending this list to template via HttpResponse() function via a context. But this displayed the list items in raw text format instead of links -
Empty Django project with error: missing 1 required positional argument
I just started to learn Django, created first project using django-admin startproject Returner and got an error trying to run it: How I can solve that? Possibly, the problem is related to multiple version of software. I have Python2.7 with Django 1.11, Python3.5 with Django 2.0 and Python3.6 from Anaconda, without Django. But I have properly set command line aliases from Python to Python3.5, from pip to pip3.5, and from django-admin to python /.../python3.5/.../django-admin.py And generated files have the comment: Generated by 'django-admin startproject' using Django 2.0.3. And this code: import sys print('Python:') print(sys.version) import django print('\nDjango:') print(django.VERSION) Turns into: Python: 3.5.0b2 (v3.5.0b2:7a088af5615b, May 31 2015, 01:00:01) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] Django: (2, 0, 3, 'final', 0) -
What tecnologies choose for Android project with Server/Database
I want to create a little app in Android that will obtain the gps coordinates of the user and save them in a Server for later view. I haven't touched Servers much so I'm a little lost on what's the best one for my project. Some friends suggested a sever in Python with DJango and a PostgresSQL database, but searching for it I saw that DJango is mostly user for web development so I don't know what to think. Any suggestions on what should I use? -
How to make a histogram clickable using django
I have a task in which i have to plot histogram and when i click the bars of histogram it should show 3rd value of the respective bar.I have been restricted to use django for backend and angular for frontend.Can u give me some advice or steps to achieve this task ? -
i want a button that Save a form to session
I have a form that is quite long, and I want my user to be able to save it in the session, do something else and go back to it later. I was thinking of a button somewhere in the middle that activates the save-to-session action and leads another form to create a necessary object. <a href="{% url 'tag:create_new_tag'%}"> <button class="btn btn-primary" value=""> Add New Tag </button> </a> The problem is that if i insert my button without any type (like in the code above), the form is submitted and my object saved to database, though I just want it to be saved in session. on the other hand, if i add a type=button attribute, the HTTP request will just be a GET, so I can't retrieve the fields that were complete so far. how then is the best way to do that ? -
Does django cache related tables when they are used in filter()
For instance: e = Entries.objects.filter(blog__name='Something') Does this cache blog as well or should I still add select_related('blog') to this. -
Returning the result of celery task to the client in Django template
So I'm trying to accomplish the following. User browses webpage and at the sime time there is a task running in the background. When the task completes it should return args where one of args is flag: True in order to trigger a javascript and javascript shows a modal form. I tested it before without async tasks and it works, but now with celery it just stores results in database. I did some research on tornado-celery and related stuff but some of components like tornado-redis is not mantained anymore so it would not be vise in my opinion to use that. So what are my options, thanks? -
Django uploading/downloading multiple files
Using Django 2.0 What i'm trying to do is post a link for each file uploaded. But my problem is that when I upload multiple files, the field only takes the last one. So long I have tried this: In my CBV def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('Resource_file') if form.is_valid(): for f in files: f.save() return self.form_valid(form) else: return self.form_invalid(form) in my forms.py Resource_file = forms.FileField( widget=forms.FileInput(attrs= { "multiple": True, } ), required = False ) for example 6 files were uploaded and saved on my media root yet only one is related with the field... How can I save multiple files and display each one on my template? Extra: How can I verify the file extension when displaying them on my template? I would like to make like an icon for each type of file. -
Opencv Live Stream from camera in Django Webpage
I am making a project in Django. And I want to show live feed from camera on a webpage. But I am not sure on how to return live feed I get from a cam on a web page. Here's my code that I have tried so far but haven't seen any progress. from django.shortcuts import render from .forms import FaceAdditionForm import cv2 import numpy as np from django.http import StreamingHttpResponse def capture_video_from_cam(): cap = cv2.VideoCapture(0) currentFrame = 0 while True: ret, frame = cap.read() # Handles the mirroring of the current frame frame = cv2.flip(frame,1) currentFrame += 1 def addfaces(request): add_faces_form = FaceAdditionForm() if add_faces_form.is_valid(): add_faces_form.save() return render(request, 'base.html', {'add_faces': add_faces_form}) def show_video_on_page(request): resp = StreamingHttpResponse(capture_video_from_cam()) return render(request, 'base.html', {'video': resp}) -
On demand column creation for model in django
So, My models.py has this model class student(models.Model): ID = models.CharField(default='DUMMY_ID',primary_key=True,max_length=10) Score = models.CharField(default='DUMMY_Score',max_length=150) class = models.CharField(default='DUMMY_class',max_length=20) and the requirement now is that a user (consider him to be admin/the director of the institute) should be able to add a new column to the database like section or rank or something. so is there any way to add a new column to the table dynamically and if yes can you please explain it with an example as I am a beginner at Django. DOUBT: if there's some way to do this, then will the above models.py have another entry (eg: rank= models.CharField(default='rank',max_length=20) after the change is made? and what data is filled for the previous entries in the new column? -
TypeError: QuerySet.annotate() received non-expression(s): 0.0 m
I'm trying to list places ordered by distance from user location, I get an error of empty query. my models are defined as this in models.py class Place(models.Model): name = models.CharField(max_length=200) id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular shop across whole library") location = gis_models.PointField("longitude/latitude", geography=True, blank=False, null=True) #objects = gis_models.GeoManager() def __unicode__(self): return self.name, 'location' class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) maplocation = gis_models.PointField("longitude/latitude", geography=True, blank=False, null=True) and in my views.py I tried to do : @login_required def home(request): """ View function for home page. """ place_list = Place.objects.all() user = User.objects.get(email=request.user) ref_location = user.maplocation place_ordered = Place.objects.annotate(distance=D(('location', ref_location))).order_by('distance') and when I try to open my web page I get this error QuerySet.annotate() received non-expression(s): 0.0 m. -
NameError-- name 'logs' is not defined
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^logs/', include(logs.urls)), ] I have written this code in main/urls.py file code in logs/urls.py is below:- from django.conf.urls import url from . import views urlpatterns = [ url(r'^$/', views.index, name='index'), ] and i am accessing http://localhost:8000/logs Error:- NameError name 'logs' is not defined -
django admin page and JWT
We are using django-rest-framework with django-rest-framework-jwt for authentication and it works everywhere except the django admin page at ip:port/admin/. That still wants username and password. Is there a setting or way to bypass that so it recognizes the JWT? jwt is the only auth set in the settings.py file. Session authentication is not in there anymore. -
Seeking suggestion/solution for an unexpected app behavior due to Gunicorn multiple workers in Django+Nginx+Gunicorn environment
I've recently bothered by an unexpected Django application behavior in the production environment of Django+Nginx+Gunicorn+MySQL. This behavior does not exist on Django development server so I barely foundd it before deployment. However I've sort of figured out a work-around after analyzing the production logs but I wonder if there's a better way to solve this issue, or my design is flawed so that I'll need to redesign. To simplify my questions, I separated and extracted the scenario where this behavior occurs: the application uses one class-based view with one model to feed one number to the front-end on one page load (users click next to next page load, the app feeds next number). The number is from a list of five numbers. These five numbers are feeded in order. When all five are feeded, the list will be shuffled and the five numbers in the shuffled list will be feeded in order again. For example, I have an list [0, 1, 2, 3, 4]. The first page load will feed 0 to the front-end by reading the URL parameters (so the view knows it's getting started). On front-end, 0 is shown, and click next to the next page. The next … -
Javascript variable in same django template
In my django app there is a javascript modal which retrieves all the available images from backend.(I send a django variable in the template and display all the images on modal) In the app I have Gridster widgets which already have some images on them which are put up via JSON On each button there is a + button which opens the modal and user can add images on the widget from which the + button is clicked Current State The modal which opens when I click + button currently has all the images.Since there are images present on the widgets I dont want those images to appear in the modal. Desired Output I want the modal to update in realtime.Of all the available images modal should only show the images which are not present on the widget. What I have done so far The images on widget have their names in a textarea on widget.As soon as I delete an image the name of that image gets deleted from textarea. In js I extract the content of that textarea and delete it from the django variable which is sent from template(it has names of all the images in it) … -
LinkedIn sign in in single page applications
We are trying to implement login with linkedin in angular application with Django in it's backend for apis. Currently we have an api let's call it /login which accepts Basic Authentication i.e. user name and password and on success generate sessionId & csrf token on server and returns in response header so that cookies can be created on front end also returns user object to use on front end. And in subsequent requests this session id is passed as header params and used to identify user. Now we have added linkedin as sign in option and using linkedin javascript sdk have setup login flow but now want to explore best possible way to generate sessionId of this login with linkedin. One option which I have given thought of is to write a custom authentication backed for linkedin user authentication in Django and after login success from linkedin pass email id to this /login api and generate sessionId on server and follow same older process afterwards. But above solution won't work for us as it's not secure as anyone can call this api with emailId and get details of all user and can get logged in to system as well. So … -
django shows only last line while looping
I am trying to upload csv file to filesystem and show within the html without storing in the database. Below code is working but... I added below line to my code; messages.add_message(request, messages.INFO, line) so that I can follow line variable. I can see that code is looping all the csv file def check_fp(request): if not request.user.is_active: return render(request, 'login.html') else: if request.method == 'POST' and request.FILES['csv_file2']: myfile = request.FILES['csv_file2'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) data = csv.reader(fs.open(filename, mode='r')) for row in data: if row[0] != 'FP_Item': line = row[0] messages.add_message(request, messages.INFO, line) context = {'line': line} return render(request, 'check_fp.html', context) return render(request, 'check_fp.html', {}) But I can only see the last line from the csv file at html file.Here is my loop within html file. Why I am not seeing all ? <tbody><tr> <td width="25%><a href="#"> {% for line in line %} {{ line }} {% endfor %} </a></td><td> -
Django simplest way to save file to folder on disk without using a model
I'm trying to save a file from an upload directly to my folder media/files, exactly as described in this thread. Here my form code: from django import forms class UploadForm(forms.Form): title=forms.CharField(max_length=50) file=forms.FileField() Here's my view code: def uploadview(request): if request.method == 'POST': form=UploadForm(request.POST, request.FILES) if form.is_valid(): uploaded_filename=request.FILES['file'].name full_filename=os.path.join('media', 'files', uploaded_filename) fout=open(full_filename, 'wb+') file_content=ContentFile(request.FILES['file'].read()) for chunk in file_content.chunks(): fout.write(chunk) fout.close() return HttpResponseRedirect('/App/') else: form=UploadForm() return render(request, 'App/uploads.html', {'form':form}) I get no errors, just a redirect to the /App/ page and no file has been downloaded. My goal here is no be able to just get a file done on disk like you can do in PHP with this simple command. move_uploaded_file(($_FILES["filetoupload"]["tmp_name"]), $target_file)