Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app deploy to Heroku, Application Error on Static files
I am struggling to get my Django 1.10 app deployed to Heroku. Just as a preface, I am using Pycharm and had to rename my project at one point, but it refactored and changed the name in all places so I'm hoping that's not related to the issue. When I push this site to Heroku, I get an application error. Error messages In the Heroku app error log, I see: 2017-01-13T22:04:48.911324+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=secret-anchorage-68558.herokuapp.com request_id=71351a21-2264-4ca7-ad0a-1ae110d72ca7 fwd="162.247.89.174" dyno= connect= service= status=503 bytes= 2017-01-13T22:04:49.334411+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=secret-anchorage-68558.herokuapp.com request_id=bf22a256-8780-49ed-8820-c8112833121c fwd="162.247.89.174" dyno= connect= service= status=503 bytes= It once worked locally on my computer, but now when I try to run the app I get: python3 manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f278bc6ea60> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 116, in create mod = … -
upload data via excel sheet using django-excel
I didn't find anything on the web regarding my issue. So I hope that somebody can help me. I building a website using Django and I would like to create a functionality in which an user via an excel sheet can upload information and populate the database. So I install the django-excel package and follow the example: settings.py: FILE_UPLOAD_HANDLERS = ("django_excel.ExcelMemoryFileUploadHandler", "django_excel.TemporaryExcelFileUploadHandler") urls.py: url(r'^import_sheet/', views.import_sheet, name="import_sheet"), views.py: class UploadFileForm(forms.Form): file = forms.FileField() def upload(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): filehandle = request.FILES['file'] return excel._make_response(filehandle.get_sheet(),"xslx",file_name="download") else: form = UploadFileForm() return render(request,'upload_form.html',{ 'form': form, 'title': 'Excel file upload', 'header': 'Please choose a valid excel file' }) def import_sheet(request): if request.FILES['file'].save_to_database( model= quote_input, mapdict= ["value_date", "value", "type", 'name']) return HttpResponse("OK") else: return HttpResponseBadRequest() else: form = UploadFileForm() return render( request, 'upload_form.html', {'form': form}) models.py: class quote_output(models.Model): value_date = models.DateField() value = models.FloatField() type = models.TextField(max_length=254) name = models.TextField(max_length=254) start_date = models.DateField() end_date = models.DateField() operational_date = models.DateField(auto_now=True) # Link fund = models.ForeignKey(Fund) stress_factor = models.ForeignKey(Stress_Factors) factor = models.ForeignKey(Factors) benchmark = models.ForeignKey(Benchmark) When I try this code by uploading a basic excel sheet: I got an OK (HttpResponse) but when I looked at the database, I have uploaded nothing. … -
Python Web & Desktop App
I want to make a little software for myself. I want to have both web and desktop apps that do the same thing, and also a mobile app later on. I have knowledge of web development languages (PHP, JavaScript etc.) and some of python. I am little confused here. I want to use one solution for all. That I don't write separate code for every app. I have studied electron & kivy. I found kivy and python more interested. Can I build a web app with django or any other python framework and link it with kivy interface for desktop and mobile app? -
CSRF simulation test for django app
I would like simulate Cross Site Request Forgery query. My query has to try change number of votes for choice. Add +1 to "choice.votes" pole in database. There is a form to vote with radiobutons for choices and submit button to call function "vote". # I've followed django tutorial # https://docs.djangoproject.com/en/1.10/intro/tutorial05/ # Some details about my model: >>> q = Question.objects.get(pk=1) >>> q <Question: spam or egg?> >>> my_choice = q.choice_set.get(pk=1) >>> my_choice <Choice: spam> >>> my_choice.votes 0 I can simulate 'attack' by hand sending post with keyword {'choice': my_choice.id} using postman application but I need write a django application test. So far in my test I used client like this: class ChoiceVoteTests(TestCase): def test_vote_on_non_existing_question(self): non_existing_pk = 2 q = create_question("q_text", days=-10) c = create_choice(q, "c_text", votes=0) url = reverse('polls:vote', args=(non_existing_pk,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) but using self.client.post(url, data={'choice': my_choice.id}) make simulation of a real user that clicks on my submit button that I don't want to test. EDIT: url = reverse('polls:vote', args=(past_q.pk,)) + '?choice=' + str(past_c.id) response = self.client.post(url) also doesn't work. How to just send raw post polls/1/vote?choice=1 without using client? -
Django how to cache only specific urls
I'm following: https://docs.djangoproject.com/en/1.10/topics/cache/ to set up caching and I have it set up like so: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/tmp/django_cache', 'TIMEOUT': 60, 'OPTIONS': { 'MAX_ENTRIES': 1000 } } } But one small problem, I only really want to cache a couple of urls, but right now I'm going through every view and giving them a 1 second long cache decorator except for the ones I want to cache for longer time. Is it possible to "disable cache" by default and cache only a couple of urls? -
Django UpdateView does not update my model
I am trying to get my model updated using UpdateView, but when i hit save button i get redirected to the "success_url" and my model is not updated. How should i solve this? Here is the code: model: class Category(models.Model): name = models.CharField(max_length=100, db_index=True, unique=True) slug = models.SlugField(max_length=100, db_index=True, unique=True) user = models.ForeignKey(User, related_name='categories') view: class CategoryUpdate(UpdateView): model = Category fields = ['name', 'slug', 'user'] template_name = 'category/update.html' success_url = reverse_lazy('wallet:category_list') @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(CategoryUpdate, self).dispatch(*args, **kwargs) url: url(r'^category/update/(?P<pk>\d+)/$', views.CategoryUpdate.as_view(), name='category_update'), template: {% block content %} <div> <p><h1>Edit your category: {{ category.name }}</h1></p> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Update" /> </form> </div> {% endblock %} I pass the "pk" using: "<a href="{% url 'wallet:category_update' pk=category.id %}">Edit this category</a>" -
Is there a way to access custom template tags and filters in all apps of a Django project?
I have a dynamic html element that will appear on many pages in multiple apps. I'd like to resuse my custom templatetag / filter / inclusion tag code, say by putting it all in one app called utils. But when I try to load one such tag I am continually told that 'xyz' is not a registered tag library. Must be one of:... Please help! -
TinyMCE Django Framework
I am using the TinyMCE editor for the admin part of my website. The editor seems like it is installed correctly but after saving a post and displaying it on the main page it shows the raw html instead of rendering it. More specifically it shows Link If it helps I used HTMLField in the model -
Django Form wizard- Data gets lost after submit on step 1
I am using CookieWizard and formsets to create a form. In step 0 i Take user input and based on that get data which is then populated in formset on step 1. Till this point code is working fine. However when I submit on step 1, all data is lost. I check cleaned_data on form, it is None. forms.py class MappedReleaseTitleFormSet(BaseFormSet): def total_form_count(self): return self.min_num def initial_form_count(self): return self.min_num @property def management_form(self): initial = { TOTAL_FORM_COUNT: self.min_num, INITIAL_FORM_COUNT: self.min_num, MIN_NUM_FORM_COUNT: self.min_num, MAX_NUM_FORM_COUNT: self.max_num } form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial=initial) form.cleaned_data = initial return form class MappedReleaseTitleForm(forms.Form): title = forms.CharField( widget = forms.TextInput(attrs={'size':50}), ) title.label = "Title" def clean(self): print "Inside Clean" for err in self.non_field_errors(): print "Inside clean method, non Field errors {}".format(err) if any(self.errors): print "Inside clean method, errors {}".format(self.errors) cleaned_data = super(MappedReleaseTitleForm, self).clean() studio = self.cleaned_data.get('title') **# 1. Printed cleaned_data as well. it is also None # 2. This is non null when coming from step 0 to step 1. # 3. This is none when I hit submit on the form** print "value of cleaned_data is {}".format(self.cleaned_data) return self.cleaned_data def is_valid(self): return not bool(self.errors) def as_inline(self): return self._html_output( normal_row='<span%(html_class_attr)s>%(label)s %(field)s%(help_text)s</span>&nbsp;', error_row='%s', row_ender='</span>&nbsp;', help_text_html=' <span class="helptext">%s</span>', errors_on_separate_row=True) def … -
How can I get the url working from js html builder in Django?
I am currently building a web app using Django. I've build a calendar using JS and I am building HTML basically from the Js File. I am trying to include hrefs in each calendar day. For example : {% url 'calendarDay' day=28 month=12 year=2016 %} is what should have for 28/12/2016 date. If I try to go to this url from anywhere else in my templates it works. For some reason it is not working when I pass the html from js. This is what I have in my urls: url(r'^calendar/$', views.calendar, name='calendar'), url(r'^calendar/(?P<day>\w+)/(?P<month>\w+)/(?P<year>\w+)/$',views.calendar, name = 'calendarDay'), This is my js builder function (the part that builds the previous month's days): if (FirstDay.getDay()==0){ for (var i=LastMonthDays-5; i <= LastMonthDays; i++) { href="<a href=\"{% url 'calendarDay' day="+i+" month="+(pastMonth.getMonth()+1)+" year="+pastMonth.getFullYear()+" %}\">" html +=href+ "<li>"+(i)+"</li></a>"; } } This is how the html file looks like when I inspect the page: <a href="{% url 'calendarDay' day=28 month=12 year=2016 %}"><li>28</li></a> For some reason the urls that it gets is: http://127.0.0.1:8000/calendar/%7B%%20url%20'calendarDay'%20day=28%20month=12%20year=2016%20%%7D And ofcourse I get the following error: The current URL, calendar/{% url 'calendarDay' day=28 month=12 year=2016 %}, didn't match any of these. What might be the issue here? -
Using globals() to augment django settings
It seems to be relatively normal in the Django world to import a local environment settings override file at the end of settings.py, something like: from settings_local.py import * This has a couple of issues, most notably for me being that you cannot inspect or modify base settings, only override them - which leads to some painful duplication and headaches over time. Instead, is there anything wrong with importing an init function from a local file and injecting the output of globals() to allow that local file to read and modify the settings a bit more intelligently? settings.py: from settings_local.py import init init( globals() ) settings_local.py: def init( config ): config['INSTALLED_APPS'].append( 'some.app' ) This seems to address a number of the concerns related to using import *, but I'd like to know if this is a bad idea for a reason I am not yet aware of. -
Loading initial data from csv with migrations in Django 1.10
This is what I have after multiple tries. My ASCII csv data is located at /.../myproject/myapp/committees.csv. It is delimited by '|'. There are no quotes around each string, but some fields have quotes (double and single) in them. It has a header. My migrations files are at the default /.../myproject/myapp/migrations/ directory. I've deleted all previous tries at migration files to start over, so it's just got the __init__.py/c files. My database is the default django sqlite3 one at /.../myproject/db.sqlite3. My Committees model is the exact fields from the csv header, all models.CharField(max_length = 100). It is at the default /.../myproject/myapp/models.py. I named the dbtable 'Committees'. At this point, I can run sqlite3 commandline and see an empty 'Committees' table in my 'main' database. The schema is correct (a bunch of VARCHAR(100) fields). First, I run this in /.../myproject/: python manage.py makemigrations --empty myapp --name load_intial_data I open up /.../myproject/myapp/migrations/0001_load_intial_data.py and edit it: # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-13 18:00 from __future__ import unicode_literals from django.db import migrations import os # where is the file directory = os.path.abspath(os.path.join(os.path.dirname(__file__), '../')) fp = os.path.join(directory, 'commmittees.csv') # an earlier try with raw SQL cmd = "BULK INSERT Committees … -
Django Admin - login
I'm building a Django Web App with Django Suit for the administration interface. Already got have Python 2.7, Django 1.10, and MySQL communicating in harmony and started a project: python -m django-admin startproject webapp So, those were the steps made in the Windows PowerShell after that: 1. Start our virtual env and run the server: PS C:\WINDOWS\system32> cd C:\PythonProjects PS C:\PythonProjects> virtualenvs\rrh\Scripts\activate (rrh) PS C:\PythonProjects> cd rrh/webapp 2. Setup Django Suit (rrh) PS C:\PythonProjects\rrh\webapp> pip install django-suit==0.2.23 Then, go to settings.py file and add the 'suit' application: (this is how is looking on mine) INSTALLED_APPS = [ 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Also, make sure you have django.template.context_processors.request,in your TEMPLATES OPTIONS context_processors (in settings.py): This is required to handle left side menu. (this is how is looking on mine) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', # Make sure you have this line 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Then, (rrh) PS C:\PythonProjects\rrh\webapp> ./manage.py collectstatic (rrh) PS C:\PythonProjects\rrh\webapp> pip install git+https://github.com/darklow/django-suit.git Django Suit (https://github.com/darklow/django-suit) The folder structure is the following: The database as the following aspect (with one row in auth_user): This is the screen when run the … -
Django asynchronously process data and keep in cache
I am making a mobile backed in django. It's about stock market data analysis and processing. My requirement is to fetch stock market data(I have subscribed to an external service to get the data), do some processing, generate some results and store it into a cache. I decide upon caching here because the processed results would be request by the android application, so it should be fast enough. Now the tricky part is, it should keep happening in the background, fetch-process-store cycle. I've done my research and found out that I can use Celery to keep triggering the task to perform, then use memcached or Redis to store them into a cache and return data from the cache when the android app requests my view. I've previously tried to use celery and redis(windows 10 x64) but with no luck, I will however dig more into it and make it work, but I'd like to know if there's a better approach, or a package that can directly address my problem. Also, I'd like to know if I should just make a thread which would start to run when I first request a view that initiates the thread, and the thread, then … -
NoReverseMatch error while trying to add the username to the url after login
When a user clicks 'login' I want them to be logged in and redirected to i.e., www.exampledomain.com/accounts/usernameGoesHere/ Here are my top level urls: from django.conf.urls import url, include from django.contrib import admin # Namespace URLs app_name = "pto_request" urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls')), ] and here are the urls for accounts: from django.conf.urls import url from django.contrib.auth.decorators import login_required from accounts.views import (login_view, register_view, logout_view) from . import views app_name = 'accounts' urlpatterns = [ # root url will look like www.website.com/accounts/ url(r'^login/$', login_view, name='login'), url(r'^logout/$', logout_view, name='logout'), url(r'^register/$', register_view, name='register'), url(r'^(?P<username>[0-9a-zA-Z._]+)/$', login_required(views.IndexView.as_view()), name = 'index'), ] This is my login view: def login_view(request): title = "Login" user_form = UserLoginForm(request.POST or None) if user_form.is_valid(): username = user_form.cleaned_data.get('username') password = user_form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) return redirect(reverse('accounts:index', args=[username])) return render(request, 'form.html', {'user_form':user_form, 'title':title}) and finally this is the traceback log of the error I am receiving: Environment: Request Method: GET Request URL: http://localhost:8000/accounts/FlashBanistan/ Django Version: 1.10.5 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'datetimewidget', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware'] Template error: In template C:\django projects\PTO\accounts\templates\accounts\index.html, error at line 0 Reverse for 'index' with arguments '()' and … -
CSRF token failing on second post Django Rest Framework
I'm having an issue where I can log in successfully but any subsequent requests show as "detail":"CSRF Failed: CSRF token missing or incorrect." I have no clue what I'm doing wrong, I've looked over Requests docs, DRF docs, turned off authentication to validate the url and searched old SO posts on the subject. Here is a basic function with attached basic info def will_fail(): CURRENT_URL = 'http://127.0.0.1:8000/{}' session = requests.Session() response = session.get(CURRENT_URL.format('api-auth/login/')) csrftoken = response.cookies['csrftoken'] first_response = session.post(CURRENT_URL.format('api-auth/login/'), data={'username': 'itsme', 'password': 'password'}, headers={'X-CSRFToken': csrftoken}) response = session.post(CURRENT_URL.format('api-v1/languages/'), params={'name': "French", "audio_base": "adpifajsdpfijsdp"}, headers={'X-CSRFToken': csrftoken}) first_response (login): URL - 'http://127.0.0.1:8000/api-v1/' Text - {"languages":"http://127.0.0.1:8000/api-v1/languages/","phrases":"http://127.0.0.1:8000/api-v1/phrases/","stats":"http://127.0.0.1:8000/api-v1/stats/"} Status - <Response [200]> response (add language): URL - 'http://127.0.0.1:8000/api-v1/languages/?audio_base=adpifajsdpfijsdp&name=French' Text - {"detail":"CSRF Failed: CSRF token missing or incorrect."} Status - <Response [403]> The settings are very basic since I'd just started on this: THIRD_PARTY_APP = [ 'rest_framework.authtoken', 'rest_framework', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } Here is the URL info which is also pretty generic from training.views import LanguageViewSet, PhraseViewSet, PhraseStatsViewSet router = DefaultRouter() router.register(r'languages', LanguageViewSet) router.register(r'phrases', PhraseViewSet) router.register(r'stats', PhraseStatsViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-v1/', include(router.urls, namespace='api')) ] I'm using ModelSerializers and ModelViewSets, I didn't override any … -
Django attempts to connect to wrong socket
I am attempting to set up django to connect to google cloud sql following the instructions found here: Connecting MySQL Client Using the Cloud SQL Proxy. After I start the proxy with: ./cloud_sql_proxy -dir=/cloudsql -instances=my-instance -credential_file=/app/keyfile.json > /logs/proxy.txt & Django fails to connect to the db, and gives this error when you try to load a page: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") I'm new to unix sockets so I could be interpreting this incorrectly, but it appears to me that django is trying to connect to a socket at /var/run/mysqld/mysqld.sock. My database configuration in Django is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOSTS': '/cloudsql/my-instance-description', 'NAME': 'main', 'USER': '****', 'PASSWORD': '****', } } Am I interpreting this correctly? If so, what do I need to change so that django tries to connect to the socket at /cloudsql/my-instance-description rather than the default? -
Django template header content goes into body
I created a text area field in Django called social_media_header. This field was created so one of us at my work could add social media meta information like Facebook Open Graphs, etc. by copy and pasting what we need into the text area. When I insert this content into the head of my template, I use the 'safe', and 'striptags' filter. This is because we are using TinyMCE, and I needed to get rid of any html tags, just keeping the meta tags. The filters work fine, and I am just getting the meta tags, but for some reason, it is not staying in the head of the template. It is being moved to the body. The odd thing is if I put that content in a script tag, just for testing, it shows up. It's as if the Django template engine doesn't like that meta tag, and decides to put it in the body tag instead. I also run into another issue where when it does show up in the script tag, the closing and opening html carrots ' <, >' are turned into html entities instead ' &lt; , &gt; '. Is there any way that this can … -
Python - get midnight tomorrow night in timezone format
Im trying to get a list of all events occuring tomorrow from a django queryset. i assumed i needed tomorrow at midnight until tomorrow at 11:59pm. i think my tomorrow_end variable will be correct if tomorrow_start was set to 00:00:00 currently it gets the exact time now. Can someone please tell me how to alter the time on the below to 00:00:00? tomorrow_start = timezone.now() + timedelta(1) tomorrow_end = tomorrow_start + timedelta(hours=11,minutes=59) maintenance = CircuitMaintenance.objects.filter(start_time__gte=tomorrow_start, end_time__lte=tomorrow_end) -
Allow user's change from the frontend reflect on the backend(Django Admin)
I'm trying to let my users update from the front-end allowing it to reflect at the django admin particularly updating of profile image. The change of user.first_name and user.last_name works fine except from the image which also doesn't reflect at the back end. I think i'm missing something plus when the fields for firstname and lastname are empty it post as null I think I'd use an exception for that but i'm more concerned with the profile image. here is my code #views.py def edit_user_profile(request, username): user = request.user form = EditProfileForm(request.POST or None, request.FILES, initial={'first_name': user.first_name, 'last_name': user.last_name}) if request.method == 'POST': if form.is_valid(): # user.photo = UserExtended(photo=request.FILES['photo'] or None, ) photo = UserExtended.objects.get(user=user) user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] # username = request.POST['username'] photo.save() user.save() context = { 'form': form, } return render(request, 'accounts/profile_updated.html', context) context = { 'form': form, 'username': username, } return render(request, 'accounts/edit_profile.html', context) #model.py @python_2_unicode_compatible # only if you need to support Python 2 class UserExtended(models.Model): user = models.OneToOneField(User, related_name='user') photo = models.ImageField(upload_to='media/user_media/users', verbose_name='Profile Picture', default='/media/user_media/avatars/avatar.png', blank=True) address = models.CharField(max_length=255) phoneNumber = models.CharField(max_length=11) class Meta: verbose_name_plural = _("user") def __str__(self): return self.user.username def image_tag(self): if self.photo: return mark_safe('<img src="/media/%s" width="150" height="150" />' % self.photo) … -
Django 1.10 - ManyToManyField not working
Django documentation as well as other tutorials didnt bring me much closer to the goal. I want to create the relationship between a person and the news article it got mentioned in. person/models.py class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=40) news_mentioned = models.ManyToManyField(News, blank=True) news/models.py class News(models.Model): title = models.CharField(max_length=250) abstract = models.TextField(max_length=1000, null=True, blank=True) description = models.TextField(max_length=5000, null=True, blank=True) url = models.URLField(unique=True) ne_person = models.CharField(max_length=250, blank=True, null=True) Extract from the celery task: article = News.objects.get(pk=pk) person = Person.objects.update_or_create(first_name=fname, last_name=lname) person.save() mentioned = Person.objects.get(person.id).news_mentioned(article.id) What am I making wrong here and yeah, Django documentation freaks me out already. Thanks, Philipp -
Django Crispy, Replace class instead to add
why django crispy append the class instead to replace For instance: self.helper.add_input(Submit('Submit', _SAVELATER,css_class="btn btn-lg btn-default pull-right")) Result would be: <input type="submit" name="Submit" value="Save and Submit Later" class="btn btn-primary btn btn-lg btn-default pull-right" id="submit-id-submit"> instead <input type="submit" name="Submit" value="Save and Submit Later" class="btn btn-lg btn-default pull-right" id="submit-id-submit"> -
Broadcast messages in Celery 4.x
I'm using django 1.8 + Celery 4.0.1 + Kombu 4.0.1 + Redis as broker from kombu.common import Broadcast CELERY_QUEUE_BROADCAST = 'broadcast' CELERY_QUEUES = (Broadcast(queue=CELERY_QUEUE_BROADCAST), ) @task(ignore_result=True, queue=CELERY_QUEUE_BROADCAST) def broadcast_task(): print "task runned" and I started two workers celery -A proj worker -Q broadcast But if I send task broadcast_task.delay() The task is performed on only one of the workers Can anybody explain me how to properly configure celery broadcast worker ? -
Django/python: How to pass the form.cleaned_data value to HttpResponseRedirect as an argument?
I wanted to pass an argument (form field value) in an URL as below. But when I do this, it raises an error not enough arguments for format string I would appreciate help me in solve this or suggest me an alternate approach for passing a form_cleaned value to HttpResponseRedirect. def phone(request): form = PhoneForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) Phone = form.cleaned_data.get('Phone') instance.save() form.save() return HttpResponseRedirect('http://send_sms.com/api_key=api&to=%s&message=Welcome%20to%messaging' %Phone) context = { "form": form, } return render(request, "phone.html", context) -
Trouble with creating new application on Django
I'm very new to programming and Django. I started following the Tango with Django tutorial and I'm at the part where I have to create a new app called "rango" by typing "rango" in the "settings.py" under the "INSTALLED_APPS" tuple. I follow the instructions and try to the run the server on the command prompt. I get the follow error C:\Python34\Scripts\tango_with_django_project> python manage.py startapp rango Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\apps\config.py", line 118, in create cls = getattr(mod, cls_name) AttributeError: 'module' object has no attribute 'staticfilesrango' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Python34\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python34\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python34\lib\site-packages\django\apps\config.py", line 123, in create import_module(entry) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked ImportError: No module named 'django.contrib.staticfilesrango' I've already tried this on visual studios and pycharm, tried it on python3.5 and 3.4, uninstalled and reinstalled python, …