Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to match dictionary keys to model ids
I have a list similar to the following: my_list = ['1', '2', '1', '3', '2', '1'] These are votes and each vote is corresponds to an id from this model which contains the choices of a poll: class Choice(models.Model): question = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) I'm using Counter to count the votes and I end up with this: >>>votes = Counter(my_list) >>>print(votes) Counter({'1': 3, '2': 2, '3': 1}) Each key in this dictionary corresponds to an ID in the Choice model. How can I replace the key names of the dictionary with the corresponding choice_text for each ID? I would like to end up with a dictionary that looks as following: {'choice_text for id=1':3, 'choice_text for id=2':2, 'choice_text for id=3':1} -
Adding extra non modal data in django_filters.FilterSet class?
In filters.py, i have made class class ReportFilter_VCB_Execution_Details(django_filters.FilterSet): class Meta: model = VCB_Execution_Details fields = ['box_id','channel_id'] In views.py ved_list_qs = VCB_Execution_Details.objects.all() ved_list_filter = ReportFilter_VCB_Execution_Details(request.GET, queryset=ved_list_qs) So far so good Now i want to add data for box and channel_id which is coming from external source which is not any model in my django project. I can very well send those as list with return render along with ved_list_filter but i am looking for some way to add those data as filterset object inside ReportFilter_VCB_Execution_Details class. Just to avoid hassle in my template which is already very complex i am looking for such way. Any alternate way is well appreciated. -
Selenium/Django: webpage to automate another webpage?
I would like to build a web app in Django that would open and then automate another webpage through Selenium. But is that even possible, since Selenium requires Chromedriver, Geckodriver etc. to be downloaded to a computer? Should I host the webdriver somewhere (would Docker be appropriate for this purpose) and then use webdriver.remote() method? I would welcome any suggestions on how to approach this. -
Django-Channels fails while giving name or service unknown error
I've a fairly simple django-channels/daphne/asgi/redis app. The app never has any problem when using chrome but fails miserably when we use firefox (latest version ~ 60). I currently have the following error: api_1 | 2018-06-12 16:02:24,378 INFO In the connect method api_1 | xxxxxx:41647 - - [12/Jun/2018:16:02:24] "WSCONNECT /updates/" - - api_1 | 2018-06-12 16:02:25,049 ERROR Exception inside application: [Errno -2] Name or service not known api_1 | File "/usr/local/lib/python3.6/site-packages/channels/consumer.py", line 54, in __call__ api_1 | await await_many_dispatch([receive, self.channel_receive], self.dispatch) api_1 | File "/usr/local/lib/python3.6/site-packages/channels/utils.py", line 48, in await_many_dispatch api_1 | await dispatch(result) api_1 | File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 110, in __call__ api_1 | return await asyncio.wait_for(future, timeout=None) api_1 | File "/usr/local/lib/python3.6/asyncio/tasks.py", line 339, in wait_for api_1 | return (yield from fut) api_1 | File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run api_1 | result = self.fn(*self.args, **self.kwargs) api_1 | File "/usr/local/lib/python3.6/site-packages/channels/db.py", line 13, in thread_handler api_1 | return super().thread_handler(loop, *args, **kwargs) api_1 | File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 125, in thread_handler api_1 | return self.func(*args, **kwargs) api_1 | File "/usr/local/lib/python3.6/site-packages/channels/consumer.py", line 99, in dispatch api_1 | handler(message) api_1 | File "/usr/local/lib/python3.6/site-packages/channels/generic/websocket.py", line 19, in websocket_connect api_1 | self.connect() api_1 | File "./flypoll/consumers.py", line 146, in connect api_1 | async_to_sync(self.channel_layer.group_add)("flypoll_socket_clients", self.channel_name) api_1 | File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line … -
Django open html page from backend
How can I display an html page if an event is triggered at the backend with django? direction.py # render error html if list is empty if len(waypoint) == 0: print("Trip not possible with selected specs : Not enough charging stations") #open error.html page views.py def error(request): return render(request, 'routing/error.html') urls.py urlpatterns = [ url(r'^error/$', views.error), ] -
expected string or bytes-like object when parsing date
I am developing a simple social webapp where you can post on the wall. I keep receiving the below error despite taking many different approaches on storing datetime. However, things work fine for the same data type on other apps. I am stuck with this for 2 days now. TypeError at /wallpost/add_wallpost/ expected string or bytes-like object Request Method: POST Request URL: http://localhost:8000/wallpost/add_wallpost/ Django Version: 2.0.2 Exception Type: TypeError Exception Value: expected string or bytes-like object Exception Location: C:\Users\Rhonald.Rose\AppData\Local\Continuum\anaconda3\envs\mydjangoenv\lib\site-packages\django\utils\dateparse.py in parse_datetime, line 107 Python Executable: C:\Users\Rhonald.Rose\AppData\Local\Continuum\anaconda3\envs\mydjangoenv\python.exe Python Version: 3.6.5 My models.py class Wallpost(models.Model): content = models.CharField(max_length=1000, blank=True, null=True) author = models.ForeignKey('members.MemberInfo', blank=True, null=True, related_name='postautor_member_set', on_delete=models.CASCADE) parent = models.ForeignKey('wallpost.Wallpost', blank=True, null=True, related_name='parent_wallpost_set', on_delete=models.CASCADE) ref_number = models.IntegerField(default=0) module_ref = models.IntegerField(default=0)#General (wall), Responses (wall), Likes, Blogs, Reshare category = models.IntegerField(default=0)#Information, Approval or Action, Alert, Warning, Danger button_type = models.IntegerField(default=0)#Social, Approval, Acceptance, Information, Alert, Warning privacy = models.IntegerField(default=0)#All, OnlySignedIn, OnlyFollowers, OnlyMutualFollowers, ExplicitIncluded, OnlyGroupMembers, Reported #date_created = models.DateField(blank=False,auto_now_add=True) date_created = models.DateTimeField(default=timezone.now()) is_archived = models.BooleanField(default=False,blank=False, null=False) allow_reshare = models.BooleanField(default=False,blank=False, null=False) date_reported = models.DateTimeField(default=False,blank=True,null=True) My template (HTML): <div class="form-group"> <div class="card"> <div class="card-header"> Make a post </div> <div class="card-body"> <form method="POST" action="add_wallpost/"> {% csrf_token %} <div class="row"> <div class="col-sm-8"> {{form.content}} </div> </div> <br> <div class="row"> <div class="col-sm-10"> … -
Django passing data to D3 - D3. eachFor is not a function
I have a small project covering the collection of data in a Postgresql database that is connected to a Django Webapp. I'd like to visualize my data using D3.js. I try to adapt two DateFields to extract my data from the db and offer it as a JSON file to D3. The console.log shows the correct values from the JSON but I am not able to access the data. Apparently, my data is handed over as a string and not as a JSON object. Do you have any idea why this is the case? My views: from django.http import JsonResponse from django.shortcuts import render from django.core import serializers from .models import Sonde from .forms import date_choice def index(request): latest_Measurement = Sonde.objects.order_by('-Date')[:3] form = date_choice if request.method == 'POST': form = date_choice(request.POST) startDate = request.POST.get("start") endDate = request.POST.get("end") print(startDate) subsetData = Sonde.objects.filter(Date__range=(startDate,endDate)) request.session['subsetData'] = serializers.serialize('json',subsetData) else: form = date_choice() context = { 'latest_Measurement': latest_Measurement, 'form': form, } return render(request,'visDat/index.html',context) def renderData(request): subsetData = request.session.get('subsetData') return JsonResponse(subsetData,safe=False) my urls: from django.urls import path from django.conf.urls import url from . import views #app_name = 'visDat' urlpatterns = [ path('', views.index, name='index'), url(r'^api/renderData',views.renderData, name='renderData'), ] My index.html template: <form action="" method="POST"> {% csrf_token %} … -
Input Field Doesnot Appear
so here is my Code form.py: from django import forms from .models import Category class CategoryForm(forms.Form): # class Meta: # model = Category # fields = ('title',) title = forms.CharField(label = 'title', max_length=100) here is My view.py : def CategoryForm(request): if request.method == 'POST': form = CategroyForm(request.POST) if form.is_valid(): # category = form.save(commit = False) # category.title = post # category.save() return redirect('posts/create_blog.html') else: form = CategoryForm() template = 'posts/create_blog.html' context = {'form':form} return render(request,template,context) and here is my view.py : <form action= "CategoryForm" method = "POST" style = 'margin-top:0'> {% csrf_token %} <!--<label style='margin-left: 4%; color: gray;'>Choose Category Name</label>--> {{ form.as_p }} <input type = 'submit' value='Submit'> </form> I dont really understand whats th eproblenm inputs are not appear -
Connection timeout while trying to send an email using Django
I am trying to build a module which allows me to send an email to users. However, I am facing an error: TimeoutError at /email [Errno 60] Operation timed out urls.py from django.contrib import admin from django.conf.urls import url from emailfunction.views import send_email urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^email', send_email), ] views.py from django.http import HttpResponse from django.conf import settings from django.core.mail import send_mail def send_email(request): subject = 'Test Subject' message = 'Test Message./n 123 123 456 456 778 990./n From ABC/n' from_email = settings.EMAIL_HOST_USER to_list = ['receiver@gmail.com', settings.EMAIL_HOST_USER] send_mail(subject, message, from_email, to_list, fail_silently=False) return HttpResponse("Mail has been sent. Please check your mail. Thank YOU!") Relevant details from settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'sender@gmail.com' EMAIL_HOST_PASSWORD = '**************' EMAIL_PORT = 587 -
Using Google Cloud SQL WITHOUT Network Authorization
I am using Google Cloud PostgreSQL with my django rest api developed locally and to be able to connect to the database, you are required to enter an IP address of where do you want to connect from. My team and I are using dynamic IP addresses and we should change the IP address everytime in the cloud interface in order to connect. Is there any other way? I wanted to try the SSL thing but it's too complicated. Any thoughts? Thanks -
Django Rest Framework Create REST API only for executions
I'm working on a django project in which I need to build a rest API for some executions, I don't have much concerns about models as I only need to perform executions on the base of user's inputs/calls. Here's my scenario: The Major thing is the Deployment ( An App in my project ) On a get request user will get a list of all it's deployments(objects). A user will send a POST request to an URL along with the complete object as: { "deployment_name": "dep4", "credentials": "cre4", "project_name": "pro4", "project_id": "004", "cluster_name": "clus4", "zone_region": "zon4", "services": "Single", "configuration": "conf4", "routing": "route4" } then I need to use this data, validate and perform some execution on the base of this data. For example, I will make deployments on a cloud platform with the help of this information by using third-party APIs. I'm really confused by the documentation of DRF, especially about serializers. Which approach and things from DRF i should use to implement my API. -
Django unicode of object id raise TypeError: coercing to Unicode
I have a django model named UserProfile. Here is my code: user_profile = UserProfile.objects.filter(id = 1).first() if user_profile: user_profile_id = user_profile.id user_details = 'user id: ' + unicode(user_profile_id) The code runs normally fine, but today I got an exception in line 4 (the last line): TypeError: coercing to Unicode: need string or buffer, NoneType found I have no clue what possibly could have gone wrong here. -
Difference between null=True and on_delete=models.SET_NULL django
I have a field owner = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) What is the difference between these two attributes on model field -
Displaying the result from DetailView at ListView
I have written a calculation on DetailView named result_xyz as follows: class Model01_DV(DetailView): queryset = Model01.objects.all() def get_context_data(self, *args, **kwargs): context = Model01_DV, self).get_context_data(*args, **kwargs) x_ = # first dependency y_ = # second dependency z_ = # third dependency result_xyz = # sophisticated calculation that involves x, y and z variables context["result_xyz"] = result_xyz return context Is there a way to display this resultant value on each row table that is generated by ListView? -
CELERY_BEAT_SCHEDULE in settings overrides crontabs in database
I have configured celery on my project with some tasks which configured in CELERY_BEAT_SCHEDULE, also I set CELERY_BEAT_SCHEDULER to database backend CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler' So when I go to admin/django_celery_beat/periodictask/1/change/ and change crontab field like from */1 (hours) to */3 (hours) and restart celery, celery was overriding crontab to default value from CELERY_BEAT_SCHEDULE config: 'schedule': crontab(minute='*/10', hour='*/1'),. But if I remove CELERY_BEAT_SCHEDULE its works as I expected So the question is, how I can configure celery to schedules work`s by priorities? That celery check if task crontab was changed on database and if so it does not override db config/ -
Django folder permissions for installation
The official Django installation documentation seems to be lacking in exactly how to set up folder permissions post-installation so that a 403 Foridden error does not show up on a live apache installation. I've spent 2 months going through thousands of forum posts, hundreds of guides, and countless Stackoverflow Q&As about setting up folder permissions. No single two of these posts, guides or Q&As are the same. All are riddled with users having to implement custom solutions here and there to get things working, there's no consistency anywhere as to exactly what folder permissions should be set up. I probably speak for silent untold thousands who gave up when trying to do folder permissions. So my question is simple, how do I set the correct file and folder permissions on Ubuntu 16.04, configured with Python 2.11 in a virtual environment, with Django on an Apache mod_wsgi server? My structure is as per the official documentation - /home/main/myproject/project All of these folders (home, main, myproject and project) have 755 permissions owned by a non-root sudo user called 'main' which I use for everything. I've done: chmod 664 ~/myproject/db.sqlite3 chmod 775 ~/myproject sudo chown :www-data ~/myproject/db.sqlite3 sudo chown :www-data ~/myproject Apparently these … -
Return the correct url of static file in Django
model.py: class A(models.Model):{ poster = models.ImageField upload_to='static/images/album/%Y/%m/%d') } setting.py STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] When I upload the image under http://127.0.0.1:8008/admin/qa/album/, the image show as 'static/images/album/2018/06/27/xxxxxx.jpg' at the poster field in the database. And I can access to the image through http://127.0.0.1:8008/static/images/album/2018/06/27/xxxxxx.jpg. However, the Django Rest Framework API return the url as: http://127.0.0.1:8008/api/index/static/images/album/2018/06/27/xxxxxx.jpg, which make the image 404. What's wrong with my setting? Need your help... -
Close connection to DB in every view function , Django
I'm having a problem with my connections to DB, as too many connections keep being alive which cause me the error too many connections for the role ( XXXXX) as XXXX is the name of the role. now I've used this method inside every function in the views.py to avoid this @login_required def notifications(request): for conn in connections.all(): conn.close() dress_need = Item.objects.filter(dress_active=False).order_by('-created_at') dress_need_count = dress_need.count() context = { 'dress_need_count': dress_need_count, 'dress_need': dress_need, } return render(request, 'fostania_web_app/notifications.html', context) as you see I used for conn in connections.all(): conn.close() in every single view function... but it still happens .. any idea how to add something that closes every connection when it is done? -
VueJS with Jquery
guys, my project using django and vueJS. I want to sign files with digital signatures. One of my cabinets is full django, so there i did it with jQuery scripts. Now i want import this script to my vue code. So user could click button and it will call signFile function. I created few script tags in vue component, using created. let es6Promise = document.createElement('script') es6Promise.setAttribute('src', '/static/etf/js/signing/es6-promise.min.js') document.head.appendChild(es6Promise) let ieEventlistnerPolyfill = document.createElement('script') ieEventlistnerPolyfill.setAttribute('src', '/static/etf/js/signing/ie_eventlistner_polyfill.js') document.head.appendChild(ieEventlistnerPolyfill) let firefoxCadespluginAsync = document.createElement('script') firefoxCadespluginAsync.setAttribute('src', '/static/etf/js/signing/firefox_cadesplugin_async.js') document.head.appendChild(firefoxCadespluginAsync) let cadespluginApi = document.createElement('script') cadespluginApi.setAttribute('src', '/static/etf/js/signing/cadesplugin_api.js') document.head.appendChild(cadespluginApi) let code = document.createElement('script') code.setAttribute('src', '/static/etf/js/signing/Code_js.js') document.head.appendChild(code) let signFileScript = document.createElement('script') signFileScript.setAttribute('src', '/static/etf/js/signing/signFile.js') document.head.appendChild(signFileScript) I created button. signFile function is in signFile.js. So how can i make event on click to call this function? -
Validate django form with local files
My web page has the option of upload videos using a form, but I wanted to extend its functionalities adding the option of giving a YouTube URL instead of uploading a file. With the file upload there is no problem, as I validate the form from a model: forms.py class VideoForm(forms.ModelForm): class Meta: model = Video fields = ('file', 'description', 'url') models.py class Video(models.Model): file = models.FileField(upload_to=video_directory_path) description = models.TextField(blank=True) url = models.CharField(max_length=255, blank=True) and everything works fine, but when I try to do that sending the video's URL, the form = VideoForm(request.POST, request.FILES) won't work by itself as request.FILES is empty, but I tried many things like: form = VideoForm(request.POST, MultiValueDict({'file': [open(fname,'r')]})) and VideoForm always returns: <tr><th><label for="id_file">File:</label></th><td><ul class="errorlist"><li>No file was submitted. Check the encoding type on the form.</li></ul><input type="file" name="file" required id="id_file" /></td></tr> <tr><th><label for="id_description">Description:</label></th><td><textarea name="description" rows="10" cols="40" id="id_description"> </textarea></td></tr> <tr><th><label for="id_url">Url:</label></th><td><input type="text" name="url" value="https://www.youtube.com/watch?v=kj7wTDK5Vx8" id="id_url" maxlength="255" /></td></tr> The question is, there is a way to set request.FILES with a local file for validating a form? I use the pytube library in order to download a video, and it works fine because it displays a bit stream when I do open(fname,'r').read(), and open(fname,'r') returns {'file': <open file u'markst.mp4', … -
Django apache2 url direct with no subdomain
I have installed on Djagno project on Apache and it was working very well. But after I set the subdomain of the projects, it breaks things. <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAlias www.mydomainname.com Alias /static /path/to/project/static <Directory /path/to/project/static> Require all granted </Directory> <Directory /path/to/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess projectname python-path=/var/bin/python3 python-home=/path/to/project WSGIProcessGroup projectname WSGIScriptAlias /subdomain /path/to/project/wsgi.py #Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog /path/to/project/error.log #CustomLog ${APACHE_LOG_DIR}/access.log combined CustomLog /path/to/project/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a … -
uwsgi setup for logging application
I am working on a rest api (in django rest) for logging data to Elasticsearch. It just receives bunch of data (each second) and logs it to Elasticsearch (using elasticsearch_dsl). I am using uwsgi in production. I would like to ask whether my init file is ok: [uwsgi] project = project plugin = python3 chdir = /app module = project.wsgi home = /home/project/env # process-related settings master = true # maximum number of worker processes processes = 3 http-socket = 0.0.0.0:8000 # clear environment on exit vacuum = true max-requests = 250 die-on-term = true # kills stucked process harakiri=30 single-interpreter=True enable-threads=True It is working fine but sometimes some workers are killed with: DAMN ! worker 2 (pid: 21) died, killed by signal 9 :( trying respawn ... and sometimes with: Wed Jun 27 09:09:02 2018 - *** HARAKIRI ON WORKER 2 (pid: 17, try: 1) *** Wed Jun 27 09:09:02 2018 - HARAKIRI !!! worker 2 status !!! Just want to ask for any recommendations for improving my init file. Or how to debug that situations. -
Retrieving data for ListView
I have a ListView and additional have to retrieve context to display the event title. I am currently retrieving the event title with Event.objects.filter(order_reference=self.kwargs['order_reference'],).first(). I now wonder if this is the right approach with .first()? I am mainly asking that because another way I could get this event name would be by using the object_list. It would reduce the database queries, but I would have an unnecessary for loop which I would have to stop after one cycle {% for tickets in object_list %}{{ tickets.order.event.name }}{% endfor %} views.py # Create your views here. class OrderListView(ListView): allow_empty = False template_name = 'orders/order_list.html' def get_queryset(self): return OrderItem.objects.filter( order__order_reference=self.kwargs['order_reference'], ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['event'] = Event.objects.filter( order_reference=self.kwargs['order_reference'], ).first() return context order_list.html: {% extends "base.html" %} {% block content %} <h1>{{ event.event.name }}</h1> {% for tickets in object_list %} {{ tickets.ticket_name }} {% endfor %} {% endblock content %} -
alter data before update in django rest framework
I've looked around for answers but they say to use update() and it doesn't work for me After the user updates an entity, I want to change it's data before saving it N.B: the same thing is done for creating it by overriding the method perform_create() and it works. Here's my code: The update view class CommentUpdateAPIView(generics.UpdateAPIView): serializer_class = CommentModelSerializer permission_classes = [permissions.IsAuthenticated] The serializer class CommentModelSerializer(serializers.ModelSerializer): class Meta: model = Comment # the model to get fields from fields = [ 'id', 'user', 'content', 'timestamp', ] Thank you -
Tag search on multiple criterias
I'd like to get all Profile where tag='hello' and tag='world'. I tried with Q() query but I don't have the correct result. models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=100) slug = models.SlugField(unique=True, max_length=100) def __str__(self): return self.name class Meta: ordering = ['slug'] class Profile(models.Model): name = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class Meta: ordering = ['name'] views.py def search(request: HttpRequest): q_tag_list = request.GET.get('search-tag').split(',') profile_filter = Q() for tag in q_tag_list: profile_filter = profile_filter & Q(tags__slug__startswith=tag) profiles = Profile.objects.filter(profile_filter) return render(request, 'list.html', {'profiles': profiles}) sql generated (from django debug toolbar) SELECT "socialmedia_profile"."id", "socialmedia_profile"."name", "socialmedia_profile"."facebook_name", "socialmedia_profile"."facebook_latest_likes" FROM "socialmedia_profile" INNER JOIN "socialmedia_profile_tags" ON ("socialmedia_profile"."id" = "socialmedia_profile_tags"."profile_id") INNER JOIN "socialmedia_tag" ON ("socialmedia_profile_tags"."tag_id" = "socialmedia_tag"."id") WHERE ("socialmedia_tag"."slug" LIKE '''hello%''' ESCAPE '\' AND "socialmedia_tag"."slug" LIKE '''world%''' ESCAPE '\') ORDER BY "socialmedia_profile"."name" ASC