Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST framework url regex patterns not being matched
I am writing a RESTful API. I have two end points as defoned in my urls.py below: urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'prices/(?P<ticker>[X]{1}[A-Z0-9]{3}:[A-Z0-9]{1}[A-Z09.-]{1,4})/?P<resolution>([0-9]{0,3})/$', views.historyPrices, name='prices'), url(r'chart/?P<name>([a-zA-Z0-9_\.-]{8,12})/$s', views.chart, name='pchart'), ] views.py from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response # Create your views here. @api_view(['GET']) def historyPrices(request, ticker, resolution=1): if request.method == 'GET': try: # do something return Response({'foo': 'foobar'}) except Exception as e: print ('Error: {0}'.format(e)) return Response(status = status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(status = status.HTTP_405_METHOD_NOT_ALLOWED) @api_view(['GET', 'POST', 'PUT', 'DELETE']) def chart(request, name=None): if request.method == 'GET': if (name is not None): try: # do something except Exception as e: print('Error:',e) return Response(status = status.HTTP_404_NOT_FOUND) return Response({'foo': 'bar') else: return Response(status = status.HTTP_400_BAD_REQUEST) elif request.method == 'POST': data = request.data # print(data) try: # do something return Response(status = status.HTTP_201_CREATED) except Exception as ex: print('Unhandled exception: {0}'.format(e)) return Response(status = status.HTTP_500_INTERNAL_SERVER_ERROR) elif request.method == 'PUT': print('Called with PUT') return Response(status=status.HTTP_501_NOT_IMPLEMENTED) elif request.method == 'DELETE': print('Called with DELETE') return Response(status=status.HTTP_501_NOT_IMPLEMENTED) else: return Response(status=status.HTTP_400_BAD_REQUEST) I want to be able to call using the following urls (all of those shown below, return a 404 not found error: curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG (404) curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG/ (404) … -
Django models query
I have a django model something like messageto: messagefrom: message: The thing is when I have to display messages between two particular users , I have to go through all messages stored in the database and check both messageto and messagefrom fields. The way I have worked with django is like each model represents a table, and corresponding to each object of the model class we have a row in the database. So according to this logic having a separate table for each messageto and messagefrom combo is not possible I think as we need to declare a separate class for each of them. Is there a way I can find the messages between the users without going through every message? I am looking for either some way with same implementation or a new implementation any is fine. Please help. -
Opening a Django Git Project: Swingtime?
this post may increase my unpopularity drastically, but a man can only try they say. So I worked my way through the very basic principals of Django and am now facing the task to build something myself. I want to build a calendar and have therefore looked on git for similar projects. I downloaded: Swingtime from git but there seems to be no manage.py. I try to run the demo folder - since it has a manage.py - but non of the urls in the url directory seem to work. How do I open this this project to see it in action? If anyone has some advice on how work through this bulk of code and form an understanding Id also be grateful. -
Django, django-allauth and the battlenet provider
First time attempting to use oauth with python django and django-allauth. I can't seem to make logins happen. I can get to the point where you are asked to authorize your site with battlenet, but when you're redirected to the callback url I just get this: {'code': 'unknown', 'provider': 'battlenet', 'exception': ProxyError(MaxRetryError("HTTPSConnectionPool(host='us.battle.net', port=443): Max retries exceeded with url: /oauth/token (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden',)))",),)} I have created my application in dev.battle.net, I've put the client key and the secret key in my django-allauth app, but I get stuck at this point. Anyone have any experience with this? -
Can amazon lambda post to sqlite database of a django app hosted on EC2?
I have an AWS lambda script that produces a json file, and a django app on an AWS EC2 instance. I want to make the json available to the django app. The django app has a default sqlite3 db, how can I get lambda to post to EC2? I am using the code below to post the results to a AWS RDS instance, but this might be costly for my needs and I'd be better off updating a db in the django app, of possible. ###################### # Save to RDS database ###################### try: created_at = time.strftime('%Y-%m-%d %H:%M:%S') with conn.cursor() as cur: cur.execute('INSERT INTO entries (created_at, useremail, datajson) values(%s, %s, %s, %s, %s)', (created_at, user, datastr)) conn.commit() # logging.info("Added to RDS MySQL table") except: print('Could not save to RDS') # logging.info("Could not save to RDS") (The lambda script is in python2) -
Cache a spatial lookup in Django
I work with Python 2.7 & Django 1.9. I managed to cache results of a spatial queryset when based on a polygon, but I can't manage to cache it when based on Distance from a location. The error returned is: "TypeError: can't pickle Binary objects" Any idea why ? Here is a summary of the caching function: qs = ThePlace.objects.annotate(distn=Distance('lnglat', populatedplacegeom)).filter(distn__lte=D(km=25).m) cache.set(cacheid, qs, 10000) For info: I also have several prefetch_related and select_related in the queryset. -
Django - Using jQuery/AJAX to access database
I hope someone can help as I have attempted this multiple times had had very little success. I have attempted to use the tango with django book to adapt it to this situation and done the same with many other examples online but had no luck. Anyway... I am currently designing a small 'Fake News' website with Django which has a mini game that displays a news article (Title, description, picture) to the user and they have to vote whether it is 'Fact' or 'Fiction', they are then told whether they are correct and how many people have voted for that answer previously. I have it working completely fine if I have all the data stored in a javascript variable like this: var questions = [ ["Pope Francis Shocks World, Endorses Donald Trump for President, Releases Statement", "News outlets around the world are reporting on the news that Pope Francis has made the unprecedented decision to endorse a US presidential candidate. His statement in support of Donald Trump was released from the Vatican this evening: 'I have been hesitant to offer any kind of support for either candidate in the US presidential election but I now feel that to not … -
A unit-test is not runing
I am trying to use selenium and unittest as in oreilly test driven development book.. i try a test to check for the title of the page and it should run and fail but it don't run here is the code: from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): self.browser.get('http://localhost:8000') self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') if __name__ == '__main__': unittest.main(warnings='ignore') when it run it. the message is: run = 0 tests in 0.000s where is the problem? -
Display list of all fieds in using a metaclass
Since I have 561 fields in a class, could we use a metaclass to help me displaying a list of all fields in this class? -
Crispy Form Not Rendering Input Fields
I believe I'm following the Django format the most concrete way possible, but these dang-on forms aren't becoming visible on my posts page: views.py: def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) form = SubForm(request.POST or None, request.FILES or None) if form.is_valid() and form.is_bound: successform=form.save() message.success(request, "Thank you for signing up!") else: message.error(request, "Sorry we couldn't put you in our mailing list") ################## LOGIC ################# context = { "title": instance.title, "instance": instance, "share_string": share_string, "timeshare": str(timeshare), "form": form, } return render(request, "post_detail.html", context) forms.py: class SubForm(forms.ModelForm): class Meta: model = SubscriptionList fields = [ "ipadd", "name", "email", ] templates/post_detail.py: {% extends "base.html" %} {% load crispy_forms_tags %} {% load urlify %} {% block head_extra %} {{ form.media }} {% endblock head_extra %} {% block meta %} """ Meta Stuff""" {% endblock meta %} <form method="POST" action="" enctype="multipart/form-data">{% csrf_token %} {{ form | crispy }} <input type="submit" class="btn btn-primary" value="Sign Up For Latest Trends!"/> </form> ############## INSTANCE OF THE BLOG POST UNDERNEATH ############## The form field isn't showing up, the csrf hidden input tag shows up, but the form variable I designated for the Subscription List will not present itself on the page. Sorry for such a trivial matter SO. -
Django throws TemplateDoesNotExist when looking for an unrelated template
This issue has been irritating me for the last few hours. It is throwing this error: TemplateDoesNotExist at /profile/max/ companies/user_detail.html Request Method: GET Request URL: http://localhost:8000/profile/max/ Django Version: 1.9 Exception Type: TemplateDoesNotExist Exception Value: companies/user_detail.html Exception Location: B:\Programs\Anaconda3\lib\site-packages\django\template\loader.py in select_template, line 74 Python Executable: B:\Programs\Anaconda3\python.exe Python Version: 3.5.2 Essentially, this is a DetailView, but the template I am calling is not located at companies/user_detail.html. In fact, it is actually called user_profile.html. You see the problem... In my views.py I have this view as: class UserProfile(generic.DetailView): model = models.User teamplate_name = "user_profile.html" context_object_name = "current_user" def get_object(self, queryset=None): user = models.User.objects.get(username=self.kwargs["username"]) return user Note again that user_detail.html does not exist. The url I am trying to target is: url(r'^profile/(?P<username>.+)/$', views.UserProfile.as_view(), name="user_profile"), The user max exists, so the issue it seems is locating this template. Also, I have tried creating a folder named companies and placing an HTML file called user_detail.html inside it, and the Template seems to be located by Django. I would prefer to not have to do this, however. Thanks for any help you can give me. -
python3: PIL / pillow and Django: turn text into image and display on page
I am trying to turn a text field into an image using pillow and Django. The text is created dynamically (so I cannot create all text beforehand, turn it into images, and upload them). Each image has to be created "on the fly" and then displayed on the correct page. I understand (maybe?) that the correct way to do that is to use the IO package to load the picture into memory and then pass it on to the django html to be displayed there. But I am having trouble with the execution. I am quite new to Django / Python programming, so I got someone to help me who told me to do something like this: def render(txt, fontsize=20, encoding=None): txt = txt.strip() lines = len(txt.splitlines()) or 1 font = ImageFont.truetype(ARIAL_TTF, fontsize) width, height = font.getsize(txt) image = Image.new("RGBA", (width, height*lines), (232,232,232)) draw = ImageDraw.Draw(image) draw.text((0, 0), txt, (0, 0, 0), font=font) temp = six.StringIO() image.save(temp, 'png') if encoding: return temp.encode(encoding) return temp.getvalue() The problem is that StringIO() produces a StringIO object that cannot be read as a file(name) by image.save -- at least this is the error message I got: "expected String got Bytes". Apparently, the above runs … -
ImportError using Mongoldb as broker for Celery
I have a Django project where i use mongoengine to use Mongodb. I want to set up celery with MongoDB as the Broker. I followed this tutorial: http://docs.celeryproject.org/en/v4.0.2/django/first-steps-with-django.html and http://docs.celeryproject.org/en/3.1/getting-started/brokers/mongodb.html When i run celery -A proj worker -l info i get ImortError: ENV/lib/python2.7/site-packages/kombu/transport/mongodb.py", line 13, in from pymongo.cursor import CursorType ImportError: cannot import name CursorType from pymongo.cursor import CursorType wroks in the python shell... Any Idea how to fix this? I have: Django==1.10.6 pymongo==2.8 (I need this version) celery==4.0.2 (pip install -U celery[mongodb]) -
Passing values to default Django authentication form
I have very silly question: How can I get value and assign it to django variables {{form.username}} and {{form.password}}? I have a bootstrap sign-in page and default django authentication views and forms for login : ` <form class="form-signin"> <h2 class="form-signin-heading">Please sign in</h2> <label for="inputEmail" class="sr-only">Email address</label> <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="Password" required> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> Remember me </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </form> </div>` If I put value={{form.username}} in input tag everything is working but I have to delete some text on start in input fields. Django version - 1.10.6 -
User Model fields not showing in Django Admin Panel
I have a basic model that extends the User model: from django.contrib.auth.models import User class Promotion (models.Model): User = models.ForeignKey(User) Rating = models.ForeignKey(Rating) Date_Effective = models.DateField() def __str__(self): return self.Rating.Rank.Short_Rank + ' ' + self.User.last_name + ' (' + str(self.Date_Effective) + ')' in my Admin.py, i have the models showing: admin.site.register(models.Promotion) when loading a promotion, the Short_Rank field and the Date_Effective fields show perfectly, but the User.last_name does not. ADM (2017-03-18) This is consistent with the rest of the models, and I am believing that the User model itself is not being attacked by the query in the admin panel. How do I get the name fields in the User model showing in the model page of the Admin panel? Thanks. -
empty fields in a class
For a target field, I would like to create a function in a class. That function will empty all fields, except the target field, whenever the field income_source is different of Employed. How could I ask to empty each field in my class? -
Django Haystack - AWS Elasticsearch connection refused
For my Django site deployed in AWS EC2 instance i am using AWS Elasticsearch service as Haystack backend. When I try to retrieve/create index data, its getting aborted with following error: File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/elasticsearch/client/__init__.py", line 531, in search 'local', 'preference', 'routing') File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/elasticsearch/transport.py", line 307, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/home/ubuntu/virtual/local/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 89, in perform_request raise ConnectionError('N/A', str(e), e) ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7ff3dfd39890>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7ff3dfd39890>: Failed to establish a new connection: [Errno 111] Connection refused) And the weird thing is, I got my codes working fine when I execute it in shell (python manage.py shell). But ends up in above error when the same code used in views.py and accessed via a nginx url. Can anyone please tell what went wrong in my settings? elasticsearch==1.9.0 django-haystack==2.4.1 Django==1.9.1 AWS Elasticsearch Service-1.5 or 2.3 -
Write python code in back end
I'm new to python web development and I'm making a web app for sentiment analysis. I have my sentiment analysis code written and running on terminal but I want to show the output on website. How can i proceed? -
DJANGO: Using CSS stylesheets in templates
I have a simple issue which I cannot seem to be able to solve. I am working on Django and I want to give some style to my template. Here is how I refer to the html template: <!DOCTYPE html> <head> <title lang="en">Stocknizer</title> {% load static %} <link href="{{ STATIC_URL }}style1.css" rel="stylesheet" type="text/css" /> </head> ... </html> in my setting.py file I have defined: STATICFILES_DIRS = [ 'C:/Users/Me/Desktop/project/mysite/mysite/static/', ] "static" is the folder in which I've put my css files Do you have any idea on where the problem is? I have checked at least 10 similar questions on this website and I still have this issue. Thank you in advance -
Django "No Such Table" Error - Django-seo2
I've very recently started to get into Django, so I apologize if this is a noob question. I'm attempting to add the package "Django-SEO2" to a project of mine, but I keep getting this error: django.db.utils.OperationalError: no such table: djangoseo_mymetadatamodelinstance I've been following this package's tutorial here: http://django-seo2.readthedocs.io/en/latest/introduction/tutorial.html#introduction-tutorial I created an seo.py file within my Post app with the exact code from their tutorial, and I successfully added it to the admin screen based on their instructions. That seemed to work fine, and the models populated in the admin screen as expected, but when I go to click on the item in the admin screen, I get the above error. Any help on this would be greatly appreciated! -
Filtering in Django Model Form where the user inputs the filter values
I am quite new to django and although my enthusiasm I am stuck to the below: I have the model class Task(models.Model): Taskdetails = models.CharField(max_length=500, null=True) asset = models.ForeignKey('Asset', null=True) def __str__(self): return str(self.id) and I have created several objects with the ModelForm technique I want to create a template that a user can choose an asset and by pressing the button to display all the tasks that are connected with this asset. I mention that an asset has many tasks. I am trying to do that using Django ModelForm. So, I created first of all the form class HistoryForm(ModelForm): class Meta: model = Task fields =('asset',) Then I created the view "history" where a user can choose the asset that is interested: def history(request): if request.method == "POST": hist_form = HistoryForm(request.POST) if hist_form.is_valid(): hist = hist_form.save(commit=False) hist.save() return ('results') else: hist_form = HistoryForm() return render(request, 'TaskTrace/history.html', {'hist_form': hist_form} The html tag (part of it) is the below {{ hist_form }} <p><a href="{% url 'results' %}"> <button type="submit" > Results</button></a></p> Then I want to take the choice that the user made and transfer it to the next view ('results') def results(request): tasks = Task.objects.filter(asset=request.POST.get('asset', None)) return render(request, 'Tasktrace/results.html', {'tasks': tasks}) … -
How to exclude fields when using Django _meta.get_fields()
My model has the standard "id" field, and I would like to exclude it when I use _meta.get_fields(). My current solution looks something like this: context_var = (MyModel._meta.get_fields())[1:] It works well enough, but I don't really like the slice solution. I'd rather remove the id field by name, or use a method that explicitly excludes the id field. Is there a more elegant solution? -
how to get username from login form, when reset password link is clicked django
I am trying to get the username from my login form when the reset password link has been pressed. view.py def ResetPassword(request): if request.method == 'POST': username = request.Post.get['login_username'] if username: #send password reset link via email else: #if username is empty search for your account return render(request, 'accounts/forms/email_search.html',{}) forms.html <form class="navbar-form navbar" method="POST"action="{% url 'login' %}"> {% csrf_token %} <div class="form-group"> {{ form.login_username }} </div> <div class="form-group"> {{ form.login_password }} </div> <button type="submit" id="loginBtn" class="btn btn-default">Submit</button> <br> <a href="{% url 'ResetPassword' %}">Reset Password</a> </form> -
query function in VBA Accesss
So I have to create a query function in access vba so that i can easily call a query when i click on a command button. my function looks like this: Public Function fCreateQueries(ByVal strQueryToRun As String) As String Dim strSQL As String Dim qryRun As QueryDef 'My sql statement strSQL1 = "SELECT gender, TannerSum, Jahr FROM Tabelle1 WHERE gender = '1'" With CurrentDb Set qryRun = .CreateQueryDef(strQueryToRun, strSQL1) DoCmd.OpenQuery qryRun.Name .QueryDefs.Delete qryRun.Name End With Set qryRun = Nothing End Function i have tried calling the function but it wont run can anyone help -
Use another class inside a class in python
I have two classes : @python_2_unicode_compatible class EmployerProfile(AbstractAddress): ... and @python_2_unicode_compatible class FinancialProfile(models.Model): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='financialprofile') income_source = models.CharField(_('Income source'), max_length=20, choices=settings.LOANWOLF_INCOME_SOURCE_CHOICES, default='employed') I would like to use FinancialProfile in the class EmployerProfile. In fact, my task is to tell if income_source == 'Employed', so all field inside the class EmployerProfile must be emptied. I thought I could user super(), but this method is used for inheritance, which is not the case here. Could anyone be able to help me with this task?