Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to translate docker-compose.yml to Dockerfile
I have an application written in Django and I am trying to run it in docker on Digital Ocean droplet. Currently I have two files. Can anybody advise how to get rid of docker-compose.yml file and integrate all the commands within Dockerfile ??? Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r reqirements.txt RUN python /code/jk/manage.py collectstatic --noinput docker-compose.yml version: '3' services: web: build: . command: python jk/manage.py runserver 0.0.0.0:8081 volumes: - .:/code ports: - "8081:8081" I run my application and docker image like following: docker-compose run web python jk/manage.py migrate docker-compose up output: Starting workspace_web_1 ... Starting workspace_web_1 ... done Attaching to workspace_web_1 web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | December 02, 2017 - 09:20:51 web_1 | Django version 1.11.3, using settings 'jk.settings' web_1 | Starting development server at http://0.0.0.0:8081/ web_1 | Quit the server with CONTROL-C. ... -
Django: Force uniqueness of many-to-many 'through' field
I am trying to design a database schema for a stock portfolio. What I have so far seems to work with one caveat --- a portfolio can contain two holdings of the same stock. I want a uniqueness of holdings with respect to the stock in the portfolio. I am new to Django, and haven't been able to figure it out. class Stock(models.Model): """ All available stocks """ symbol = models.CharField(primary_key=True, max_length=4) class Portfolio(models.Model): """ A user's portfolio containing stocks. """ user = models.OneToOneField(User, on_delete=models.CASCADE) usd = models.FloatField(default=0) stocks = models.ManyToManyField(Stock, blank=True, through='Holding') class Holding(models.Model): """ A holding of a stock in a portfolio. """ stock = models.ForeignKey(Stock) amount = models.FloatField(default=0.0) portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE) -
Django Admin 502 Bad Gateway - Corrupted migration?
I was in the middle of running a migration on my server and my internet went down. I'm now receiving 502 Bad Gateway errors on the detail page for models which had changes made of them. Rest of the site and admin runs fine. What's my next step to fix this? Try to re-run the migration? Revert the migration? How? I don't want to lose my data -
HTML Table in Django
I have a dataset which looks like that: dict = { 'columns': ['one', 'two', 'three'], 'headers': ['header1', 'header2', 'header3', 'header4'], 'data': [ ['111', '222', '333'], ['111', '222', '333'], ['111', '222', '333'], ['111', '222', '333'] ]} How I can get this exact table, using HTML and Django: Table that I need Please, provide the example of the code. -
How to get the name of uploaded file in Django
I have seen some question about it already but these couldn't solve my issue, that's why I'm asking a new question.So, don't mark this as duplicate, please! Using Python(3.6) & Django(1.10) I'm trying to get the name of uploaded file, but it returns AttributeError: 'NoneType' object has no attribute 'name' Here's what I have tried: From models.py sourceFile = models.FileField(upload_to='archives/', name='sourceFile', blank=True) From HTML template: <div class="form-group" hidden id="zipCode"> <label class="control-label" style="font-size: 1.5rem; color: black;">Select File</label> <input id="sourceFile" name="sourceFile" type="file" class="file" multiple data-allowed-file-extensions='["zip"]'> <small id="fileHelp" class="form-text control-label" style="color:black; font-size: .9rem;"> Upload a Tar or Zip archive which include Dockerfile, otherwise your deployment will fail. </small> </div> From views.py: if form.is_valid(): func_obj = form func_obj.sourceFile = form.cleaned_data['sourceFile'] func_obj.save() print(func_obj.sourceFile.name) what's wrong here? Help me, please! Thanks in advance! -
TypeError: 'NoneType' object is not callable(is ok in windows, but have this error in linux)
It can run successfully in Windows,but have a typeError when I want to run it in Linux. Description: [linux]Using Django==1.11, python==3.6 and mysql-connector-python==2.1.6 [windows]Django==1.10, python==3.6 and mysql-cinnector-python==2.1.6 the error picture thanks! -
cannot resolve dependencies of migrations files
I tried all the solution mentioned below: delete all files of migrations except init.py and db.sqlite3. After that run makemigrations also. applied fake migrations upgrade django and make migrations again delete migrations folder and then tried Any of this solution, could not help me.Everytime same error is generated(mentioned below). Please, help me to get rid of this error. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 52, in __init__ self.build_graph() File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 244, in build_graph self.graph.validate_consistency() File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\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 "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\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 "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\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 taggit.0003_tag_tags dependencies reference nonexistent parent node ('personal', '0006_auto_20171113_1322') -
How to move paginator block to the footer?
I have developed a django application. I added a paginator block to a webpage. It is placed on the wrong position. Instead, i want it to be placed below the list which is being shown. Actually, I am displaying group list on the page. Per page, only 5 group names will be displayed. Using pagination, i did that. But the problem is i am unable to place it in a correct position. I am attaching an image of the page. The html page for this is: {% extends "groups/group_base.html" %} {% block pregroup %} <div class="col-md-4"> <div class="content"> {% if user.is_authenticated %} <h2> Welcome back <a href="{% url 'posts:for_user' username=user.username %}">@{{user.username }}</a> </h2> {% endif %} <h2>Groups</h2> <p>Welcome to the Groups Page! Select a Group with a shared interest!</p> </div> {% if user.is_authenticated %} <a href="{% url 'groups:create' %}" class="btn btn-md btn-fill btn-warning"><span class="glyphicon glyphicon-plus-sign"></span> Create New Group!</a> {% endif %} </div> {% endblock %} {% block group_content %} <div class="col-md-8"> <div class="list-group"> {% for group in object_list %} <a class="list-group-item" href="{% url 'groups:single' slug=group.slug %}"> <h3 class="title list-group-item-heading">{{ group.name }}</h3> <div class="list-group-item-text container-fluid"> {{ group.description_html|safe }} <div class="row"> <div class="col-md-4"> <span class="badge">{{ group.members.count }}</span> member{{ group.members.count|pluralize }} </div> <div … -
How to load more content in django application?
I have developed template for viewing the group list in my django application. What I came to know is that, after more groups, the page is scrolling down. I am unable to see all the names of the groups. And also I want to view only 4 group names on the starting and then after clicking load more button, next 4 groups have to be shown. I am unable to do this. {% extends "groups/group_base.html" %} {% block pregroup %} <div class="col-md-4"> <div class="content"> {% if user.is_authenticated %} <h2> Welcome back <a href="{% url 'posts:for_user' username=user.username %}">@{{user.username }}</a> </h2> {% endif %} <h2>Groups</h2> <p>Welcome to the Groups Page! Select a Group with a shared interest!</p> </div> {% if user.is_authenticated %} <a href="{% url 'groups:create' %}" class="btn btn-md btn-fill btn-warning"><span class="glyphicon glyphicon-plus-sign"></span> Create New Group!</a> {% endif %} </div> {% endblock %} {% block group_content %} <div class="col-md-8"> <div class="list-group"> {% for group in object_list %} <a class="list-group-item" href="{% url 'groups:single' slug=group.slug %}"> <h3 class="title list-group-item-heading">{{ group.name }}</h3> <div class="list-group-item-text container-fluid"> {{ group.description_html|safe }} <div class="row"> <div class="col-md-4"> <span class="badge">{{ group.members.count }}</span> member{{ group.members.count|pluralize }} </div> <div class="col-md-4"> <span class="badge">{{ group.posts.count }}</span> post{{ group.posts.count|pluralize }} </div> </div> </div> </a> {% endfor … -
Extract important information
I am trying to extract specific information i.e money value,and Date/Time. pesa = 'BS39OR301 Confirmed. You have received Ksh350.50 from MICHAEL FEDERSEN 254729901555 on 15/10/11 at 11:52 AM New M-PESA balance is Ksh350.50.Save & get a loan on Mshwari'" money = re.search(r'Ksh(\d+.?\d*)',pesa) print(money.group(0) I need extracted the data and save it to a database where by there is a table which contain money_received,date_received etc so i want to get numeric digits only e.g 350.50 and for date it should be 15/10/11 11:52. using the above code currently gives me a result of ksh350.50. -
How to list all relations and foreign keys in for all models in django?
I need a script which writes to csv displaying all models names, foreign keys and relationship with other models(if any.) How to get all models and how do I list a the foreign key field and model it is referencing to? -
form.is_valid() is not running on first visit?
When the page is first loaded, the initial form values are loaded but if form.is_valid() did not run (I know this for certain from some testing). Why? views def view(request): form = FilterForm(request.GET or None) if form.is_valid(): # code processing... forms class FilterForm(forms.Form): filter_1 = forms.BooleanField(initial=True, required=False) filter_1 = forms.BooleanField(initial=False, required=False) filter_1 = forms.BooleanField(initial=False, required=False) -
How do I force Django queryset return datetime field in current timezone?
I have Django model: class Deal(models.Model): ... created_at = models.DateTimeField(auto_now_add=True) When I get created_at value by queryset, it always return to me the datetime value with tzinfo=<UTC> like this: Deal.objects.filter(id=62).values('created_at') <QuerySet [{'created_at': datetime.datetime(2015, 10, 26, 4, 10, 54, 997000, tzinfo=<UTC>)}]> How do I force queryset return datetime value in current timezone (e.g Asia/Ho_Chi_Minh)? -
Django: Bootsrap-fileinput with Resumable.js working example
Bootstrap-fileinput module works perfectly, but when it comes to large file upload(~2GB or more), Django Server side (Apache or Nginx) would encounter time-out issue. By setting a longer window for large file upload doesn't seem optimal, which leads me to try Resumable.js Does anyone have a working example of setting up Django with Resumablejs, especially if I want to use bootstrap-fileinput at the same time? -- Both js file and server side set-up to accept chunked files. (e.g. r.assignBrowse in Resumable.js would break the file preview in bootstrap-fileinput) Really appreciate it! -
Seemingly weird logic of HTTP requests in Django
I have a problem that I solved but the fact that I don't understand how tells me that there is something basic I'm missing. Hope somebody can help me. So I have a class based update view with inline formsets. I use crispy forms to render the view. The code below was first working, then for some reason it started giving me Management form missing error when just trying to load the update page in my browser. #views.py: class CaveUpdateView(UpdateView): model=Cave form_class=CaveForm template_name='caves/cave_form.html' def get_context_data(self,**kwargs): context = super(CaveUpdateView, self).get_context_data(**kwargs) entrance_helper = EntranceFormSetHelper() context['entrance_helper'] = entrance_helper if self.request.GET: context['entrance_formset']=EntranceInlineFormSet(instance=self.object) else: context['entrance_formset']=EntranceInlineFormSet(self.request.POST, instance=self.object) After wrecking my brains out, I changed the last 4 lines of the get_context_data function to this and everything was solved: if self.request.POST: context['entrance_formset']=EntranceInlineFormSet(self.request.POST, instance=self.object) else: context['entrance_formset']=EntranceInlineFormSet(instance=self.object) So my question is, how are these two expressions not equivalent? Is there another type of request I somehow make my browser send by refreshing? -
How to store Templates in Django 1.11?
I have two ways to use templates like this. Which is good in Django 1.11 1st way app1/ templates/ contact.html app2/ templates/ home.html about.html And then in settings TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'app1/templates'), os.path.join(BASE_DIR, 'app2/templates')], ... } 2nd way app1/ ... app2/ ... templates/ home.html about.html contact.html And then in settings TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], ... } Which is better in arranging templates -
django.utils.datastructures.MultiValueDictKeyError: "'date'"
I have a form for adding the stock to the table(not save to database). Multiple items can be added like date(mandatory), item(FK not mandatory), item_group(FK not mandatory), remarks etc. When user adds the stock to the table and hit the save button then those added items should be saved to the database. What i tried is, when add button is clicked, the items are fetched using jquery and add it to the table. This one is working correctly but when I try to post those added items to the database when save button is clicked, I get an error of django.utils.datastructures.MultiValueDictKeyError: "'date'" I am using FormData so I can use form.is_valid and save the form to database so I can render the error if error exist. Here is the code {% block content %} <div class="right_col" role="main"> <h1 class="text-center">Stock</h1> <form class="stock-form"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="Save" /> </form> <button class="btn btn-primary add-stock">Add</button> </div> <div class="stock-list"> {% include 'dashboard/stocks/stock_to_save_list.html' %} </div> {% endblock content %} {% block javascripts %} {{ block.super }} <script> var objList = []; $(document).ready(function() { $('.add-stock').on("click", function(){ var obj = {}; obj['date'] = $('#id_miti').val(); obj['item_group'] = $('#id_item_group').val(); obj['item'] = $('#id_item').val(); obj['department'] = $('#id_department').val(); … -
Django Rest Framework APITestCase reques tofrmat
When trying to test apis that are decorated with @api_view I receive a format that does not match to the response when testing it manually. I expect the following format: { "field": "string value" } but when I try to post(from tests) I receive error because the format appears to be this one: { "field": ["string_value"] } To reproduce this problem: class Tests(rest_framework.test.APITestCase): def test_api(self): ... response = self.client.post(url, data) ... -
Working around with Javascript libraries and Django views
I'd like to ask the pros out here if there is such a way to use a javascript library/api in Django views. Like, maybe a middle-getter or something without using ajax (or can use ajax but not from a template action)? If you know osmtogeojson, its a javascript library to convert osm data to geojson. Obviously it'll be easy to call view from template using ajax and passing the converted data to it. My problem is, when the user wants to directly input the URL, the views must be able to handle the direct conversion without interacting with the template (hence can't send data using ajax (maybe?)). Any way to use the library from Django views directly or at least like an ajax call that will fire automatically if it enters a ValueError in my try/except code? -
Django model, how to create varying choices in model field based on form submitted?
Suppose I have a model for books, and a page that user can submit a form to filter books. After a user submit a form, display a result page that has a checkbox for each book, and then user can select some books(at least 1) from the result page and submit a new form. My question is since the result page depends on the first form submitted, how can I dynamically create a varying choices on the result page? -
Errors in my python code: Can't connect to MySQL server
I was trying to run a python project located here which is for ad detection inside a video. I installed the required dependencies on my Ubuntu 16.04 (by running the dependencies.sh). I changed the comdet.py main part to account for my input file: def test_recognize(): #input_file_path = '../test/test.mp4' input_file_path = '../test/nadal-news.mp4' ad_det = ComDet() ad_det.recognize_ads_file(input_file_path) if __name__ == '__main__': #test_generate() test_recognize() Based on the instruction, I just do python2.7 comdet.py. After a few dependencies and import problems, now it complaints about not being connected to the local SQL database: _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)") What is the problem? I thought maybe I should run start-server.sh located in src/web, but that does nothing. I'm new to python. -
Cannot launch Scrapy as I keep getting "INSTALLED_APPS." % (module, name)
I'm trying to run a scrapy script but today when I started it I get: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. To fix this I added: from django.conf import settings settings.configure() Now I get: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. With: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Now: "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I've then went to my scrapy folder in Anaconda and tried adding: INSTALLED_APPS = [ 'myAppName.apps.myAppNameConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', This is generally for Django though so I don't think it approved. Can someone help me get out of the array of bug errors I'm getting so I can launch scrapy? I've been trying to launch scrapy program today but feel I'm going on an endless quest for different errors. Am I overthinking this and it's as simple as deleting a few lines of code or a case of wrong directory? Thanks from django.conf import settings settings.configure() from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from scrapy import cmdline … -
SQL 1064 Error, Syntax going unseen
SELECT i.*, ii.file_location FROM group_shop_item i, group_shop_itemimage ii, group_shop_brand b WHERE i.brand_id = b.id AND b.brand_status_id = 1 AND i.is_deleted = 0 AND i.is_displayed = 1 AND i.id = ii.item_id AND ii.is_main = 1 AND i.deal_participate = 1 AND i.brand_label_id IS NOT NULL ORDER BY i.datetime_modified DESC; This SQL query keeps throwing me a 1064. It seems to be on the last line which I've tried with and without the i table variable. I can't for the life of me catch the error, anyone can lend me another pair of eyes? I'm throwing this as a RAW query into the in built Django function and building this query with string concatenation. This copy paste is directly from a print I've done from the command line. It's outputting neatly but isn't reading when I run the view on my browser. -
Are there examples of reactjs and django-rest-framework email verification
Im pretty new to reactjs and creating a site which the backend is django drf. How can I accomplish email verification that the message will show on some reactjs page. Most of the documented email verification link points on the django backend and return the massage via json. How to consume that message on my reactjs app? -
Django admin 'Post' object has no attribute 'publish'
I want to create admin backend with django modules/blog/admin.py from django.contrib import admin from .models import Post # Register your models here. admin.site.register(Post) I except to Add new blog post content when i click SAVE AttributeError at /admin/blog/post/add/ 'Post' object has no attribute 'publish' Request Method: POST Request URL: http://ilkblog.dev:8000/admin/blog/post/add/ Django Version: 1.11.7 Exception Type: AttributeError Exception Value: 'Post' object has no attribute 'publish' Exception Location: /data/lib/python3.6/site-packages/django/db/models/base.py in _perform_date_checks, line 1146 Python Executable: /data/bin/python Python Version: 3.6.3 Python Path: ['/app/app', '/data/lib/python36.zip', '/data/lib/python3.6', '/data/lib/python3.6/lib-dynload', '/data/lib/python3.6/site-packages'] Server time: Fri, 1 Dec 2017 22:36:08 +0000