Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post photo on Facebook page doesn't work
I can't post a photo on a facebook page with my facebook app (V 2.11). My app has the manage_pages e publish_pages permissions. I have a page token too. Post text works well. If I use a image url from my domain the post doesn't work if I use a image url from another domain (eg: tripadvisor) the post works. My domain has a SSL DigiCert SHA2 Secure Server CA. This is my code: def PostPhotoFB(photo, title, link, text , fb_access_token, fb_page_id, desc): facebook_data = {'url': photo, 'access_token': fb_access_token, 'caption': text, } facebook_request = "https://graph.facebook.com/" + fb_page_id + "/photos" response_facebook = requests.post(facebook_request, data=facebook_data) if response_facebook.status_code == 200: return json.loads(response_facebook.text)['id'] else: return "" with an image in my server I get 400 and "(#324) Missing or invalid image file","type":"OAuthException","code":324 I use Jpg or PNG image. I don't understand. Can you help me please? Thanks a lot -
filter object_list in django templete
I am new in Django and have some problem: I create a template with object_list table and run in each object with loop: but I also need to have filter by substring then when the user will filter the table will updates online. I attch part from my code .. only the relvant I debug the code and get the expected querset both in server print to log and in response ajax call but I still need to refresh point_list in some way or to determine the filters inside the templete and not in the server? Any help??? I create view for this filter get the ajax request with substring value def filters_points(request): point_list = Point.objects.all() try: req = request.GET.get("filterData") if req: point_list = Point.objects.filter(onsitePointName__icontains=req) except AttributeError: print("failed") #qs_json = serializers.serialize('json', point_list) #return HttpResponse(qs_json, content_type='application/json') return render_to_response('point/point_list_update.html', {'point_list': point_list}) in HTML templete: {% for point in point_list %} ... {{ point.mangoId }} {{ point.onsitePointName }} .... -
how to convert an InMemoryUploadedFile upload to cloudinary in Django=1.11 using cloudinary.uploader.upload()
I am trying to upload an image file to cloudinary which I have sent from my django template to a function in views.py The file is in request.FILES['image'] cloudinary.config( cloud_name="p*****", api_key="33************", api_secret="4***-S***_o*********" ) img_obj = request.FILES['image'] cloudinary_response = cloudinary.uploader.upload(img_obj) image_url = cloudinary_response['url'] Printing img_obj gives the name of the image (Like : "tree.jpg") cloudinary upload doc is as follows https://cloudinary.com/documentation/image_upload_api_reference#upload The type of img_obj is InMemoryUploadedFile. Now is there a way to convert it to base64 or somthing like that so I can upload. Or any other solution ?? -
'NoneType' object is not iterable (Python Django) [on hold]
This is what I'm trying in view, try: numbers = Data.objects.all().aggregate(Sum('number')) except: numbers = None But I'm getting this error, 'NoneType' object is not iterable How can I fix that ? -
unable to connect django and angular 2
I want to connect my angular 2 app to django but how can i connect because both have different servers. I also read about cors but didn't work. Please suggest me some simple way to connect both of them Thanks in Advance -
Collapsible list of app models on django admin page
The list of apps and models is getting long in Django project. Is it possible to make apps and models lists on Django Admin page collapsible ? I've seen some admin replacements, but I'm looking for a way to incorporate this in standard Admin. -
I am using django tables 2 and trying to export my table following the official documentation
I have followed the official documentation of django tables 2 but it is not working I dont know why views.py from django.shortcuts import render from django_tables2 import RequestConfig from django.template.response import TemplateResponse from .models import Customer from .tables import CustomerTable from .tables import TableView from django_tables2.export.export import TableExport def user_profile(request): table= CustomerTable(Customer.objects.all()) RequestConfig(request,paginate={'per_page':15}).configure(table) return render(request, 'home.html', {'table': table}) def TableView(request): table = CustomerTable(Customer.objects.all()) RequestConfig(request).configure(table) export_format = request.GET.get('_export', None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response('table.{}'.format(export_format)) return render(request, 'table.html', { 'table': table }) my html template {% extends 'base.html' %} {% block content %} {% load render_table from django_tables2 %} {% load querystring from django_tables2 %} <!doctype html> <html> <head> <title>List of Customers</title> </head> <body> {% querystring '_export'='csv' %}home {% for format in table.export_formats %} <a href="{% querystring '_export'=format %}"> download <code>.{{ format }}</code> </a> {% endfor %} <p margin-bottom:500px;> </p> <div style="width: 2500px; height: 600px; overflow-y: scroll;"> <div id ="users"> <input class="search" placeholder="Search" /> {% render_table table %} {% endblock %} </div> </div> </body> urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', user_profile, name="user_profile"), url(r'^$', TableView, name="TableView"), ] tables.py import django_tables2 as tables from .models import Customer from django_tables2.export.views import ExportMixin from .models import Customer class CustomerTable(tables.Table): class Meta: model … -
The view accounts.views.register didn't return an HttpResponse object. It returned None instead
i have tried all possible solutions found online but none seems to help me eliminate this error message. from django.shortcuts import render, redirect from accounts.forms import RegistrationForm def home(request): numbers = [1,2,3,4,'A','B','C'] name = 'SimiDev' args = {'myname': name, 'numbers': numbers} return render(request,'accounts/home.html',args) def register(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/accounts') else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html',args) -
Django static and media files not loading on Firefox Focus when served from S3
Django static and media files are not loading on Firefox Focus when served from S3 using nginx and using HTTPS. Everything works well if I use a different browser or serve static files from localhost. There's and option in Focus called "Block other content trackers". If I turn that off, Focus works as expected, loading all the files properly. So I understand that my files are being blocked for some reason but I don't know why. And since most of the websites are working fine on Focus, I guess my website should work too. -
Django: How to retrieve a particular item for specific user from a model?
How can I retrieve a specified field for a particular user in Django? I got user: A, B, C and user A got 10 url records in the database. The problem is how to retrieve the 10 url records of user A? Thank you so much.models.py class Bookmark(models.Model): url = models.CharField(max_length=500) shortlisted_by = models.ForeignKey(User, related_name='bookmark') shortlisted_date = models.DateTimeField(auto_now_add=True) -
Django rest framework timefield input format
After hours of searching , i found many post that is related but wasnt able to help. What i want to do is input eg: 10:30 AM into the timefield. In the django rest framework api on browser, it is using this 10:30 AM format ('%I:%M %p'). But when i am using postman to test it, the output is in 24hr format ('%H:%M:%S'). I also tried to using 10:30 PM as input but the output i get is 10:30:00 instead of 22:30:00. Many of the answer i found is change the timefield format in settings.py by using this line TIME_INPUT_FORMATS = ('%I:%M %p',) but it doesnt work for me. Sorry for my inexperience on django rest framework as i am still learning. Here is the screenshot of the result. On browser API: On postman: -
Log formatting in django for kibana
In my django app, I'm trying to log the exception messages in dictionary format. The keys of the dictionary would be used in kibana for filtering. For example an exception message like Could not get details for student <student> in school <school> should look like { 'message': 'Could not get details for student <student> in school <school>', 'student': <student>, 'school': <school> } Above I would be using value in to get the school related exception details in my kibana. I've looked into logstash_formatter. It does not parse the exception message for me. With my approach I'm ending up creating dictionaries with certain key, value pairs at all the places wherever I'm logging and it really doesn't look good. Another option I thought of is adding a wrapper on top of my django logging and implement debug, info etc methods inside it and use it at all the places I'm logging. Not sure if that's the right way too. This can also be achieved using grok patterns on logstash side but for certain maintainability reasons can't do it too. What are the other options to achieve this. suggestions ? -
How to set multiple Django site on VPS using Apache?
I have Deploy a Django application on VPS using Apache and mod_wsgi. Without a Domain name. One can access the site just by typing IP address on browser. Now I have another application I want to configure this second application with similar IP address, how can I set this. So that if some one can access both the site just by typing xx.xxx.xxx.63/app1 or xx.xxx.xxx.63/app2 On browser.. bellow is my "000-default.conf" file: <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 Alias /static /home/myproject/DATAPLO/static <Directory /home/myproject/DATAPLO/static> Require all granted </Directory> <Directory /home/myproject/trytable> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/myproject:/home/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/myproject/trytable/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, … -
Allow django rest api to process Not raw Json
I wrote simple django app to store emails, when I send raw data it works perfectly, meanwhile when use postman or request.post(url, data: {'from':'somebody', 'to': 'someboy' ...} ) I get No JSON object could be decode error in the entranteJson = json.loads(entrante) line. @csrf_exempt def email_create(request): """ List all code pedidos, or create a new pedido. """ if request.method == 'GET': emais = Email.objects.all() serializer = EmailSerializer(emais, many = True) return JsonResponse(serializer.data, safe = False) elif request.method == 'POST': entrante = request.body.decode("utf-8") entranteJson = json.loads(entrante) serializer = EmailSerializer(data=entranteJson) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Somebody has any suggestion to can send data via form-data ? I really appreciate it very much. -
NoReverseMatch at /answer/ Reverse for 'detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['answer/$(?P<pk>\\d+)/$']
for some reason I cannot seem to solve this bug. , any help will be appreciated this is the models.py def get_absolute_url(self): # return f"/question/{self.slug}" return reverse('qna:detail', kwargs={'pk': self.pk}) qna/Urls.py url(r'^$', AnsListView.as_view(),name='list'), url(r'^create$', AnsCreateView.as_view(),name='create'), url(r'^(?P<pk>\d+)/$', AnsDetailView.as_view(),name='detail'), main/url.py url(r'^answer/$',include('qna.urls', namespace='qna')), Error when try to load http://127.0.0.1:8000/answer/ NoReverseMatch at /answer/ Reverse for 'detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['answer/$(?P<pk>\\d+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/answer/ Django Version: 1.11.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['answer/$(?P<pk>\\d+)/$'] Exception Location: C:\Users\prash\Desktop\prashantks\pksproject\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 -
Removed id field from my model by mistake
I accidentally removed id field from the model. Now I want to undo it. I am getting Integrity Error - datatype mismatch error. But python manage.py makemigrations and python manage.py migrate are running well with no problems. I have also deleted the model and created it once again. After creating, the 0001_initial.py file that gets created on migrating the model contains the default id column. But still I am not able to overcome my problem. The full error trace is as follows: Internal Server Error: /drizzlelore/createEvents Traceback (most recent call last): File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\backe nds\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\backe nds\sqlite3\base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: datatype mismatch The above exception was the direct cause of the following exception: ngo\dTraceback (most recent call last): File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\core\han dlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\core\han dlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\core\han dlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\eloixir\Desktop\mysite\mysite\home\views.py", line 54, in creat e_event event = form.save() File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\forms\mo dels.py", line 463, in save self.instance.save() File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\model s\base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\model File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\model s\base.py", line 837, in save_base … -
How can I configure GeoNode 2.6 to PUBLIC IP?
I am new to GeoNode, I installed Geonode 2.6 on ubuntu 16 (http://docs.geonode.org/en/master/tutorials/install_and_admin/quick_install.html) and after successfully installed it, I configured my server to a public IP and using sudo geonode-updateip command I changed my ip in geonode, but after that I can't login to geonode application, Browser show "The connection was reset" (I thing its a time out) Checked with local ip, its working.And I changed Proxy Base URL on geoserver to public IP, still not solved. How can I fix this? Geoserver log last lines 2017-11-22 10:01:14,734 DEBUG [org.geoserver.security.filter.GeoServerSecurityContextPersistenceFilter$1] - SecurityContextHolder now cleared, as request processing completed 2017-11-22 10:01:15,036 DEBUG [org.geoserver.security.IncludeQueryStringAntPathRequestMatcher] - Checking match of request : 'Path: /web/, QueryString: null'; against '/web/**' 2017-11-22 10:01:15,036 DEBUG [org.geoserver.security.IncludeQueryStringAntPathRequestMatcher] - Matched Path: /web/, QueryString: null with /web/** 2017-11-22 10:01:15,042 TRACE [org.geoserver.ows.OWSHandlerMapping] - No handler mapping found for [/web/] 2017-11-22 10:01:15,043 TRACE [org.geoserver.ows.OWSHandlerMapping] - No handler mapping found for [/web/] 2017-11-22 10:01:15,043 TRACE [org.geoserver.ows.OWSHandlerMapping] - No handler mapping found for [/web/] 2017-11-22 10:01:15,043 TRACE [org.geoserver.ows.OWSHandlerMapping] - No handler mapping found for [/web/] 2017-11-22 10:01:15,185 DEBUG [org.geoserver.filters] - Creating a new http session inside the web UI (normal behavior) java.lang.Exception: Full stack trace for the session creation path at org.geoserver.filters.SessionDebugFilter$SessionDebugWrapper.getSession(SessionDebugFilter.java:92) at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229) at … -
Django installed but throws import error in virtual env when running: sudo python manage.py collectstatic
I am working in a virtual environment. When I run import django and django.VERISON, I get >>> django.VERSION (1, 10, 2, 'final', 0) but when I run the command sudo python manage.py collectstatic it throws error: "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I checked the sys.path inside virtual env and it does not have django. it has these: ['', '/www/XXX/venv/lib/python35.zip', '/www/XXX/venv/lib/python3.5', '/www/XXX/venv/lib/python3.5/plat-x86_64-linux-gnu', '/www/XXX/venv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/www/XXX/venv/lib/python3.5/site-packages'] I still don't know how to make it work. Should I install django again in virtualenv, or should I uninstall the version already there on the server, or should I just add it to python variable? Also I if should do one of these things, how to do it? I am working with a server for the first time, hence not doing anything intuitively. -
Django Form Request.GET only get 1 value from multiple selected field
I have a multi select field using select2 in my form, i want to get all the value selected when submit, but when I print the value, its only get the value of the last selected option, how can i fix this? Any help is much appreciated, below is my code : html <select class="js-example-basic-multiple" name="Project" multiple="multiple" style="display:inline-block;"> <option value="ALL" checked="1">ALL</option> <option value="1">a</option> <option value="2">b</option> <option value="3">c</option> <option value="4">d</option> </select> <script> $('.js-example-basic-multiple').select2(); $('.js-example-basic-multiple').on('change', function() { var a = $('.js-example-basic-multiple').val(); }) </script> view.py if 'Project' in request.GET: print(request.GET['Project']) -
celery works not found if not start with sudo
I make use of celery with django, and setup supervisor according celery supervisor configuration example. but I found some error in log: unregister task. So, I test it on terminal by following CMD: celery worker -A dating -l INFO -P gevent Yes, not see my task. [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap . dating.celery.debug_task After I swith to sudo like this: **sudo** celery worker -A dating -l INFO -P gevent the output show all my task. [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap **. dater.tasks.xxx** . dating.celery.debug_task **. feed.tasks.xxx** I have no idea about this problem, please help to check it, Thanks. PS: i set user: www-data in /etc/supervisor/conf.d/celery.conf and checked the owner of log and python script, all are www-data. dating/celery.py: from __future__ import absolute_import import os from celery import Celery os.environ.get('C_FORCE_ROOT', True) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dating.settings') app = Celery('dating') app.conf.update( broker_url = 'redis://localhost:6379', result_backend = 'redis://localhost:6379', task_serializer='msgpack', result_serializer='json', accept_content=['msgpack', 'json'], # Ignore other content enable_utc=True, result_expires=3600*24, ) # Load task modules from all registered Django app configs. app.autodiscover_tasks() -
Django Rest Framework: An example how to post a new ordering of tracks
I am using Django Rest Framework and I have a situation similar to the Album and Tracks example used in the documentation here : http://www.django-rest-framework.org/api-guide/relations/#api-reference I want to make an endpoint that allows me to post this JSON data [{"id":1},{"id":2},{"id":3},{"id":4},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":75},{"id":76},{"id":77},{"id":78}] so that the Tracks will be reordered accordingly within the Album they belong to. The ids in the json data refer to the primary key of the tracks. The field I use to store their order is order and the unique index is unique_together = ('album', 'order') I can write my own custom endpoint to satisfy this, but was wondering if I can reuse whatever existing code that DRF already has to fulfil this. I have looked at https://github.com/miki725/django-rest-framework-bulk but I am using Django Rest 3.6.3 Django 1.10, python 3 so it appears to be outdated for me. -
Change "Quit the server with CTRL-BREAK."
Is there a way in one of the Django scripts to change the CTRL-BREAK exit command to something else when using "python manage.py runserver?" -
Map Mannually Created Table as M2M in Django
I have table T1 (list of all words Used in Text) and T2 (list of Text). I have created another Table T3 with foreign key to T1, and T2 so that it can act as M2M, in T3. I additionally add another column called WordCount, so i cannot create this table with models.ManyToMany Field! Can I access T2 from T1 using Many to many Constrains in Django ORM? -
Why I count’t use get_user_model() at import time
Just as the title, I cannot import usercreationform . The exception is model haven’t been loaded. It’s only appears in Django 1.10. There’s no such problem in Django 1.11 . I know it depends on whether get_user_model() can be called at runtime. What should I do to solve it in Django 1.10? -
What is the best way to restrict jsonField's key value in Django model
I working on Django project for that i need a model to keep personalized_information from user. This field is individual independent so i keep this as a jsonField. Now i am wondering what is the best possible way to restrict key values of this field. Say some user would like to share name, address, email to us and some just want to share name. This list can increase from time to time. So its very hard to predict what is going to be needed as future. For simplicity i like to keep this information as a json response in my database. What is the best design for this problem?