Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / Ajax - How to filter and display result based on selection
I am trying to filter and display data in Django based on the selection made by the user from drop down box. I'm using ajax call to send a request to Django views. When a user selects, for example, Airline A, then Ajax will send the 'value' of that selection which is an integer to Django backend to filter data and send it back to frontend. Here is my code: HTML: <form method="GET"> <select id="airline-selected"> {% for airline in airline_list %} <option value="{{ airline.id }}"> {{ airline.name }} </option> {% endfor %} </select> <input type="button" value="Update" id="selection-button" method="GET"> </form> Ajax: <script> $( "#selection-button" ).click(function(event) { event.preventDefault(); var airlineSelected = $('#airline-selected').find(":selected").val(); $.ajax({ url: "{% url 'charts_data' %}", method: 'GET', filter_category: parseInt(airlineSelected), success: function(data){ console.log(data) }, error: function(error_data){ console.log("error") console.log(error_data) } }) }); </script> Views.py: class ChartData(generics.ListAPIView): serializer_class = FinancialDataSerializer def get_queryset(self, *args, **kwargs): filter_category = self.request.GET.get("filter_category") queryset = FinancialData.objects.filter(airline_id=filter_category) queryset_filtered = queryset.filter() return queryset_filtered My console.log(data) is showing an empty Array which means views are not getting filtered. How can I filter and display the data based on the selection made by the user? -
Can you modify a model field within a for loop?
I'm trying to write a method that converts temperature units so I can display si units on demand without modifying the database. When I load the view, Currently converts properly as it's not done within a for loop. The problem I'm having is with Hourly. Modifying data within the scope of a for loop doesn't change the actual object, but I'm not sure how to modify temperature as I can't access the slices by index or like a regular list as I've seen in other solutions. models.py class DataPoint(models.Model): ... # Other fields temperature = models.FloatField(null=True, blank=True) def convert_f_to_c(self, temperature_f): if temperature_f is not None: return float("{0:.2f}".format((temperature_f - 32) * .5556)) return temperature_f def get_si_units(self): self.convert_f_to_c(self.temperature) class Meta: abstract = True class Currently(DataPoint): pass class Hourly(DataBlock): pass class HourlyPoint(DataPoint): hourly = models.ForeignKey( Hourly, on_delete=models.CASCADE, related_name='data' ) class Location(model.Model): ... # Other fields currently = models.ForeignKey(Currently) hourly = models.ForeignKey(Hourly) def get_si_units(self): self.currently.get_si_units() # modifies the location for data in self.hourly.data.all(): data.get_si_units() # doesn't modify the location object views.py class SomeView(APIView): def get(self, request, *args, **kwargs): ... location = Location.objects.get(latitude, longitude) location.get_si_units() return LocationSerializer(location).data -
How to properly import two top-level modules? - module has no attribute error
In the views.py file, I am importing a form to render a form. It also has a global variable defaultSelection and the get method would return the global variable. #views.py from .forms import testingForm context = ('form', testingForm) defaultSelection = 'A' def getDefaultSelection(): global defaultSelection return defaultSelection In the form.py file, I was trying to retrieve the global variable #form.py from . import views defaultSelection= views.getDefaultSelection() class testingForm(forms.Form): But I am getting a module has no attribute error importing the form in the views.py file -
Deploying Django App
I am using a tutorial repo, and now that I want to deploy it to an EC2 instance it is not working here is the repo, the only thing I added was the ec2-54-197-26-105.compute-1.amazonaws.com to allowed host. I have left the instance running so you can access it at ec2-54-197-26-105.compute-1.amazonaws.com REPO https://bitbucket.org/trackstarz/clab Here is the output KeyError at /accounts/logout 'en-us' Request Method: GET Request URL: http://ec2-54-197-26-105.compute-1.amazonaws.com/accounts/logout Django Version: 1.11.4 Exception Type: KeyError Exception Value: 'en-us' Exception Location: /home/ubuntu/clab/denv/local/lib/python2.7/site-packages/django/urls/resolvers.py in reverse_dict, line 335 Python Executable: /home/ubuntu/clab/denv/bin/python Python Version: 2.7.6 Python Path: ['/home/ubuntu/clab', '/home/ubuntu/clab/denv/bin', '/home/ubuntu/clab/denv/lib/python2.7', '/home/ubuntu/clab/denv/lib/python2.7/plat-x86_64-linux-gnu', '/home/ubuntu/clab/denv/lib/python2.7/lib-tk', '/home/ubuntu/clab/denv/lib/python2.7/lib-old', '/home/ubuntu/clab/denv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/ubuntu/clab/denv/local/lib/python2.7/site-packages', '/home/ubuntu/clab/denv/lib/python2.7/site-packages'] Server time: Sat, 5 Aug 2017 01:58:31 +0000 Error during template rendering In template /home/ubuntu/clab/courses/templates/base.html, error at line 16 en-us 6 <title>{% block title %}Educa{% endblock %}</title> 7 <link href="{% static "css/base.css" %}" rel="stylesheet"> 8 </head> 9 <body> 10 <div id="header"> 11 <a href="/" class="logo">Educa</a> 12 <ul class="menu"> 13 {% if request.user.is_authenticated %} 14 <li><a href="{% url "logout" %}">Sign out</a></li> 15 {% else %} 16 <li><a href="{% url "login" %}">Sign in</a></li> I am not sure where to start here. requirement.txt has the following django django-braces gunicorn Thank you in advance. -
Trying to deloy django without root, server cant find .fcgi file
I am trying to deploy django onto an a2hosting vps account (https://myfantasyedge.com) without root access. I followed the directions for installation here except since I wasn't allowed a global virtualenv account I used: pip install --user virtualenv and my virtual environment had to be added to ~/djangoenv instead of the path described. I couldn't find any instructions that described how to alter install to account for this so I continued on and tried my best to substitute what i thought was right eg.paths. I added these 2 files to my html_public: .htaccess AddHandler fcgid-script .fcgi AddHandler fcgid-script .fastcgi RewriteEngine on # Set up static content redirect: RewriteRule static/(.+)$ mysite/public/static/$1 # The following two lines are for FastCGI: RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ application.fcgi/$1 [QSA,L] application.fcgi #!/home/fantasy2/.local/lib/python2.7 # Set up the virtual environment: import os, sys os.environ.setdefault('PATH', '/bin:/usr/bin') os.environ['PATH'] = '/home/fantasy2/djangoenv/bin:' + os.environ['PATH'] os.environ['VIRTUAL_ENV'] = '/home/fantasy2/djangoenv/bin' os.environ['PYTHON_EGG_CACHE'] = '/home/fantasy2/djangoenv/bin' os.chdir('/home/fantasy2/public_html/mysite') # Add a custom Python path. sys.path.insert(0, "/home/fantasy2/public_html/mysite") # Set the DJANGO_SETTINGS_MODULE environment variable to the file in the # application directory with the db settings etc. os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings" from django.core.servers.fastcgi import runfastcgi runfastcgi(method="threaded", daemonize="false") After adding these it says to check the url to see the "it worked" page … -
Django bad password exception with all auth(not sure if this is it)
Working on my App using Python 3.6, django 1.11,django-allauth 0.32. I have't been working with Django for very long. Is this a configuration problem with allauth OR django authentication? This error occurs when I try login using the admin account and a bad password. Using a valid password works as expect. Using google and facebook(configured in allauth) works as well. Environment: Request Method: POST Request URL: http://localhost:8000/accounts/login/ Django Version: 1.11 Python Version: 3.6.0 Installed Applications: ['strays.apps.StraysConfig', 'core.apps.CoreConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'avatar', 'userprofiles', 'bootstrap3', 'bootstrapform'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/terencetan/.virtualenvs/mech_project/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in authenticate 72. inspect.getcallargs(backend.authenticate, request, **credentials) File "/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/inspect.py" in getcallargs 1314. (f_name, kw)) During handling of the above exception (authenticate() got multiple values for argument 'request'), another exception occurred: File "/Users/terencetan/.virtualenvs/mech_project/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/terencetan/.virtualenvs/mech_project/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/terencetan/.virtualenvs/mech_project/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/terencetan/.virtualenvs/mech_project/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Users/terencetan/.virtualenvs/mech_project/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/Users/terencetan/.virtualenvs/mech_project/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/Users/terencetan/.virtualenvs/mech_project/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/Users/terencetan/.virtualenvs/mech_project/lib/python3.6/site-packages/allauth/account/views.py" in dispatch … -
{u'error_description': u'', u'error': u'params_missing'} (Podbean)
I am making a Django app to upload my .mp3 files in Podbean. I have tried uploading the file through 'terminal' and it was a success. But now I want to upload the files through my app. To achieve this I have to follow 3 steps. First I have to authorize the file through requests.post and get the result in json. Then from the json data I want to specifically get some data. I have tried the following query but an error shows up. If the first step will be achieved then I can easily do the other steps. views.py from django.shortcuts import render import requests import os, json import httplib as http_client http_client.HTTPConnection.debuglevel = 2 def upload_recordings(request): file_name = "/slayer.mp3" file_size = 1291021 file_path = "path" title = "recording1" access_token = "13a8ee4cec0af562dsdfsdfeee1a2b3f975d3dff64" r = requests.post("https://api.podbean.com/v1/files/uploadAuthorize", params={"access_token": access_token}, headers={"Content-Type": "application/json"}, data=json.dumps({ "filename": file_name, "filesize": str(file_size), "content_type": "audio/mpeg" })) j = json.loads(r.text) print(j) return render(request, 'upload.html') I am getting the following error: send: 'POST /v1/files/uploadAuthorize?access_token=13a8ee4cec0af56fsdf0deee1a2b3fsdf75d38f64 HTTP/1.1\r\nHost: api.podbean.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.18.3\r\nContent-Type: application/json\r\nContent-Length: 80\r\n\r\n{"filesize": "1291021", "content_type": "audio/mpeg", "filename": "/slayer.mp3"}' reply: 'HTTP/1.1 400 Bad Request\r\n' header: Cache-Control: no-store, no-cache, must-revalidate header: Cache-control: no-cache="set-cookie" header: Content-Type: application/json header: Date: Sat, 05 Aug 2017 … -
django session value different then originally set
First off I have SESSION_SAVE_EVERY_REQUEST = True in my settings Using OAuth 2.0, I have a view that sends the user to login the QuickBooks def get_CSRF_token(request): token = request.session.get('csrfToken', None) if token is None: token = getSecretKey() request.session['csrfToken'] = token return token def connectToQuickbooks(request): url = getDiscoveryDocument.auth_endpoint params = { 'scope': settings.ACCOUNTING_SCOPE, 'redirect_uri': settings.REDIRECT_URI, 'response_type': 'code', 'state': get_CSRF_token(request), 'client_id': settings.CLIENT_ID } url += '?' + urlencode(params) return redirect(url) getSecretKey generates some random 40 character string Then QuickBooks sends back the same random string I saved into the session in the state parameter def authCodeHandler(request): state = request.GET.get('state', None) error = request.GET.get('error', None) csrfToken = get_CSRF_token(request) print("State: " + state + " csrfToken: " + csrfToken) if error == 'access_denied': return redirect('index') if state is None: return HttpResponseBadRequest() elif state != csrfToken: # validate against CSRF attacks return HttpResponse('unauthorized', status=401) ... ... But when get_CSRF_token is called it gives me something different than I put in the session. -
Django Email Backend
I'm developing a django app locally and trying to configure it to use the Amazone SES service to send emails. I've installed django-ses and added this to my settings.py: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'us-west-2' AWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com' AWS_ACCESS_KEY_ID = '...' AWS_SECRET_ACCESS_KEY = '...' Unfortunately, mail.get_connection() returns that it's still using django.core.mail.backends.console.EmailBackend; both in the shell and when the development server is running. It behaved the same when I was attempting to go the normal smtp configuration route with django.core.mail.backends.smtp.EmailBackend too... Any ideas as to why it's not making the switch? -
Django Full Text Search Not Matching Partial Words
I'm using Django Full Text search to search across multiple fields but have an issue when searching using partial strings. Lets say we have a report object with the name 'Sample Report'. vector = SearchVector('name') + SearchVector('author__username') search = SearchQuery('Sa') Report.objects.exclude(visible=False).annotate(search=vector).filter(search=search) The following QuerySet is empty but if I include the full word 'Sample' then the report will appear in the QuerySet. Is there anyway to use icontains or prefixing with django full text search? -
Django: Operational Error with html template and "no such table"
I'm following a tutorial from Obeythetestinggoat.com (Win7, Django 1.11, Python 3.6.1) and having some issues when I try to access the local site manually. When I run python manage.py runserver and opening localhost:8000 in Chrome browser window, I get the following error: django.db.utils.OperationalError: no such table: accounts_user The output in the browser windows says that there was an Error during template rendering Here is snippet of template it is trying to render: <div class="container"> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <a class="navbar-brand" href="/">Superlists</a> {% if user.email %} <ul class="nav navbar-nav navbar-right"> <li class="navbar-text">Logged in as {{ user.email }}</li> <li><a href="#">Log out</a></li> </ul> {% else %} <form class="navbar-form navbar-right" method="POST" action="{% url 'send_login_email' %}"> <span>Enter email to log in:</span> <input class="form-control" name="email" type="text"/> {% csrf_token %} </form> {% endif %} </div> </nav> {% if messages %} <div class="row"> <div class="col-md-8"> {% for message in messages %} {% if message.level_tag == 'success' %} <div class="alert alert-success">{{ message }}</div> {% else %} <div class="alert alert-warning">{{ message }}</div> {% endif %} {% endfor %} </div> </div> {% endif %} </div> I believe the issue comes from {% user.email %} because these specific errors didn't come up until I added them into the template. Although, … -
Can I use bulk_create on models with primary keys being AutoFields without making the data inconsistent?
From Django documentation of bulk_create: If the model’s primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does, unless the database backend supports it (currently PostgreSQL). Well I'm not using Postgres. Am I to understand that if my model's pimary key is an AutoField then bulk_create will insert rows to the database with empty primary key column? I suppose that having in a table rows with no value for primary key is a straight way to problems, since it breaks the invariant that each row must have a primary key set and no two rows may have the same primary key, right? Can I solve this problem by manually setting the primary key like this when I know the table to be empty before the bulk_create? Person.objects.bulk_create([ Person(name='John', surname='Doe', pk=1), Person(name='Mary', surname='Sue', pk=2) ]) Will it not create problems with further insertion of objects? For example, if after the above statement I do: Person.objects.create(name='Donald', surname='Duck') Will Donald Duck's primary key be correctly set to 3? Or will it be incorrectly set to 1? Can I force the primary key counter for the new objects to be set to an arbitrary value (like, … -
why don't the django cms urls match even though they look exactly the same in the error?
So I am trying to make a simple url to make an ajax call on and I keep getting the error saying that the url does not match any of the urls in the system It looks exactly the same to me: ^en/ ^registration/ ^create-user/$ [name='create_user'] The current URL, /en/registration/create-user/, didn't match any of these . The way I am loading things is by putting this in my main urls file: url(r'^registration/', include('registration.urls')), and then in a registration app I have another urls file. urlpatterns = [ url(r'^create-user/$', ajax.create_user, name="create_user") ] To me it seems like the url /registration/create-user/ should match.What am I doing wrong? -
i can-not add a picture from django database through variable
if i try to add a simple static address with this code: it works, but when i try this code: {% for B in productss%} to get data from my database with the help of loop it does'nt give me exact address: it gives strange address while in my database there is the value is Diamond Arshad.PNG enter image description here -
How to send a mail using gmail in Django 1.10? [duplicate]
This question already has an answer here: STARTTLS extension not supported by server - Getting this error when trying to send an email through Django and a private email address 3 answers I am trying to make a simple django program which sends a mail when a specific button is clicked My settings include the following - EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 But while testing the following code in python shell. from django.core.mail import EmailMessage email = EmailMessage('Subject', 'Body', to=['def@domain.com']) email.send() I got the following error message - Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Nikhil Khandelwal\AppData\Local\Programs\Python\Python35-32\lib\smt plib.py", line 751, in starttls "STARTTLS extension not supported by server.") smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server. Please suggest ways to remove this error keeping in mind that I am beginner in django and python. Thank you in advance :) -
How to serialize an object instance which gets the data from 2 separate models using Django Rest Framework?
Query : I have a GET request which gives the data from the 2 models (single_tracklog_object in View). However, when I serialize this object instance using the serializers I am getting an empty data for devices as below. { "lat": "51.0038", "lon": "8.0038", "speed": 50, "course": 5, "device": {} # this needs to be having a value but is empty. } I am not understanding why its happening. Please guide me on this. My Models : class Tracklogs(models.Model): tracklog_id = models.AutoField(primary_key=True) device = models.ForeignKey(Tracking_devices, related_name='tracklogs') lat = models.CharField(max_length=10, null=False) lon = models.CharField(max_length=11, null=False) ......... #timestamps tracker_datetime = models.DateTimeField(blank=True, null=True) class Meta: get_latest_by = "tracker_datetime" class Tracking_devices(models.Model): device_id = models.AutoField(primary_key=True) device_type = models.ForeignKey(Device_type) user = models.ForeignKey(User, null=False) name = models.CharField(max_length=100) description = models.CharField(max_length=256, blank=True, null=True) My View : serializer_class = ShowLocationInfoSerializer def get(self, request, *args, **kwargs): # get the imei from the url imei = self.kwargs['imei'] try: single_tracklog_object = Tracklogs.objects.filter(device__imei = imei).values('lat', 'lon','speed','course','device','device__name').latest() # Here its causing problem!!! serializer = self.serializer_class(single_tracklog_object) return Response(serializer.data) except ObjectDoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) My Serializer: class Tracking_DeviceSerializer(serializers.ModelSerializer): name = serializers.CharField(read_only=True) class Meta: model = Tracking_devices fields = ('name') class ShowLocationInfoSerializer(serializers.ModelSerializer): lat = serializers.CharField(read_only=True) lon = serializers.CharField(read_only=True) speed = serializers.IntegerField(read_only=True) course = serializers.FloatField(read_only=True) device = Tracking_DeviceSerializer() class Meta: … -
Unit tests fail after a Django upgrade
I am trying to bring a Django project from version 1.8 to 1.11. Pretty much everything seems to work fine except unit tests. We have a base test class inheriting from Django TestCase with a Tastypie mixin. The base class has some code in the setUp() list this class BaseApiTest(ResourceTestCaseMixin, django.test.TestCase): def setUp(self): super().setUp() self.username = "secret_user" self.password = "sekret" self.email = "secret@mail.com" self.first_name = "FirstName" self.last_name = "LastName" self.user = User.objects.create_superuser( self.username, self.username, self.password ) And the app specific tests would inherit the base test and do something like class TheAPITest(BaseApiTest): def setUp(self): super().setUp() # more setup goes here So, under Django 1.8.x this works fine. But under 1.11.x all of these give me an error on the User.objects.create_superuser() line. django.db.utils.InterfaceError: connection already closed I have been going through the release notes, but there is just too much stuff that has happened between 1.8 and 1.11. Is there something simple that I am missing? -
Django Channels: How to flush send buffer
I'm using Django 1.10 with Channels as a backend for an app I'm building. I've set up websocket communication between my client (Angular 4) and Django. Everything works, but I'm a bit confused. Consider the following code: @channel_session def ws_receive(message): for a in range(10): message.reply_channel.send({'text': json.dumps({'test': '123'})}) time.sleep(1) Im receiving the respons on the client after the for-loop has completed iterations, in this example after 10 seconds. Question: Is it possible to flush the send 'buffer', meaning the message.reply_channel.send function will send immediately? -
Getting the Django-generated unique name of a file uploaded multiple times
I am using DRF backend to upload files. In my specific case I will want to get the name of the file, after it has been uploaded. The reason is that if a user uploads a file with same name, I am still able to process it independently. views.py: class ImageUploaderView(viewsets.ModelViewSet): renderer_classes = [renderers.JSONRenderer] queryset = ImageUploader.objects.all() serializer_class = ImageUploaderSerializer parser_classes = (MultiPartParser,) serializer.py: class ImageUploaderSerializer(serializers.ModelSerializer): class Meta: model = ImageUploader models.py: class ImageUploader(models.Model): # name=models.ImageField(upload_to='media') name=models.FileField(upload_to='media') I tried to put signals and hooks after the model definitions but I am not being able to get this filename. Can someone shed some light pls? -
How can I use django's default test framework to test a module included in sys.path that is not a subdirectory of the django project?
I have a django (1.8) site that is structured like this: .../django_project/ ./templates/ ./manage.py ./<dir with settings,urls,etc> .../django_app_project/ ./app_name/ ./<app files> ./test_app.py To run the site, I set the environment variable PYTHONPATH=.../django_app_project/. This works perfectly when running the server, but causes problems when running the tests. Django's DiscoverRunner (django.test.runner.DiscoverRunner) does not notice .../Django_app_project/app_name/test_app.py. How can this be made to work without moving the app into the Django project? (It is outside for version control reasons) -
Show images from django server
I am developing web app with Django 1.11, in my angular app I ask to my web server and convert image to base64, but I change this and I try return path for in my web app with angular calling the image , but I have found that I must configure the path to my media files but I can not show them. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'images') MEDIA_URL = 'images/' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static-root') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] views.py I return my information as if it were a API rest. for ix in photos: data.append({"path":ix.idSTFolio.path_img, "obra":ix.idObra.name, "st":ix.idSTFolio.idST.name, "folio":ix.idSTFolio.idFolio.name, "profesional":ix.idSTFolio.idPro.name, "date":ix.idSTFolio.date, "lat":ix.idSTFolio.lat, "lng":ix.idSTFolio.lng, "note":ix.idSTFolio.note}) response = { "data":data, } return HttpResponse(json.dumps(response, default=json_serial),content_type='application/json',status=200) But in my web app I see the path to my image, but not the image My web app angular Before I see my images when I convert in base64, but I don't make it now. -
Python/Django Referencing Nested JSON
I'm using the Google Places Reverse Geocode API to return the latitude and longatude of a given address. The API returns a massive JSON file with tons of nested objects. Here's Google's documentation on it. I'm trying to grab the geometry.location.lat object (see documentation). Here's my current code, followed by the error it returns: address_coords = gmaps.geocode(raw_address) # gmaps makes the API request and returns the JSON into address_coords address_lat = address_coords['results']['geometry']['location']['lat'] address_lon = address_coords['results']['geometry']['location']['lng'] TypeError: List indices must be integers or slices, not str I'm not sure how to reference that JSON object. -
Python Django: getting started with mocks
I have the following code that I'm attempting to create a test (still work in progress): from core.tests import BaseTestCase from core.views import get_request from entidades.forms import InstituicaoForm from mock import patch class InstituicaoFormTestCase(BaseTestCase): def setUp(self): super(InstituicaoFormTestCase, self).setUp() @patch('get_request', return_value={'user': 'usuario_qualquer'}) def test_salva_instituicao_quando_informaram_convenio(): import pdb pdb.set_trace() form = InstituicaoForm() it fails because when I try to create a InstituicaoForm, a get_request is called: def get_request(): return getattr(THREAD_LOCAL, 'request', None) and it trows this error entidades/tests.py:11: in <module> class InstituicaoFormTestCase(BaseTestCase): entidades/tests.py:16: in InstituicaoFormTestCase @patch('get_request', return_value={'user': 'usuario_qualquer'}) .tox/unit/local/lib/python2.7/site-packages/mock/mock.py:1670: in patch getter, attribute = _get_target(target) .tox/unit/local/lib/python2.7/site-packages/mock/mock.py:1522: in _get_target (target,)) E TypeError: Need a valid target to patch. You supplied: 'get_request' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > /home/vinicius/telessaude/.tox/unit/local/lib/python2.7/site-packages/mock/mock.py(1522)_get_target() -> (target,)) What am I doing wrong? How should mock this get_request() method? -
TypeError: __str__() takes 0 positional arguments but 1 was given (Django)
Whenever I am going to posts/new link Django is giving '**TypeError at /posts/new/ __str__() takes 0 positional arguments but 1 was given This is the view: class CreatePost(LoginRequiredMixin, generic.CreateView): fields = ('message', 'group') model = models.Post def form_valid(self , form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) This is the Post Model: class Post(models.Model): user = models.ForeignKey(User,related_name='posts') created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True) def __str__(self): return self.message def save(self,*args, **kwargs): self.message_html = misaka.html(self.message) super.save(self,*args, **kwargs) def get_absolute_url(self, *args, **kwargs): return reverse('posts:single', kwargs={'username':self.user.username, 'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user', 'message'] And this is the post_from.html: {% extends "posts/post_base.html" %} {% load bootstrap3 %} {% block post_post %} <h4>Create a new Post</h4> <form id="postForm" action="{% url 'posts:create' %}" method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Post" class="btn btn-primary btn-large"> </form> {% endblock %} Whenever I am removing {% bootstrap_form form %}, I am getting the page without form. But when I have {% bootstrap_form form %}, I am getting TypeError at /posts/new/ __str__() takes 0 positional arguments but 1 was given After a lot of searching, I don't able to find where the problem is! -
Django. Refreshing part of the page with ajaxForm
I am submitting forms via django forms and I want data to refresh on submit in a certain part of the page (div) $(function () { $('#post-form').ajaxForm({ success: function (json) { console.log(json); // log the returned json to the console $('#this').append('snippet.html') console.log("success"); // another sanity check } }) }); of an html snippet <div id="this"> <tr> <th>ID</th> <th>Дата</th> <th>Цена</th> <th>Откуда</th> <th>Куда</th> <th>Водитель</th> </tr> {% for item in query_set %} <tr> <td>{{ item.id }}</td> <td>{{ item.date }}</td> <td>{{ item.price }}</td> <td>{{ item.des_from }}</td> <td>{{ item.des_to }}</td> <td>{{ item.driver }}</td> </tr> {% endfor %} </div> And here is "views" file def post(self, request): csrf_token_value = get_token(self.request) data = {} form = SchedForm(request.POST) if form.is_valid(): obj = form.save() data['result'] = 'Created!' data['object'] = { 'price': obj.price, 'driver': obj.driver_id, 'des_from': obj.des_from_id, 'des_to': obj.des_to_id, 'date': obj.date, } return JsonResponse(data) else: return JsonResponse(form.errors) The problem is I have a JsonResponse in view's return while on the INTERNET I've read that there are two solutions via render_to_response and render_to_string. But as far as I'm concerned to refresh data in forms you need render_to_string. I just don't see a way to include it in the return with JsonResponse