Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show many models in one list in Django Admin?
I have many similar models with different fields, like: # app_one/models.py class AppOne(models.Model): number = models.IntegerField(_('Number'), default=0) ... # app_two/models.py class AppTwo(models.Model): name = models.CharField(_('Name'), max_length=255) ... # app_three/models.py class AppThree(models.Model): is_ready = models.BooleanField(_('Is ready?'), default=False) ... Any way, how to show all of them in Django Admin page into the one list? For example, with model name badge for pretty view. It's would be great solution if you have many similar models, like orders for very different products with different fields, and you want to show and may click to administrate all of them in one place (one list). I use Django 2.x. -
Render Chart from custom template in Django
I am trying to render chart (Echart) from costume template. I have a base where JS librarires included and a block where I want to show my chart. In this block there a many things and I would like to separate my charts via custom templates. According to the Echart example I have to render it. The problem is that I already render my other things that is why i couldn't create an other view which render to the same page. That is why I use custom template.For the simplicity I attach my example code without the base.html. My view: # Source: test/templatetags/test.py from __future__ import unicode_literals import math from django.http import HttpResponse from django.template import loader from pyecharts import Bar from pyecharts.constants import DEFAULT_HOST from monitor.models import Test from django import template register = template.Library() @register.simple_tag def chart(): test_data=Test.objects.all() #Here is my Django query from my databse data=[i['a'] for i in test_data] attr=[i['b'] for i in tropo_data] bar = Bar("Test Chart") bar.add("Test",attr, data, is_stack=True) bar_chart = bar context = dict( myechart=bar_chart.render_embed(), host=DEFAULT_HOST, script_list=bar_chart.get_js_dependencies() ) return context My template: Source test/templates/test/chart.html <!DOCTYPE html> <html> {%load chart%} <head> <meta charset="utf-8"> <title>Proudly presented by PycCharts</title> {% for jsfile_name in script_list %} <script … -
Django form valid even if it doesn't exist in template
I have multiple forms using a single submit button in my template with prefix=name using CrispyForms. Check if a form exists or is rendered in Template. Django I have the following code in my template {% extends BASE_TEMPLATE %} {% load crispy_forms_tags %} {% block title %}<h2>New Thread</h2>{% endblock %} {% block content %} <div class="col-md-6"> <form method="post" accept-charset="utf-8">{% csrf_token %} {{ threadForm|crispy }} {{ postForm|crispy }} {% if SHOW_WIKI %} {{ wikiFrom|crispy }} {% endif %} <input type="submit" class="btn btn-primary btn-sm" value="Submit"/> </form> </div> {% endblock %} The only filed which the WikiForm renders has blank=True. What happens when I do wikiForm.is_valid() in my code is even though it hasn't been shown in template it is valid according to Django. Why does this happen? Is there a way to fix this in a way other than making the field in my wikiForm to blank=False? -
Not able to create table with textField
I have model from cgkapp.validators import validate_number # Create your models here. class Master_Questions(models.Model): Question_Number = models.AutoField(primary_key = True), Question_Text = models.TextField(max_length = 100), Option1 = models.TextField(max_length=50), Option2 = models.TextField(max_length=50), Option3 = models.TextField(max_length=50), Option4 = models.TextField(max_length=50), Answer = models.TextField(max_length=50), Difficulty_Level = models.IntegerField(validators=[validate_number]) and my table is created as below. The textfields are not created. sqlite> .schema cgkapp_master_questions CREATE TABLE "cgkapp_master_questions" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "Difficulty_Level" integer NOT NULL); -
raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet..how to load the apps?
i was trying to run the following command:: python populate_book.py and stuck with this error:: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. The Whole Traceback is as follow:: Traceback (most recent call last): File "populate_book.py", line 6, in <module> from opac.models import Book, BookCopy File "/home/prashant/Desktop/po/opac/models.py", line 6, in <module> from transactions.models import EndUser File "/home/prashant/Desktop/po/transactions/models.py", line 4, in <module> class EndUser(models.Model): File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. settings.py:: # Django settings for cope project. import os DEBUG = True TEMPLATE_DEBUG = DEBUG PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) ADMINS = ( ('pulkit', 'data.pulkit@gmail.com'), ('shashank', 'shashankgrovy@gmail.com'), ('sourabh', 'sourabh.coder@gmail.com'), ('utsav', 'kumaruts@gmail.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'cope.db', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '3306', # Set to empty string for default. } } # Hosts/domain names that are valid … -
react native 0.50.3 authorization header not sent
I am using react-native 0.50.3 to send token authenticated requests to my backend and unfortunately the 'authorization' part of the header is not send by the fetch. My code is the following : async componentDidMount() { var mytoken = await AsyncStorage.getItem('token'); fetch('http://myserver:8000/home', { method: 'GET', headers: { 'Accept': 'application/json', 'Origin': '', 'Content-Type': 'application/json', 'authorization': 'Bearer ' + mytoken } }) .then((response) => response.json()) .then((content) => { this.state.user = content.user; }) .done(); } And on my server side, the wireshark trace shows that the authorization is not in the request header : Hypertext Transfer Protocol GET /home/ HTTP/1.1\r\n Host: 10.150.21.124:8000\r\n Content-Type: application/json\r\n Origin: \r\n Accept: application/json\r\n User-Agent: Expo/2.3.0.1012011 CFNetwork/893.14 Darwin/17.3.0\r\n Accept-Language: en-us\r\n Accept-Encoding: gzip, deflate\r\n Connection: keep-alive\r\n \r\n [Full request URI: http://10.150.21.124:8000/home/] [HTTP request 1/1] [Response in frame: 2326] And of course I get a 401 unhautorized by the server. My backend is a django API with CORS installed and CORS_ORIGIN_ALLOW_ALL = True and ALLOWED_HOSTS = ['*']. The versions of my developments framework elements are the following : npm 4.6.1 node v9.3.0 react-native-cli 2.0.1 Thank you for your help. Alex. -
Binding django and angular 1
I have angular project that binding with django. Angular template has: <script type="text/ng-template" id="document_received_date.html"> <input type="text" ng-model="$parent.model"> </script> Django has domain: class Podgotovka(Activity): fields = [ 'document_recieved_date' ] And model has field "document_recieved_date": document_recieved_date = models.DateField(null=True, default=None) If I edit input the client send http request to django. I don't understand how client send request to django and how model write data to BD. What mechanism do it? Do you have some idea? -
Django - all form select options going to the same page
I have a for loop for select options in my template. The options are displaying correctly, but when I submit they all go to the same page. <div> /* If I take this for loop out then I get a reverse error. I need the dir for the regex. Other methods reverse to the program page using dir. */ {% for function_program in function_programs %} <form action= "{% url 'project:program_page' dir=function_program.program.dir %}" method='post'> {% csrf_token %} {% endfor %} <br> <select id=options name="program"> <option>Choose From List</option> {% for function_program in function_programs %} <option value="{{function_program.program.dir}}"> {{funtion_program_program.name}}</option> {% endfor %} </select><br> <input type="hidden" name="dir" value=" {{function_program.program.dir}}"> <input type="submit" value=" Go to page"> </form><br> </div> urls.py url(r'^program_page/(?P<dir>\d+)$', views.program_page, name='program_page'), url(r'^source/(?P<dir>\d+)$', views.source, name = source') views.py def function_page(request, Function_id): assignments = Function.objects.get(id=Function_id) function_programs = WP.objects.filter(id=Function_id) context = { 'assignments': assignments, 'function_programs' : function_programs, } return render (request, 'project/function.html', context)enter code here def capacity_req(request, dir): info = Program.objects.information(request.POST) return redirect (reverse('project:program_page', kwargs={'dir': dir})) Terminal Using request.POST I get the following in the terminal: <QueryDict: {u'function_program': [u'332456'], u'csrfmiddlewaretoken': [...], u'dir': [u'']}>` /* Page 332456 is the right page for my selection. But the template renders 123408 for all the items on the list. */ Can someone … -
Django Rest Framework import CSV to models
is there any way to import csv file to django rest framework models? Thank You in advance. -
Django segmentation fault
When I try to start 'python manage.py runserver', I endup with 'Segmentation Fault'. I could also notice on repetitive try, sometimes server gets up and running. When I run with 'python -v manage.py runserver', here're the last few lines. `import 'django.core.handlers' # <_frozen_importlib_external.SourceFileLoader object at 0x0000028248BC4C50> # C:\Users\pc\CODE\my_django_env\lib\site-packages\django\core\handlers\__pycache__\wsgi.cpython-36.pyc matches C:\Users\pc\CODE\my_django_env\lib\site-packages\django\core\handlers\wsgi.py # code object from 'C:\\Users\\pc\\CODE\\my_django_env\\lib\\site-packages\\django\\core\\handlers\\__pycache__\\wsgi.cpython-36.pyc' # C:\Users\pc\CODE\my_django_env\lib\site-packages\django\core\handlers\__pycache__\base.cpython-36.pyc matches C:\Users\pc\CODE\my_django_env\lib\site-packages\django\core\handlers\base.pySegmentation fault Please note, I get above error in newly installed Windows 10 machine. With all other same settings, I am able to run this project successfully in another machine running with older windows version. May I know what could be issue in this. -
Rendering validation errors when using Ajax to POST Django form data
How does one generally go about handling validation errors when using Ajax to process POST requests of Django forms? I'm a server-side dev dabbling in a bit of pure JS to learn the ropes. I finished writing AJAX methods to handle the POST request of a Django form, but am now unsure regarding how to render validation errors. For instance, here's a simple Django form: class TextForm(forms.Form): reply = forms.CharField(widget=forms.Textarea(attrs={'cols':30,'class': 'cxl','autocomplete': 'off','autofocus': 'autofocus'})) def __init__(self,*args,**kwargs): super(TextForm, self).__init__(*args,**kwargs) self.fields['reply'].widget.attrs['id'] = 'text_field' def clean(self): data = self.cleaned_data reply = data["reply"].strip() if not reply: raise forms.ValidationError('Write something') elif len(reply) > 1500: raise forms.ValidationError("Can't exceed 1500 chars") return reply And here's how the Ajax request works: function overwrite_default_submit(e) { // block the default behavior e.preventDefault(); // create and populate the form with data var form_data = new FormData(); form_data.append("reply", text_field.value); // send the form via AJAX var xhr = new XMLHttpRequest(); xhr.open('POST', e.target.action); xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken')); xhr.send(form_data); } What's the best pattern to catch and display validation errors under such circumstances? Would love to see an illustrative example of how the experts do it. Note: I prefer pure JS at this point since that's what I'm starting with. JQuery's on my radar, but I'll look … -
django paginator not work well when showing search data
I select datetime to find the data from mysql database,then I use paginator to show my search data. the first page of paginator is right ,but when i click next page ,it will not follow my search data list to show. It shows the second page of whole data list. I have no idea ,please help me ,thanks. The first page of paginator the console shows "GET /blog/create/?csrfmiddlewaretoken=YPVGofXCsTIlZe578CmzzvJ8I5bFQPe3cMniHPQmjugHGNjlz2aVnFZnVvTYPhN8&datetime1=2018-01-16&datetime2=2018-01-31&search= HTTP/1.1" 200 7530" The second page of paginator ,the console shows GET /blog/create/?page=2 HTTP/1.1" 200 7722 I think maybe the wrong url lead the wrong result. but I don't know how to fix it. Here is my views.py from django.template.loader import get_template from django.template import RequestContext from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render,render_to_response from datetime import datetime from .form import DateRangeForm from .models import Post import tkinter.messagebox import logging from tkinter import * from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger # Create your views here. def answer(): showerror("Answer", "Sorry, no answer available") def homepage(request): posts = Post.objects.all() now = datetime.now() context = {'posts':posts,'now':now} return render(request,'jishi.html',context) def showpost(request,times): template=get_template('post.html') ##posts=Post.objects.all().values('customer') posts=Post.objects.filter(pub_date__year=2018) now = datetime.now() html = template.render(locals()) return HttpResponse(html) def foobar(request): if request.method == "GET": posts = Post.objects.all() date_sel1 = request.GET.get('datetime1',None) … -
Can i use DJango web application to connect the SQL database and display the same on Web page?
I have python based script to get emails and transfer it to SQL database and i want to display the same data on we. is it okay to use Django framework to apply the same ? -
Django TypeError when I try to print context in views.py
I use Python 3.6.4. When I try to print the context in a DetailView using this code: class FormularDetailView(DetailView): model = form template_name = "detail.html" def get_context_data(self,**kwargs): print (self.kwargs) context = super().get_context_data(**kwargs) context['formulare'] = form.objects.all() print (context) return context I get this error: File "C:\Victor\Django_CNC\src\formular\views.py", line 44, in get_context_data print (context) File "C:\Victor\Django_CNC\venv\lib\site-packages\django\db\models\base.py", line 513, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) TypeError: __str__ returned non-string (type datetime.date) [02/Feb/2018 09:45:46] "GET /1/ HTTP/1.1" 500 84731 kwargs are printed: print (self.kwargs) {'pk': 1} what am I missing? -
python3 django error imort name url
I am getting the "from core import urls as core_api_urls ImportError: cannot import name 'urls'" error when I run python3 manage.py runserver on ubuntu terminal. I use the following configuration: Python 3.5.2 Django 1.11.2 Please help me how I resolve this issue. -
What is a proper way to Override - Delete() method in Django Models?
I have an Employee model, and I don't want an objects of this Model to be deleted completely from DB. What I want is to keep them in DB even after 'deleting' them. I ended up building this solution, but it's confusing me a little bit: class EmployeeQuerySet(models.QuerySet): def delete(self): self.update( is_deleted=True, datetime_deleted=datetime.now() ) class Employee(models.Model): user = OneToOneField(User, on_delete=CASCADE) is_deleted = BooleanField(default=False) objects = EmployeeQuerySet().as_manager() def delete(self): # Should I use this: self.is_deleted = True super(Employee, self).delete() # Or this: self.is_deleted = True self.save() # Or this: self.update(is_deleted=True) I'm confused about having 2 delete methods, one in model and second in models.QuerySet. Can I accomplish what I want with just 1 delete method ? As I understood, delete() in models.QuerySet will be triggerred only if delete group of objects, and delete method in model will be triggerred only if I delete a single object, am I wrong ? How to accomplish what I want in a right way ? Thank you -
AssertionError: 404 != 200 in django test
When I test the simple app according to tutorial 'AssertionError: 404 != 200' is occured. Can anybody fix this problem? (Project name: simple_project, app name inside the project: pages) My app-level urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), path('about/', views.AboutPageView.as_view(), name='about'), ] My app-level views.py: from django.views.generic import TemplateView class HomePageView(TemplateView): template_name = 'home.html' class AboutPageView(TemplateView): template_name = 'about.html' My project-level urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] My tests.py: from django.test import SimpleTestCase class SimpleTests(SimpleTestCase): def test_home_page_status_code(self): response = self.client.get('/') self.assertEquals(response.status_code, 200) def test_abaout_page_status_code(self): response = self.client.get('about') self.assertEquals(response.status_code, 200) When I test, this error is occured: FAIL: test_abaout_page_status_code (pages.tests.SimpleTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\User\Dj\simple\pages\tests.py", line 10, in test_abaout_page_status_code self.assertEquals(response.status_code, 200) AssertionError: 404 != 200 -
django get the strange request while runserver
I am curious, I run the runserver with Django, the first request is what I am working on, but how about the others? I don't provide baidu server, why does someboy request it from my temporary server? [02/Feb/2018 12:20:05] "GET /stk/?format=json&_=1517542783567 HTTP/1.1" 200 2247 Invalid HTTP_HOST header: '1.164.39.192'. You may need to add u'1.164.39.192' to ALLOWED_HOSTS. [02/Feb/2018 12:50:54] "GET //wp-login.php HTTP/1.1" 400 62538 Invalid HTTP_HOST header: '1.164.39.192'. You may need to add u'1.164.39.192' to ALLOWED_HOSTS. [02/Feb/2018 12:51:20] "GET /wp//wp-login.php HTTP/1.1" 400 62571 Invalid HTTP_HOST header: 'www.baidu.com'. You may need to add u'www.baidu.com' to ALLOWED_HOSTS. [02/Feb/2018 14:15:00] "GET http://www.baidu.com/cache/global/img/gs.gif HTTP/1.1" 400 62677 -
Sqllite and Django shell are not in sync
I have deleted a table from sqllite3 shell and then when I try creating it again by running python manage.py migrate/python manage.py makemigrations table is not created and showing below error. How to re-create the table and make my db and the API is insync. I tried with the python manage.py dbsync also but not worked. Operations to perform: Apply all migrations: admin, auth, cgkapp, contenttypes, sessions Running migrations: Applying cgkapp.0002_delete_questions...Traceback (most recent call last): File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: cgkapp_questions The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle fake_initial=fake_initial, File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/shrivatsa555/.virtualenvs/django20/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, … -
Find the PYTHONPATH/env bitnami uses and how to use it
I've setup the one-click install of bitnami on Google Cloud. It's got Django 2.0 installed and that only works with python 3.x shown when I get out of a virtualenv I've created (djangoenv) bitnami@britecore-vm:/home/muiruri_samuel/apps/django$ cd .. (djangoenv) bitnami@britecore-vm:/home/muiruri_samuel/apps$ deactivate bitnami@britecore-vm:/home/muiruri_samuel/apps$ . /opt/bitnami/scripts/setenv.sh bitnami@britecore-vm:/home/muiruri_samuel/apps$ python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook ImportError: No module named site # clear __builtin__._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.exitfunc # clear sys.exc_type # clear sys.exc_value # clear sys.exc_traceback # clear sys.last_type # clear sys.last_value # clear sys.last_traceback # clear sys.path_hooks # clear sys.path_importer_cache # clear sys.meta_path # clear sys.flags # clear sys.float_info # restore sys.stdin # restore sys.stdout # restore sys.stderr # cleanup __main__ # cleanup[1] zipimport # cleanup[1] signal # cleanup[1] exceptions # cleanup[1] _warnings # cleanup sys # cleanup __builtin__ # cleanup ints: 5 unfreed ints # cleanup floats bitnami@britecore-vm:/home/muiruri_samuel/apps$ python ImportError: No module named site I tried a snippet I saw on bitnami community on starting the env but it didn't work. I need to pip install a new package to where bitnami has it's packages so it can use it. I'm ok with just running … -
Django URL give me space between root and included urls
So I create an url in root/project/urls.py with this lines from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('accounts.urls')) ] while in my root/app/urls.py from django.urls import path from .views import UserView, AuthenticationView urlpatterns = [ path('register/', UserView.as_view()), path('auth/', AuthenticationView.as_view()), ] So it is expected to give me http://localhost:8000/users/register and http://localhost:8000/users/auth urls. Meanwhile my request doesn't behave as expected. apparently it returns me a space between the root path and include path. I check my root/project/settings.py file I don't find any weird settings. Does anybody know what is going on? -
Django 2.0 DateTimeField add by admin failure
This is pretty specific: I have a dead simple model. from django.db import models class Update(models.Model): update = models.DateTimeField() When I try to add an update in the admin panel, it foobars the whole thing, and gives me an error immediately saying: 'datetime.date' object has no attribute 'tzinfo' Any ideas? this has to be a bug no? Django 2.0.1, Python 3.5.4. -
Check if a form exists or is rendered in Template. Django
I have a situation where I display a Form sometimes and sometimes I don't display it. Actually, there are multiple forms using the same Submit button. What do I do to take care of the situation when a particular form is not shown in the template. The template code {% extends BASE_TEMPLATE %} {% load crispy_forms_tags %} {% block title %}<h2>New Thread</h2>{% endblock %} {% block content %} <div class="col-md-6"> <form method="post" accept-charset="utf-8">{% csrf_token %} {{ threadForm|crispy }} {{ postForm|crispy }} {% if SHOW_WIKI %} {{ wikiFrom|crispy }} {% endif %} <input type="submit" class="btn btn-primary btn-sm" value="Submit"/> </form> </div> {% endblock %} This is the view code @login_required def createThread(request, topic_title=None): if topic_title: try: if request.method == 'POST': topic = Topic.getTopic(topic_title) threadForm = ThreadSUForm(request.POST, prefix='thread') postForm = PostForm(request.POST, prefix='post') show_wiki = getattr(settings, "REFORUMIT_ALLOW_WIKI_FOR_THREADS", False) and topic.is_wiki_allowed wikiForm = WikiCreateForm(request.POST, prefix='wiki') if threadForm.is_valid() and postForm.is_valid() and wikiForm.is_valid(): thread = threadForm.save(commit=False) post = postForm.save(commit=False) wiki = wikiForm.save(commit=False) thread.op = post thread.wiki_revision = None post.setMeta(request) wiki.setMeta(request) if is_authenticated(request): post.created_by = request.user wiki.author = request.user thread.save() wiki.wiki_for = thread wiki.save() post.save() thread.wiki_revision = wiki thread.save() return HttpResponseRedirect(thread.get_absolute_url) else: topic = Topic.getTopic(topic_title) threadForm = ThreadSUForm(prefix='thread', initial={"topic": topic}) postForm = PostForm(prefix='post') wikiForm = WikiCreateForm(prefix='wiki') show_wiki = … -
Django celery with twilio SMS
I have my twilio client object inside tools.py and celery tasks inside tasks.py. I have to import the twilio connection object inside celery tasks. tools.py from django.conf import settings from twilio.rest import Client client = Client(settings.TWILIO_SID, settings.TWILIO_TOKEN) tasks.py from .tools import client from config.celery import app @app.task def send_sms(): client.messages.create(...) return 0 If I import the client like this my celery tasks are not registered. celery -A config worker --loglevel=info but If I remove the client import the tasks are working fine. What could be the issue ? and how can I import the client object ? Thanks. -
Duplicate -tpl.c~ files when created a new project in Django
I created a new project with django-admin startproject basicform And then created a new application django-admin startapp basicapp But, when i started my server, python manage.py runserver It made duplicated files, like this https://drive.google.com/open?id=1MTvpHf7pACsp9o_b129g5wPsKqwbbZDp Is this an ERROR? Should i delete the files? I am working on django-1.11 and Python 3.6.4 :: Anaconda, Inc. Also, when i tried running the server, it worked fine. python manage.py runserver https://drive.google.com/open?id=1arjf3U8Mm8ggwLTbSk5Gc9bd_FDl5lJj