Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: can I have both "action=" and jQuery assigned to the same form?
I have a form inside my template, which sends the submitted data to "{% url 'javascript:index' %}": <form id="login-form" action="{% url 'javascript:index' %}" method="POST"> {% csrf_token %} {{ form }} <input id="create_table" type="submit" value="View results" /> </form> But I have also a jQuery script assisgned to the same form like this: $('#login-form').on('submit', function(event){ event.preventDefault(); console.log("form submitted!"); // sanity check $('#table').load('http://127.0.0.1:8000/results',function(){ $('#go_back').remove(); }); // <-- Add it Here! }); Problem is, the form is never posted to "{% url 'javascript:index' %}", because the jQuery script is executed first. Is there any way to make the form submission happen in this order: first send the data to "{% url 'javascript:index' %}", then run the script? -
How do I use MYSQL as the database in a Django project?
The default database of the Django is sqlite, however I want to use MYSQL instead.Since the MYSQLdb module is not supported in python3.x, the official doc of django recommend using mysqlclient and MySQL Connector/Pythoninstead.Here is the original doc: MySQL has a couple drivers that implement the Python Database API described in PEP 249: • mysqlclient is a native driver. It’s the recommended choice. • MySQL Connector/Python is a pure Python driver from Oracle that does not require the MySQL client library or any Python modules outside the standard library. These drivers are thread-safe and provide connection pooling. In addition to a DB API driver, Django needs an adapter to access the database drivers from its ORM. Django provides an adapter for mysqlclient while MySQL Connector/Python includes its own. I've got the latest version of mysql-client and mysql-connector-python, but as I execute themigratecommand, error occurs.Here is part of the message: Unhandled exception in thread started by .wrapper at 0x7f2112e99d90> Traceback (most recent call last): File "/home/lothakim/anaconda3/envs/py36/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in import MySQLdb as Database ModuleNotFoundError: No module named'MySQLdb'django..........core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.Did you install mysqlclient? It seems to be the problem of the database connection.But I followed every step of the official … -
How do you point an ElasticBeanStalk's Enviroment to a non attached RDS instance?
I tried following the instruction from AWS documentation https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.RDS.html?console_help=true but it seems to be outdated! I followed all the instructions specifically and most importantly:Added the detached RDS instance security group name(called default) to the Enviroment's Security group. I created the neccessary enviroment name like RDS_HOSTNAME, RDS_USERNAME etc.I can ssh into the detached RDS instance via the eb shell, so the instance is working. However, the elastic beanstalk's enviroment name RDS_HOSTNAME seems to still reference the deleted instance endpoint name. -
How can I display the form errors under each field?
I was wondering how can I display the form errors under each field. Considering I have the log in form, if there is a problem with username, then the specific errors should be displayed under, otherwise if there is a problem with the password, the error should be displayed under the password field. I have been searching for a proper way to do it, this is what I came with: <div class="jumbotron"> <form class="login" method="POST"> {% csrf_token %} <h4>Log In</h4> <p class="field">{{ form.username }}</p> <p class="field">{{ form.password }}</p> <button class="btn btn-default" type="submit">Log In</button> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} </form> </div> -
Django: Template Filters
I'm trying to create a small django app. I've create a model in something like this, class Model(models.Model): content = models.TextField() After doing so, I saved some text data into the database using django Admin panel. Here it is, Here is the <b>random</b> data. Click this link -> <a href="https://google.com">Google</a> But problem is that i'm getting the same exact output while printing out this data on screen. Is there any django filters which can change this above data into this -> Here is the random data. Click this link -> Google Thank You :) -
AssertionError: after accessing serializer.data
Trying to ovewrite my POST request Django REST framework. So far I was able to do it successfully until I started playing with the retrieved data from the data base. I searched online and I found similar question Django REST Framework perform_create: You cannot call .save() after accessing serializer.data with proposed solution is_valid(). Unfortunately for me it did not work, I also found online Overriding serialization and deserialization behavior which suggests to use serializer.validated_data. Again for me it did not work the error keeps insisting. Part of my views.py. views.py # class to be called when user is sending POST requests through url <ip>:<port>/upload/ class FileUploadView(views.APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): serializer = SnippetSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): # save the data so the file can be created serializer.save(owner=self.request.user, ) # instantiate the class the pass the request to be used by all methods file_obj = FileProcesses(request) # retrieve the data from the file list_of_data = file_obj.file_processing(settings.MEDIA_ROOT) # check filename in case of keywords store keywords file_name = request.data.get('file') if file_name.name == 'keywords.txt': keywords = '\n'.join(list_of_data) # store the retrieved data serializer.validated_data serializer.save(owner=self.request.user, code=keywords, keywords=keywords, ) else: information = '\n'.join(list_of_data) # entry = self.getLatestKeywords(serializer.data['id']) entry = … -
Django-Allauth: How to authenticate users via Chrome extension?
I'm building a Django web app with django-allauth handling user authentication. As title, how do you expose a RESTful API to authenticate users from a Chrome extension? Taking into account of both: locally stored username & password hash string pairs and third party social log-in providers? What is the best or simplest way to do this? -
General Settings for a website created with Django
Think that you want to define some settings like "Twitter username", "Meta description" etc. for your website which is created with Django. Is there any thing in Django to do this in really beautiful or logical way? I know there are duplicate questions but non of them has a logical answer to this problem. Django is the most powerful framework I've ever seen. But this really basic problem unsolved for me still. I did something like this: created GeneralSetting model. I added just one instance (entry) to this model in the admin panel and all my settings here. But "add new" button is still here too. Also, I'm using hardcoded general setting id. Maybe I can hide the 'add new' button, yes, but all of these are looking strange for me. I'm thinking that: there are some undiscovered ways to do this job which is unknown for many Django developers. Or, really, Django has no skill to do this thing easily? -
How do i enable users to upload downloadable files in django?
I'm using django on a project whereby there will be regular uploads of product catalogues which are to be made downloadable to site visitors on a downloads page, the problem is i can't figure out how to create a view that does this without hand coding the logic and the download url path. my current downloads view only serves one file and i have no way of managing the files without interacting with the code. can someone help? -
duplicate key value violates unique constraint .... Django error
I am trying to make a 'get' query on a model. The parameters that i'm using to query the model are foreign keys(both of them). The models looks something like this... class model_1(models.Model): field_1 = models.ForeignKey(model_2) field_2 = models.CharField(max_length = 512) field_3 = models.ForeignKey(model_3) class Meta: unique_together = ("field_1", "field_3") and i'm trying to run this query m = model_1.objects.get(field_1 = 'something', field_2 = 'something_1') But it throws back an error duplicate key value violates unique constraint... along with DETAIL: Key (model_1_id, model_3_id)=(1339, 5) already exists I'm not able to understand why the error is on duplicate keys when I'm trying to read the entries. It would have made sense to me if I were trying to insert a new record in it and had conflicting keys. Thanks! -
After moving the script from template to separate file, it stops working
If I put the below script at the bottom of my Django template: <script> $('#login-form').on('submit', function(event){ event.preventDefault(); console.log("form submitted!"); // sanity check }); </script> Everything works fine and "form submitted!" gets printed in the console on form submission. However, if I move the script to another file, so the template looks like this: <script src="{% static "javascript/scripts/create_table.js" %}"></script> and the "create_table.js" script file is: $('#login-form').on('submit', function(event){ event.preventDefault(); console.log("form submitted!"); // sanity check }); it doesn't work anymore. File directiories are OK. What am I missing? -
How to search my bucket to see if a certain file exists
Here's my s3 session: img = request.FILES.get('image') filename = random_string() """if filename exists in my s3 bucket: create another random_string""" session = boto3.Session( aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, ) s3 = session.resource('s3') s3.Bucket('my-bucket').put_object(Key='media/%s' % img.name, Body=img) Basically when I upload a file via AJAX, as per the code above, I generate a random filename. However before using this filename for the new uploaded image, I want to check that it doesn't exist, to prevent overlap. If it does exist, then try another random string. How can I do this? -
how to display nested json data on django template?
I am using an api where i can fetched data.The data look like: "Time Series (Daily)": { "2018-03-16": { "1. open": "94.6800", "2. high": "95.3800", "3. low": "93.9200", "4. close": "94.6000", "5. volume": "47329521" }, "2018-03-15": { "1. open": "93.5300", "2. high": "94.5800", "3. low": "92.8300", "4. close": "94.1800", "5. volume": "26279014" }, "2018-03-14": { "1. open": "95.1200", "2. high": "95.4100", "3. low": "93.5000", "4. close": "93.8500", "5. volume": "31576898" } In views.py def home(request): url='www.api.example.com' response = requests.get(url) geodata = response.json() return render(request, 'home.html', { 'Data': geodata['Meta Data'], 'Time': geodata['Time Series (1min)'] }) How to display this on my html view and how to write "2018-03-16" and "1. open" key on html like example:<li>{{ items.'1. open' }}</li> -
Not loading icon css from static ( 404 Error ) Flaticon and Font-mfizz
I'm creating a website and i needed a icon of python, so i searched that Flaticon had it. This is my HTML code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link href="{% static "css/flaticon.css" %}" rel="stylesheet" type="text/css"> <link href="{% static "css/font-awesome.css" %}" rel="stylesheet" type="text/css"> <link href="{% static "css/font-mfizz.css" %}" rel="stylesheet" type="text/css"> <meta charset="UTF-8"> <title>Title</title> </head> <body> <i class="icon-python" style="font-family: Flaticon, serif"></i> <i class="icon-python"></i> <i class="fa-gamepad"></i> </body> </html> I created a different html just to show this icon and make sure it was nothing related to other things in my HTML code. And this is the console from the element inspection on the html i ran with Django 'python manage.py runserver' in my localhost using Opera : GET http://xxxxxxxxx:xxxx/static/css/flaticon.css net::ERR_ABORTED GET http://xxxxxxxxx:xxxx/static/css/font-mfizz.css net::ERR_ABORTED And of course, the page has only the Font-Awesome icon, this is the same error i was getting from my main page. I'm using python and this is my Flaticon.css code /* Flaticon icon font: Flaticon Creation date: 17/03/2018 04:22 */ @font-face { font-family: "Flaticon"; src: url("./Flaticon.eot"); src: url("./Flaticon.eot?#iefix") format("embedded-opentype"), url("./Flaticon.woff") format("woff"), url("./Flaticon.ttf") format("truetype"), url("./Flaticon.svg#Flaticon") format("svg"); font-weight: normal; font-style: normal; } @media screen and (-webkit-min-device-pixel-ratio:0) { @font-face { font-family: "Flaticon"; src: url("./Flaticon.svg#Flaticon") format("svg"); } } [class^="flaticon-"]:before, … -
use django/json api for internal use in two views
I am developing a search engine for our college using Django-Haystack-Solr. I want auto-suggestion and spell check feature. So I used auto_query() and spelling_suggestion() method. This is my views.py file. As of now, it is only static script not taking any form input from actual user. from django.shortcuts import render from haystack.query import SearchQuerySet import json from django.http import HttpResponse def testpage(request): search_keyword = 'stikar' data = SearchQuerySet().auto_query(search_keyword) spelling = data.spelling_suggestion() sqs = SearchQuerySet().autocomplete(context_auto=spelling) suggestions = [result.title for result in sqs] link = [result.url for result in sqs] context = [result.context for result in sqs] the_data = json.dumps({ 'results': suggestions, 'link': link, 'context': context }) return HttpResponse(the_data, content_type='application/json') My main url.py file: from django.conf.urls import url, include from django.contrib import admin from search.views import testpage urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test/', testpage), # this is where JSON API is being generated url(r'^', include('haystack.urls')), # this is where actual search page with search form is ] Now, I have no idea how to link those two together. Any help would be appreciated. P.S: API is being rendered perfectly fine, no issues there. and sorry for bad English. Please ask me for any extra information. Thank you. :) -
django.db.migrations.exceptions.NodeNotFoundError Migration authentication
I was running my code on django and i ran into this problem. What might be the issue? I am using django 2.0.2 Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f6ead6dcea0> Traceback (most recent call last): File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run self.check_migrations() File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 274, in build_graph raise exc File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 244, in build_graph self.graph.validate_consistency() File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/db/migrations/graph.py", line 261, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/db/migrations/graph.py", line 261, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/geek/PycharmProjects/hadhari/venv/lib/python3.6/site-packages/django/db/migrations/graph.py", line 104, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration authentication.0001_initial dependencies reference nonexistent parent node ('auth', '0009_alter_user_last_name_max_length') -
Django filter with date range list in orm
Is there any way for filter with date range array in django orm? example : date_ranges = [["2011-01-01", "2011-01-31"],["2011-02-01", "2011-02-31"]] Sample.objects.filter(date__range__in=date_ranges) -
Django Auth 1.11 Template does not exists 'login'
I have been googling and attempting this and that and just can't get a login form to work. I have been following this tutorial which I have rebuilt a couple times in hope of catching a small error that I have missed. I also have been googling looking up errors and potential leads to to no avail. My issues are: When I run my Django app and try to reach http://localhost:9000/login/, I get two errors that toggle back and forth as I hit refresh in the browser. ERROR 1 TemplateDoesNotExist at /login/ login.html Request Method: GET Request URL: http://localhost:9000/login/ Django Version: 1.11.4 Exception Type: TemplateDoesNotExist Exception Value: login.html Exception Location: /home/vagrant/gst/venv/lib/python2.7/site-packages/django/template/loader.py in select_template, line 53 Python Executable: /home/vagrant/gst/venv/bin/python2.7 Python Version: 2.7.4 Python Path: ['/home/vagrant/gst/tools', '/home/vagrant/gst/venv/bin', '/home/vagrant/gst/tools/tools', '/home/vagrant/gst/venv/lib/python27.zip', '/home/vagrant/gst/venv/lib/python2.7', '/home/vagrant/gst/venv/lib/python2.7/plat-linux2', '/home/vagrant/gst/venv/lib/python2.7/lib-tk', '/home/vagrant/gst/venv/lib/python2.7/lib-old', '/home/vagrant/gst/venv/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/home/vagrant/gst/venv/lib/python2.7/site-packages'] Server time: Sat, 17 Mar 2018 19:31:48 -0700 Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/vagrant/gst/tools/tools/templates/login.html (Source does not exist) ERROR 2 NoReverseMatch at /login/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:9000/login/ Django Version: 1.11.4 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. … -
How to use Django rest framework to serve Media directory?
I want to design an API that serves all the files in my django media directory in response to a GET request-- what should my app's view.py look like? -
Integrate Django app in Mezzanine
I have an online resume in Django and I want to integrate it with a Mezzanine site. I copied the "resume" app to my Mezzanine project (I called it /Mezzanine) and added "resume" to > INSTALLED_APPS: #in Mezzanine/settings.py: INSTALLED_APPS = ( "resume", "moderna", ...) #in Mezzanine/urls.py: from resume import views ... urlpatterns += [ #place resume first url(r'^resume/$', views.index, name='index'), ...] Then I create a "resume" page from mezzanine. The setup above is able to override this /resume/ page. However, the theme (moderna) is not applied to /resume/. Is that the proper way to include Django in Mezzanine, and what is the recommended way to use the same styles? I tried running collectstatic but after that the whole Mezzanine lost the theme. -
django.db.utils.IntegrityError: null value in column "category" violates not-null constraint
I've deleted this field from my Post model, but it's still bringing up this error when create make a Post instance: return self.cursor.execute(sql, params) File "/home/james/app/env/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/james/app/env/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/james/app/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: null value in column "category" violates not-null constraint When I removed category from my Post model and performed makemigrations & migrate, it succesfully generated this file in my migrations folder: 0002_remove_post_category # -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2018-03-16 22:56 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('post', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='post', name='category', ), ] so It shouldn't be causing problems any more, but it still is. Any idea why? -
Error when deploying Django project to Heroku
I have a Django project that I've deployed on Heroku. For some reason, when I navigate to the home page for the app, there is application error. In the heroku logs, there is the error: at=error code=H10 desc="App crashed" method=GET path="/" dyno= connect= service= status=503 bytes= protocol=http . Based on other posts with similar issues, it seems like the error has to do with the Procfile. Inside the procfile I have the line: web: gunicorn uploader.wsgi --log-file - It seems that the problem might have to do with the Project name that is specified in the Procfile. The following is the files structure of the project: uploader_repo .git .travis.yml Procfile README.md requirements.txt src uploader settings settings.py urls viewer admin.py models.py views.py Should something other than uploader be used in the procfile setting? -
Django-Filter choices as buttons
I'm trying to have tabs that filter the data on click, like a button. We want to do this server-side rather than w/ javascript. We implemented django-filter as below: from .models import Engagement, Proposal, Campaign, ESGIssue import django_filters from django import forms from django.forms import CheckboxSelectMultiple class ProposalFilter(django_filters.FilterSet): company__name = django_filters.CharFilter(lookup_expr='contains') esgissue = django_filters.ModelMultipleChoiceFilter(queryset=ESGIssue.objects.all(), widget=CheckboxSelectMultiple) class Meta: model = Proposal fields = ['company', 'esgissue'] And then we have html code: <form method="get"> {% for thing in filter.form.esgissue %} <button class="button"> <span> {{ thing }} </span></button> {% endfor %} </form> We found that by using the widget=checkbock, and then wrapping the checkbox in a html button, we were able to have the filter change the view on-click whenever anyone selects a checkbox. For styling reasons, we REALLY don't want there to be a checkbox, though. It should look like a button or tab. Is there a way to do implement this filter using a button directly? If we get rid of the widget=checkbox, django-filters defaults to widget=select, but no information passes through when someone clicks the button. We looked through the Django Widgets we could substitute, but none seemed to be a simple button. I know we could define custom filters … -
Calculate average count per hour of day using Django ORM
I'm trying to retrieve the average count of items per hour over several days using the Django ORM. For example, if I have entries over two days: -------------------------------------------------- | ID | entry_timestamp | name | -------------------------------------------------- | 1 | 2018-03-12 16:12:11.000000 UTC | Albert | -------------------------------------------------- | 2 | 2018-03-12 16:32:05.000000 UTC | Josh | -------------------------------------------------- | 3 | 2018-03-12 16:56:45.000000 UTC | Sally | -------------------------------------------------- | 4 | 2018-03-13 04:32:11.000000 UTC | Eric | -------------------------------------------------- | 5 | 2018-03-13 07:34:11.000000 UTC | Max | -------------------------------------------------- | 6 | 2018-03-13 16:56:45.000000 UTC | Fred | -------------------------------------------------- | 7 | 2018-03-13 18:24:17.000000 UTC | Sharon | -------------------------------------------------- | 8 | 2018-03-13 18:32:45.000000 UTC | Alex | -------------------------------------------------- The expected averages, which is total entries within hour of the day / number of days would be: ---------------------------- | Hour | Average Entries | ---------------------------- | 04 | 0.5 | ---------------------------- | 07 | 0.5 | ---------------------------- | 16 | 1.5 | ---------------------------- | 18 | 1 | ---------------------------- I'm pretty sure this is possible solely in the Django ORM without using raw queries, but I can't quite figure out how to compute the average per hour of day. No date range will … -
Why is my Update URL link kicking me to the CreateNew html view
so this is a tag on from my previous stackoverflow post: Django updateView saving another instance instead of updating and i think i've narrowed it down. Whats happening is that when i click on the link to update my view, it sends me to the "create new" page. my problem is that I cant figure out why its doing that. Any and all help is appreciated. here is the code: question_form.html {% extends "base.html" %} {% load bootstrap3 %} {% block content %} <h4>Create New Question</h4> <form method="POST" action="{% url 'questions:create' %}" id="questionForm"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Post" class="btn btn-primary btn-large"> </form> {% endblock %} question_update.html {% extends "base.html" %} {% load bootstrap3 %} {% block content %} <h4>Update Question</h4> <form method="POST" action="{% url 'questions:update' pk=question.pk %}" id="questionForm"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Update" class="btn btn-primary btn-large"> </form> {% endblock %} question_detail.html {% block content %} this is the question detail view <h3>{{ question.question_html|safe }}</h3> <h3>{{ question.answer_html|safe }}</h3> <a href="{% url 'questions:update' pk=question.pk %}"> Update Question</a> {% endblock %} urls.py url(r'new/$', views.CreateQuestion.as_view(), name='create'), url(r'questionupdate/(?P<pk>\d+)/$', views.QuestionUpdate.as_view(), name='update'), url(r'questiondetail/(?P<pk>\d+)/$', views.QuestionDetail.as_view(), name='single'), views.py class CreateQuestion(generic.CreateView): model = models.Question form = QuestionForm fields = ('question', …