Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dealing with multiple databases in Django with and without timezones
I'm in the situation where I use django (2.0.7) to deal with multiples databases: database_A: without timezone; database_B: with timezone 'Europe/Paris'; settings.py USE_TZ = True TIME_ZONE = 'Europe/Paris' DATABASES = { 'database_A': { 'NAME': ... 'PASSWORD': ... etc. 'TIME_ZONE': None, # still raise RuntimeWarning; received a naive datetime while time zone support is active. }, 'database_B': { 'NAME': ..., etc. } on models of database A class Something(models.Model): date_creation = models.DateTimeField() def save(self, *args, **kwargs): if self._state.adding is True: self.date_creation = timezone.datetime.now() # naive print("BEFORE SAVE") print(self.date_creation) super(Something, self).save(*args, **kwargs) print("AFTER SAVE") print(self.date_creation) print("AFTER REFRESH") self.refresh_from_db() print(self.date_creation) I get the following result BEFORE SAVE 2019-11-04 11:44:35.233876 AFTER SAVE 2019-11-04 11:44:35.233929 AFTER REFRESH 2019-11-04 10:44:35.23392 # 10:44:35 , what's wrong ô_O ? I have the same 1 hour difference between Europe/Paris and UTC. import pytz from datetime import datetime datetime.now(tz=pytz.timezone('Europe/Paris')), timezone.now() (datetime.datetime(2019, 11, 4, 12, 10, 55, 320028, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>), datetime.datetime(2019, 11, 4, 11, 10, 55, 320077, tzinfo=<UTC>)) So, I think PostgreSQL is using UTC to save my naive datetime considered as timezone aware datetime ? In database I have the following time \d something_table date_creation | timestamp without time zone | non NULL Par defaut, now() SELECT NOW(); … -
Is there any simplest way to run number of python request asynchronously?
There is an API localhost:8000/api/postdatetime/, which is responsible for changing the online status of the driver. Every time a driver hits the API and if the response sent back then the driver status will be online otherwise the driver status will be offline. Drivers need to give the response within every 10 seconds. If there is no response from the driver then he/she will be marked as offline automatically. Currently what I am doing is getting all the logged in drivers and hitting the above-mentioned API one driver at a time. For the simulation purpose, I populated thousands of drivers. To maintain the online-offline of thousands of drivers using my approach will leave almost many drivers offline. The code for my approach is as described below: online-offline.py import requests import random import math from rest_framework.authtoken.models import Token from ** import get_logged_in_driver_ids from ** import Driver def post_date_time(): url = 'localhost:8000/api/postdatetime/' while True: # getting all logged in driver ids logged_in_driver_ids = get_logged_in_driver_ids() # filtering the driver who are logged in and storing their user id in the driver_query variable driver_query = Driver.objects.only('id', 'user_id').filter(id__in=logged_in_driver_ids).values('user_id') # storing the user id of driver in list driver_user_ids = [driver['user_id'] for driver in driver_query] # … -
Azure Functions Django ModuleNotFoundError
I have been trying to run Django on Azure Function as mentioned in the tutorial below Running serverless Django apps with Functions I am trying to use the following module as mentioned https://github.com/carltongibson/azure-functions-wsgi-adapter The library above does not look maintained, still, the approach is simple enough and should work. I am able to get the code in the tutorial running, but my code is not working. The only difference I see is in the directory stucture(my code and Django by default has one more level in the directory structure). My directory structure is: Running the above gives me the following error on Azure: Exception: ModuleNotFoundError: No module named 'notifications' Stack: File "/azure-functions-host/workers/python/3.6/LINUX/X64/azure_functions_worker/dispatcher.py", line 242, in _handle__function_load_request func_request.metadata.entry_point) File "/azure-functions-host/workers/python/3.6/LINUX/X64/azure_functions_worker/loader.py", line 66, in load_function mod = importlib.import_module(fullmodname) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/site/wwwroot/serverless/__init__.py", line 14, in <module> from notifications.notifications.wsgi import application By default Django project parent directory does not have an __init__.py, I have added it so that import works. Not able to figure out the missing piece here! -
How to use class based views with more than one model?
I am using class based view with a created model, but I am not able to insert another model. models.py: class Test(models.Model): name = models.CharField(max_length=255, null=False, data = models.DateField(null=False, default=date.today) class Test2(models.Model): teste = models.ForeignKey(Test, on_delete=models.CASCADE), data = models.DateField(null=False, default=date.today) views.py without the "Test2" model: class IndexTemplateView(TemplateView): template_name = "index.html" class TestCreateView(CreateView): template_name = "cadastro.html" model = Test form_class = InserePropriedadeForm success_url = reverse_lazy("test:list_test") class TestListView(ListView): template_name = "list.html" model = Test context_object_name = "tests" class TestDetailView(DetailView): template_name = "detail.html" model = Test fields = '__all__' context_object_name = 'test' ... How can I add the model "Test2" to this view? -
Django + JQuery - Iterate over table rows updating each row with json data
I have table rows that look like this {% for item in items %} <tr id="labels" data-index="{{ forloop.counter }}"> </tr> {% endfor %} I have this json data: "labels": [ "A", "B", "C ", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ], Im trying to iterate over the table rows and the json data at the same time, so that I can assign each table row its label. jQuery.each(labels, function() { newlabel = this; document.querySelectorAll('#labels').forEach(function (element, index) { element.innerHTML = newlabel; }); })}, But with this all the rows are populated with the letter Z, instead of being A-Z in alphabetical order. Thank you for any help -
Accessing ForeignKey field value inside template
I have two models Fleet and Ship, Ships are ForeignKey fields of Fleets: class Fleet(models.Model): fleet_ship_n_01 = models.ForeignKey(Ship, on_delete=models.CASCADE, null=True, related_name='fleet_ship_n_01', blank=True) fleet_ship_n_02 = models.ForeignKey(Ship, on_delete=models.CASCADE, null=True, related_name='fleet_ship_n_02', blank=True) fleet_ship_n_03 = models.ForeignKey(Ship, on_delete=models.CASCADE, null=True, related_name='fleet_ship_n_03', blank=True) Ships itself also have many fields like: class Ship(models.Model): ship_class = models.CharField(default='NoClass', max_length=200, help_text="Ship class") ship_tech_level = models.CharField(default=5, max_length=100, choices=tech_level) ship_mass = models.PositiveIntegerField(default=0, help_text="Ship mass") I have an update view in which i am adding ships to Fleet: class UVFleetDetails(UpdateView): template_name = 'fading_thrust/fleet_details_form.html' model = Fleet form = FleetForm() total_ship_mass = 0 fields = ('fleet_ship_n_01', 'fleet_ship_n_02', 'fleet_ship_n_03', 'fleet_ship_n_04', 'fleet_ship_n_05', 'fleet_ship_n_06', 'fleet_ship_n_07', 'fleet_ship_n_08', 'fleet_ship_n_09', 'fleet_ship_n_10', ) def form_valid(self, form): fleet = form.save() fleet_id = self.kwargs['pk'] fleet.fleet_id = fleet_id fleet.save() return redirect('fleet_details', pk=fleet_id) here is its form: class FleetForm(ModelForm): fleet_ship_n_1 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_2 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_3 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_4 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_5 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_6 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_7 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_8 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_9 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_10 = forms.ModelChoiceField(Ship.objects.all(), required=False) class Meta: model = Fleet fields = ('fleet_ship_n_01', 'fleet_ship_n_02', 'fleet_ship_n_03', 'fleet_ship_n_04', 'fleet_ship_n_05', 'fleet_ship_n_06', 'fleet_ship_n_07', 'fleet_ship_n_08', 'fleet_ship_n_09', 'fleet_ship_n_10',) Now when adding ships to a Fleet i want to display also important details about those ships. Like ship_class, ship_tech_level, … -
Django-based Quiz app: Answers and Answer Verification
I am creating a Django-based quiz application(MCQ type) in which i have reached the stage where my questions with options(answers) with checkboxes are being displayed but i required help on how to proceed forward from here.I needed help to take the input from the user after he/she selects the checkboxes and clicks on 'submit' button and to verify whether the answers are correct. Here is my html file/code- {% extends "app/basic_app_base.html" %} {% block body_block %} <h1>{{ question.question_text }}</h1> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <ol> {% for question in questions %} <form action="{% url 'app:detail' question.id %}" method="post"> {% csrf_token %} <h3>{{ question.question_text }}</h3> {% for choice in question.choice_set.all %} <input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }} </label> {% endfor %} <br> {% endfor %} </ol> <input type="submit" name="" value="Submit"> </form> </body> {% endblock %} I am looking for the code after this step.Please help. -
How to access the user details when i use the original user model as a foreign key in Django
I have a book model as below : from django.db import models from django.db.models.signals import pre_save from django.utils.text import slugify from django.conf import settings class Book(models.Model): added_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_add', on_delete=models.CASCADE), last_edited_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_edit', on_delete=models.CASCADE) title = models.CharField(max_length=120) description = models.TextField(null=True, blank=True) slug = models.SlugField() updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) @property def user_id(self): return self.added_by.id def __str__(self): return self.title def pre_save_book(sender, instance, *args, **kwargs): slug = slugify(instance.title) instance.slug = slug pre_save.connect(pre_save_book, sender=Book) Now in my admin.py file i am trying to do this : from django.contrib import admin from .models import Book from .forms import BookForm class BookAdmin(admin.ModelAdmin): fields = [ 'title', 'slug', 'added_by' ] read_only_fields = [ 'updated' 'timestamp', 'added_by', 'last_edited_by' ] admin.site.register(Book, BookAdmin) I am getting an error which says the added_by field is not recognized , but it should be right, since i have defined it as a foreign key on the original user model. So i tried to go to the console and try it out : (Django-concepts) ~/Desktop/Studies/Codes/Django-concepts/django_cls_views:$ python manage.py shell Python 3.7.3 (default, Mar 27 2019, 09:23:15) [Clang 10.0.1 (clang-1001.0.46.3)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from … -
Django Rest Framework: insert list using ModelViewSet
The online documentation is not very clear. The default POST method of ModelViewSet is supposed to allow you to insert a list of your models, but in reality it only allows single model insertion. For code example please refer to the one stated in the https://www.django-rest-framework.org/api-guide/viewsets/ class UserViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing user instances. """ serializer_class = UserSerializer queryset = User.objects.all() -
how to create a xar file for python script or django/flask application?
Is anyone tried creating XAR file for python scripts or django or flask application in CentOS? How stable is it for production usage? Most importantly, how to include python interpreter too in the xar self-executable? https://www.pydoc.io/pypi/xar-18.7.12/autoapi/commands/bdist_xar/index.html https://engineering.fb.com/data-infrastructure/xars-a-more-efficient-open-source-system-for-self-contained-executables/ -
elasticsearch: NotFoundError
Installed elasticsearch. I try to find the records, but when I try to iterate, I get the error elasticsearch.exceptions.NotFoundError: NotFoundError (404, 'index_not_found_exception', 'no such index', cars, index_or_alias) Although such a record is in the database. What could be the reason. I launch the project on port 8001. def search(request): json_data = json.loads(request.body) title = json_data['title'] if 'title' in json_data else '' note_text = json_data['note_text'] if 'note_text' in json_data else '' publication_type = json_data['publication_type'] if 'publication_type' in json_data else '' mesh_terms = json_data['mesh_terms'] if 'mesh_terms' in json_data else '' conditions = json_data['conditions'] if 'conditions' in json_data else '' comments = json_data['comments'] if 'comments' in json_data else '' more = json_data['more'] posts = ArticleDocument.search() if title and title != '': posts = posts.query("match", title=title.lower()) if note_text and note_text != '' : posts = posts.query("match", note_text=note_text.lower()) if comments and comments != '': posts = posts.query("match", comments=comments) if publication_type and publication_type != '': posts = posts.query("match", publication_type=publication_type.lower()) if mesh_terms and mesh_terms != '': posts = posts.query("match", mesh_terms=mesh_terms) if conditions and conditions !='': posts = posts.query("match", conditions=conditions) posts = posts.extra(from_=0, size=more) resdata = [] for hit in posts: resdata.append({"title":hit.title, "id":hit.index}) return JsonResponse({'code':1, 'data':resdata, 'msg':"Success"}) -
Push Notification React Native Expo with Django RestFramework
I am a newbie with notification using React Native Expo, and all Tutorials that I have searched so far is integrated with Firebase, But I am working on Django Rest Framework, I could not find any example, except on the Expo Documentation . I know all the mechanism, but I am struggling on the usage of Python Library : https://github.com/expo/expo-server-sdk-python If anyone has an example on how to use it, I'd be much appreciated. -
How to display some message if the user account is not active?
Here I am trying to display some messages if the username and password is correct but if the is_active field is false but it is not displaying the message with this code.It is displaying me the else part even if the username and password are correct of that inactive user.How can I do it ? views.py form = LoginForm() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] remember_me = form.cleaned_data['remember_me'] user = authenticate(request, username=username, password=password) if user and not user.is_active: messages.info(request,'Sorry your account is deactivated now.') return redirect('/login/') elif user and user.is_active: login(request, user) if not remember_me: request.session.set_expiry(0) else: request.session.set_expiry(settings.SESSION_COOKIE_AGE) else: messages.error(request, 'Invalid login credentials. Try Again.') return redirect('/login/') -
ID field is always returning empty
I have a very simple model of user with name email and password and I am assuming the default id field. I am using tastypie and djongo. Now when I write a resource I always get empty id field even though its there in mongo as well. 1- I set ENFORCE_SHEMA to False in settings.py. If I don't do that I always get error yield self._align_results(doc) File "/usr/local/lib/python3.6/dist-packages/djongo/sql2mongo/query.py", line 289, in _align_results raise MigrationError(selected.column) djongo.sql2mongo.MigrationError: id and now When I query I get such data {"email":"abc@abc.com", "name":"abc", "id":""} Tried setting id field manually and tried other ways but no benefit -
Regular expression to match phrases with plus sign
Was wondering what is the best way to match "clear 18+ from your history" from "clear 18+ from your history? blah blah blah" is? Using Python. I've tried this, keyword = "clear 18+ from your history" prepped_string = "clear 18+ from your history? blah blah blah" is_flagged = False if re.search(r'\b' + keyword + r'\b', prepped_string): is_flagged = True The above code only works with no special character. If there is a special character like the plus sign, it won't work. Thanks in advance. -
Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name
I am getting the above error when I try to access the landing page. What am I missing? Traceback NoReverseMatch at / Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name. Here is the base.html code <button> `<a href="{% url 'trucks:fleet' %}"> Fleet Admin </a> </button> and below is the app urls.py file from django.urls import path from .admin import fleet_admin_site app_name = 'trucks' urlpatterns = [ path('fleet/', fleet_admin_site.urls, name="fleet"), ] and the main urls.py file from django.contrib import admin from django.urls import path, include, reverse from django.views.generic import TemplateView urlpatterns = [ path('admin/', include('workers.urls')), path('admin/', include('trucks.urls')), path('', TemplateView.as_view(template_name='base.html')), ] -
How to combine two different Models in serializers module (Django)?
I want to create a Registration API, wherein, I aim to combine the User Model and Profile Model in order to create a new user by adding the username, email, password (User Model fields) and gender, salary, company, and address (Profile Model fields). I attempted to use the source from this link. However, I am not able to POST any data in. This is my code so far: views.py: class RegisterAPIView(APIView): def post(self, request, format=None): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response("Thank you for registering", status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py: from rest_framework import serializers from users.models import Profile from django.contrib.auth.models import User class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['gender', 'company', 'salary', 'address'] class RegisterBSerializer(serializers.ModelSerializer): #User Model serializer profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'password'] def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password', None) user = User.objects.create(**validated_data) if password is not None: user.set_password(password) user.save() Profile.objects.create(user = user, **profile_data) return user Can anyone hint me on where I am going off-track?. -
Django - Page not found (404) URLconf not updating
Following this tutorial https://docs.djangoproject.com/en/2.2/intro/tutorial01/ I get a 404 when trying to load /polls/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. mysite.urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls.urls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] polls.views from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") Directory structure Django |mysite |__pycache__.py |__init__.py |settings.py |urls.py |wsgi.py |polls |migrations |__init__.py |init.py |admin.py |apps.py |models.py |tests.py |urls.py |views.py |db.sqlite3 |manage.py I've tried rebooting my computer as well as the server -
Multiple django 'with' statements inside 'if' statement
I have a Django multiple 'with' statements inside 'if/elif' statement. The blocks of code inside if/elif are the same except for one variable 'slide1_line2'. I am wondering if there is a way to re-write code to avoid repetition. {% if country == 'England' or country == 'Wales'%} {% with graphic='map.png' %} {% with classes='color-1' %} {% with slide1_line1='Your constituency is '|add:name %} {% with slide1_line2='Heading1' %} {% with slide1_line3='text' %} {% with icon='keyboard_arrow_down' %} {% include 'slide_map.html' %} {% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %} {% elif country == 'Scotland' or country == 'Northern Ireland' %} {% with graphic='map.png' %} {% with classes='color-1' %} {% with slide1_line1='Your constituency is '|add:name %} {% with slide1_line2='Heading2' %} {% with slide1_line3='text' %} {% with icon='keyboard_arrow_down' %} {% include 'slide_map.html' %} {% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %} {% endif %} -
How do I create a Django project using Jupyter?
I have some python code that needs to interact with my HTML page. For that, I have to use Django Framework. As I am very new to this I don't how to do it. I have installed the Django on my system using the following command: pip install django After running this command, I got the below output: Collecting django Downloading https://files.pythonhosted.org/packages/b2/79/df0ffea7bf1e02c073c2633702c90f4384645c40a1dd09a308e02ef0c817/Django-2.2.6-py3-none-any.whl (7.5MB) Requirement already satisfied: pytz in c:\users\hisingh\appdata\local\continuum\anaconda3\lib\site-packages (from django) (2019.1) Collecting sqlparse (from django) Downloading https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl Installing collected packages: sqlparse, django Successfully installed django-2.2.6 sqlparse-0.3.0 Note: you may need to restart the kernel to use updated packages. Now I want to create my first django project. I am trying to do it through Jupyter notebook by running the below command: django-admin FirstProject OUTPUT: File "", line 1 django-admin FirstProject ^ SyntaxError: invalid syntax Can someone please guide me to do that? Any help will be appreciated. -
django API how to get parameter include special Characters
hello now i make django api for searching mysql DB but i will send parameter like this %20%20%20chinkyu5211 it cognize chinkyu5211 except special characters chinkyu5211 so if someone know that way to cognize %20%20%20chinkyu5211 all sentences plz teach me.. class SearchView(APIView): def get(self, request): data_list=[] #es = Elasticsearch() # 검색어 search_word = request.query_params.get('search') print(search_word) this is my views code and if i printed search_word i got the result chinkyu5211 as i said before i hope that the problem will be solved.. thanks you -
How do I filter data with two parameter from two different Django models
I want to create a JSON object which will Search the particular Projects from the model "EmpProject" by a specific emp_id Search whose project status is "Pending" from the model "Project" with the help of (1.) Search result I am using JSON Parser (no models or generic view) Models Below are my models I have not use many to many field instead I created a Intermediate Table if the solution is also possible by using manytomanyfield than also suggest class Employee(models.Model): employeeid = models.IntegerField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_no = models.CharField(max_length=10) date_of_birth = models.DateField() email = models.EmailField(unique=True) password = models.CharField(max_length=50) designation = models.CharField(max_length=50) dept_id = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) class Meta: ordering = ('id',) def __str__(self): return self.emp_name class Project(models.Model): projectname = models.CharField(max_length=50, unique=True,) project_status = models.CharField(max_length=50) description = models.TextField() start_date = models.DateField(auto_now_add=True) due_date = models.DateField() class Meta: ordering = ('id',) def __str__(self): return self.projectname class EmpProject(models.Model): emp_id = models.ForeignKey(Employee,on_delete=models.SET_NULL, null=True, blank=True) project_id = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True, blank=True) class Meta: unique_together = [['emp_id','project_id']] ordering = ('project_id',) def __str__(self): return self.emp_id Serializer class EmployeeSerializer(serializers.ModelSerializer): dept_id = serializers.SlugRelatedField(queryset=Department.objects.all(), slug_field='dept_name') class Meta: model = Employee fields = [ 'id', 'employeeid', 'first_name', 'last_name', 'phone_no', 'date_of_birth', 'email', 'password', 'designation', 'dept_id', ] class ProjectSerializer(serializers.ModelSerializer): … -
Unable to run celery task that depends on Django code
I seemingly have a bit of a catch 22 scenario when trying to run a celery task that depends on django code. Celery code from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery import shared_task from celery import task from letters.send_write_letter_reminders import send_write_letter_reminders # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_name.settings') app = Celery('app_name') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.timezone = 'Europe/London' # Load task modules from all registered Django app configs. app.autodiscover_tasks(settings.INSTALLED_APPS) @app.task(bind=True, name='send_letter_reminders') def send_letter_reminders(slug=None): send_write_letter_reminders(slug=slug) The problem I've run into is that with this line from letters.send_write_letter_reminders import send_write_letter_reminders With it I get: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. And the app server won't run, but without it I get: NameError: name 'send_write_letter_reminders' is not defined Obviously I'm missing something fundamental about how to run Celery and Django together, but I can't see it. Can anyone enlighten me as to what I've done wrong? -
Django's POST method remove "+" symbol from html input form
I'm new to Django, was wondering how can I make it not remove + or passed in html input form. For ex. one of the input form has an input value of $\frac{1}{2} + \frac{2}{3}$, apparently it is converted to $\\frac{1}{2} \\frac{2}{3}$. I don't want Django's post method to remove + from it. The input html code looks like this: <td><input id="element1" type="text" maxlength="100" lang="latex" required></td> -
IPFS not storing encrypted file completely
I am using django-ipfs-storage module for my project and wants to upload a file to InterPlanetaryFileSystemStorage() model field. However if I simply upload a pdf file, it gets successfully uploaded but when I upload after encrypting the file, only first 4096 bytes are stored and rest are not there. When I tried adding the same encrypted file using ipfs add command on the terminal, the file is successfully uploaded. Here is the code for uploading an encrypted file: file_ = open(os.path.join(settings.ENCRYPTION_ROOT,str(paper)+'.encrypted'),'rb') s_file = File(file_) store = Request.objects.get(tusername=request.user.username) store.paper.save(str(paper)+'.encrypted',s_file,save=True) I have searched everywhere but still didn't get any help in this regard.