Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use ChannelNameRouter to communicate between Worker and Websocket (Django and Channels2.x)?
I am trying to set up an app which uses django2.0.2 and channels2.1.1. What I would like to achieve is using a background/worker task to perform some work that will produce data, that should dynamically appear on the website. My problem, related primarily to channels, is: how do I correctly establish communication between the worker, and the consumer connected to a websocket? Below is a minimal example highlighting the issue: The idea is that the user triggers the worker, the worker produces some data and sends it, via the channel layer, to a consumer that is connected to the websocket. #routing.py from channels.routing import ChannelNameRouter, ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import path from testApp.consumers import * application = ProtocolTypeRouter({ "websocket":AuthMiddlewareStack( URLRouter([ path("chat/stream",TestConsumer), ]), ), "channel":ChannelNameRouter({ "test_worker": TestWorker, }), }) The consumers: #consumers.py from channels.consumer import SyncConsumer from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class TestConsumer(WebsocketConsumer): def websocket_connect(self,message): async_to_sync(self.channel_layer.group_add)("testGroup",self.channel_name) self.connect() #I understand this next part is a bit weird, but I figured it #is the most concise way to explain my problem async_to_sync(self.channel_layer.group_send)( "testGroup", { 'type':"echo_msg", 'msg':"sent from WebsocketConsumer", }) def echo_msg(self, message): print("Message to WebsocketConsumer", message) class TestWorker(SyncConsumer): def triggerWorker(self, message): async_to_sync(self.channel_layer.group_add)("testGroup",self.channel_name) async_to_sync(self.channel_layer.group_send)( "testGroup", { 'type':"echo_msg", … -
Django Upgrade From 1.8.8 to 1.11.13 Issue
I am getting the following error. I have added the sites framework, allowed the domain and updated the middleware and context processors but cant fathom this error. Any help would be appreciated as this is live at the minute. manager@web-server:~/Websites/shen$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management /__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/dist-packages/easy_thumbnails/models.py", line 6, in <module> from easy_thumbnails import utils, signal_handlers File "/usr/local/lib/python2.7/dist-packages/easy_thumbnails/utils.py", line 15, in <module> from easy_thumbnails.conf import settings File "/usr/local/lib/python2.7/dist-packages/easy_thumbnails/conf.py", line 334, in <module> settings = Settings() File "/usr/local/lib/python2.7/dist-packages/easy_thumbnails/conf.py", line 21, in __init__ super(AppSettings, self).__init__(*args, **kwargs) TypeError: __init__() takes exactly 2 arguments (1 given) -
Django + Infludb
I have tseries data that has been stored in influxdb, I would like to serve this data through a web API and therefore are considering Django framework and its REST API framework as a solution. At the moment, there is no known support for Influxdb on Django framework, however I have seen someone imply successful creation of this stack in a discussion thread here. Any clear comments or thoughts on how this can be achieved would be appreciated, particularly how to integrate influxdb into the Django framework. -
Django-currentuser error when using custom user model
I'm creating a Django project and I used the package django-currentuser (https://pypi.org/project/django-currentuser/) In my Django project am not using the basic user table, I created custom user model, when I used current user it gives me an error townoftech_warehouse.Item.created_by: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. that is how I am using it in models.py class Item(models.Model): item_category = models.ForeignKey(Category, on_delete="PROTECT") item_name = models.CharField(max_length=100, null=False) item_quantity = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True, editable=False) created_by = CurrentUserField(settings.AUTH_USER_MODEL) -
Django admin Login page giving error "incorrect username password" although I am using correct
this is my model class from django.db import models # Create your models here. from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager): """Helps Djamgo work with our custom user model""" def create_user(self,email,name,password=None): if not email: raise ValueError('users must have an email address') #normalizing the email address convert it to the lowercase email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,password): user = self.create_user(email,name,password) user.is_superuser =True user.is_staff = True class UserProfile(AbstractBaseUser,PermissionsMixin): email = models.EmailField(max_length=255,unique = True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) related_name = "+" object = UserProfileManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ['name'] #helper funtionality def full_name(self): """Use to get full name of the user""" return self.name def short_name(self): """Use to get short name name of the user""" return self.name def __str__(self): `enter code here`return self.email My Setting.py contains everything and my db is sync and i have already created superuser . When i am trying to access my admin from admin login page it gives an error "please login with correct email password " But i have already ensured 5 times that i am using correct email password -
Django Rest Framework + Postman + JSON parse error
I created a Django Api. I used rest_framework.generics.CreateAPIView to post. It works well in default browser. But When i use Postman it throws a error. views.py class AuthorCreateAPIView(CreateAPIView): queryset = Author.objects.all() serializer_class = AuthorCreateUpdateSerializer serializers.py class AuthorCreateUpdateSerializer(ModelSerializer): class Meta: model = Author fields = [ 'name', 'biography', ] Error : "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" -
Wagtail Custom Inline PageChooser
Currently i face a strange problem, using wagtail. I modified a Snippet from the Documentation. But it seems like i miss something. This is my Code... The Goal is to allow selecting multible Pages using PageChooser (and maybe later show links in template) class BlogPage(Page): content_panels = Page.content_panels + [ MultiFieldPanel([ InlinePanel('related_pages', label="Related Pages"), ]) ] class BlogPageRelated(Orderable): page = ParentalKey('home.BlogPage', on_delete=models.CASCADE, related_name='related_pages') relpages = models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', blank=True, null=True ) panels = [ PageChooserPanel('relpages', 'home.BlogPage'), ] The Database is filled with data. It seems like no data are delivered to the template. The template variable {{ page.related_pages }} outputs "home.BlogPageRelated.None". {{ page.related_pages }} = home.BlogPageRelated.None -
Django: Cannot migrate database
I've spent the past hour scouring stack overflow and absolutely could not find anything that worked in my situation. I changed a ManytoManyField to a ForeignKeyField (to simplify my project) and it resulted in the error below. I switched it back to a ManytoManyField but the error would not go away. I've stopped and started Postgres, dropped and recreated my tables but I cannot get it to work again. My error is as follows: Operations to perform: Apply all migrations: admin, rango, sessions, contenttypes, auth Running migrations: Rendering model states... DONE Applying rango.0013_auto_20180506_1225...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/db/migrations/operations/fields.py", … -
Python Django How to add a function to maintenance mode ?
I'am using this Maintenance-mode package https://github.com/fabiocaccamo/django-maintenance-mode in order to display my maintenance template. I would like to add to my maintenance template a function e.g (Subscription to Newsletter) but I don't know where should I write my code. Because when the maintenance is On, my code from views.py is not used and my form is not displayed on my template. Can anybody help me to find the way to add a function to my template when the maintenance mode is On ? -
Why my virtual environments are hidden created by 'mkvirtualenv'?
Whenever I create any virtual environment using mkvirtualenv envname, it creates the env and activate it automatically. But I can't find the folder named envname. Whenever I do workon envname it activates it, but I can't see the virtual environment folder. Below is the packages I've installed. Django==2.0.4 pbr==4.0.2 pytz==2018.4 six==1.11.0 stevedore==1.28.0 virtualenv==15.2.0 virtualenv-clone==0.3.0 virtualenvwrapper-win==1.2.5 -
Django: Ajax not receiving data from server response
I am pretty new to Django and I am trying to figure out how to add content dynamically coming from a python script without reloading a page. Currently, I have two functions in my views.py file. One handles uploading a file (home), and the other handles calling a python script and handling the file (handle). The reason I separated it like this is because I want to sequentially populate a HTML table as the python script works with the uploaded file. However, my ajax function is not receiving any data from the handle function's http response and I am not sure why. Neither the success nor the error functions are being called. This is really strange because the print statement in the handle function in views.py prints successfully with data. Views.py i=0 uploaded_file = None def home(request): if (request.method == 'POST'): file_form = UploadFileForm(request.POST, request.FILES) if file_form.is_valid(): global uploaded_file uploaded_file = request.FILES['file'] print(uploaded_file) else: file_form = UploadFileForm() return render(request, 'personal/home.html', {'form': file_form}) def handle(request): # TODO make ajax wait for a response from 'home' # so I don't have to wait for 1 second time.sleep(1) data = {} data['Name'] = fileName(uploaded_file) if(request.is_ajax()): print(data) # prints succesfully return HttpResponse(json.dumps(data), content_type="application/json") home.html … -
Django Channels - Client receives only one message when Group.send() is called in a loop in consumers.py
I have built a Django app which runs automated testing. I collect the inputs from the user, as to what all tests need to be run and when the user clicks on submit button, the tests run for a few hours to a couple of days (depending on the number of tests selected) and once all the tests are completed, the results are showed on a template. Now the problem is, till all the tests are completed, the user is not updated with the progress. So I decided to use Django Channles to provide live update to the client as and when I have results for individual tests. With my implementation, I call the Group('user-1').send({'text': i}) method in a for loop. But all I see in the template is only the output of the last Group('user-1').send({'text': i}) operation. As per my requirement, once Group('user-1').send({'text': i}) is called, the socket.onmessage() function in the section of my template should receive the message and should again wait for messages sent by subsequent Group('user-1').send({'text': i}) calls. I saw a very similar question here which is already answered, but the solution is not working for me. Please help me identify what needs to corrected in … -
Python import, multiple setting file overrride issues
In a package: have 3 files each one of them containing settings(Django settings): settings __init__.py base.py; dev.py; stage.py; In __init__.py I have: from settings import base try: import dev except: pass try: import stage except: pass Then I point an import to __init__.py In each one of the settings files, variables, are defined. They can be new variables or variables that I override the previous file variables. For example if in base.py there is a variable A = 5, in dev.py I override A=9. Also replace a list or append to a list. This doesn't work, so I need to import base in the other two files. from .base import * But I have another issue, even if variables and lists are ok now, dictionaries are not override; For example in base.py I have: Db = { 'default': { 'ana': 'test', } } In dev.py I have: Db = { 'default': { 'ana': 'dev', } } I receive an error, because is using the db in base instead the db in dev. Why ? -
django-registration-redux login redirect failed
I'm using django registration redux in my django project,but it failed to redirect to LOGIN_REDIRECT_URL after logged in. django-registration-redux version 2.4 python version 3.6.1 Login Page Redirect Page Here is my code for settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rango', 'registration', ] REGISTRATION_OPEN = True ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True LOGIN_REDIRECT_URL = '/rango/' LOGIN_URL = '/accounts/login/' Here is my code for login.html: {% extends "rango/base.html" %} {% block body_block %} <h1>Login</h1> <form method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Log in" /> <input type="hidden" name="next" value="{{ next }}" /> </form> <P> Not a menber? <a href="{% url 'registration_register' %}">Register</a> </P> {% endblock body_block %} Here is my code for rango/base.html: <!DOCTYPE html> {% load static %} {% load rango_template_tags %} <html> <head lang="en"> <meta charset="utf-8" /> <title>Rango - {% block title_block %} How to Tango with django! {% endblock %} </title> </head> <body> <div> {% block body_block %} {% endblock %} </div> <hr /> <div> <ul> {% if user.is_authenticated %} <li><a href="{% url 'auth_logout' %}?next=/rango/">Logout</a></li> <li><a href="{% url 'add_category' %}">Add a New Category</a></li> {% else %} <li><a href="{% url 'auth_login' %}?next=/rango/">Sign In</a></li> <li><a href="{% url 'registration_register' %}">Sign Up</a></li> {% endif %} <li><a … -
Excessive Queries in Django Role Permission
I am building a REST API with Django and Django Rest Framework. Its a application where teacher can create classroom. Classroom has lectures and other materials. These classroom can only be visit by the owner or the administrator. For controlling access to different endpoint I am using Django-Role-Permissions. Whenever I'm trying to check permission using BasePermission from Django Rest Framework and Django-Role-Permission, I am receiving an excessive number of Database queries. For example, When I'm hitting List-Create Classroom endpoint, I am getting 40 Queries which is very weird. Here's my Classroom model from django.db import models class Classroom(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100, null=False, blank=False) description = models.CharField(max_length=200, null=False, blank=False) course = models.ForeignKey(Course, null=True, blank=True, on_delete=models.SET_NULL) semester = models.ForeignKey(Semester, null=True, blank=True, on_delete=models.SET_NULL) teacher = models.ForeignKey(User, related_name='classrooms', on_delete=models.CASCADE) archive = models.BooleanField(default=0) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) Here's my ListCreateClassroomAPIView from rest_framework.generics import ListCreateAPIView class ListCreateClassroomAPIView(ListCreateAPIView): serializer_class = ClassroomSerializer permission_classes = (IsAuthenticated, IsAuthorizedToCreate) def get_queryset(self): if has_permission(self.request.user, 'view_classroom'): return Classroom.objects.all().select_related('teacher').select_related('teacher__employee_details') return Classroom.objects.filter(teacher=self.request.user).select_related('teacher'). \ select_related('teacher__employee_details') def perform_create(self, serializer): course = Course.objects.get(id=self.request.data.get('course')) semester = Semester.objects.get(id=self.request.data.get('semester')) serializer.save(teacher=self.request.user, course=course, semester=semester) Here I'm trying to return all the classroom if the user has 'view_classroom' permission or return just the classroom the user owns. The permission … -
Django can't open a .xlsx file with pandas [ File does not exist error]
from django.views.generic.edit import FormView from django.http import HttpResponseRedirect from .form import FileFieldForm, edit from django.shortcuts import render from .models import Document import pandas as pd list1=[] class FileFieldView(FormView): form_class = FileFieldForm template_name = 'base.html' # Replace with your template. # success_url = 'moreorless' # Replace with your URL or reverse(). files = [] def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files=request.FILES.getlist('file_field') if form.is_valid(): file = Document(file_field=request.FILES['file_field']) file.description='fill' print(file.file_field.path) for f in files: list1.append(file.file_field.path) file.save() print('reached') return HttpResponseRedirect('/dataprocessing/edit/') else: return self.form_invalid(form) class editable(FormView): form_class = edit template_name = 'edit.html' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = edit(request.POST) if form.is_valid(): print(form.cleaned_data['dummy']) return HttpResponseRedirect('/dataprocessing/view/') def viewing2(request): str=list1[0] dataset = pd.read_csv(str) #opening file here X = dataset.iloc[:, :].values return render(request, "view.html", {'word':X}) FileNotFoundError at /dataprocessing/view/ File b'F:\\python3\\harry\\dataprocessing\\media\\List of Participants for PTU.xlsx' does not exist Request Method: GET Request URL: http://localhost:8000/dataprocessing/view/ Django Version: 2.0.2 Exception Type: FileNotFoundError Exception Value: File b'F:\\python3\\harry\\dataprocessing\\media\\List of Participants for PTU.xlsx' does not exist Exception Location: pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._setup_parser_source, line 718 Python Executable: F:\python3\python.exe Python Version: 3.6.4 Python Path: ['F:\\python3\\harry\\dataprocessing', 'C:\\Users\\Harinder\\Desktop\\Deep_Learning_A_Z\\Volume 1 - Supervised Deep ' 'Learning\\Part 1 - Artificial Neural Networks (ANN)\\Section 4 - Building an ' 'ANN', 'F:\\python3\\python36.zip', 'F:\\python3\\DLLs', 'F:\\python3\\lib', 'F:\\python3', 'F:\\python3\\lib\\site-packages'] … -
Celery Error: Received unregistered task of type 'task'
I'm getting the following error in my celery log: [2018-05-04 23:33:42,186: ERROR/MainProcess] Received unregistered task of type 'post_jobs'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[], {}, {"callbacks": null, "errbacks": null, "chord": null, "chain": null}]' (77b) Traceback (most recent call last): File "/home/james/postr/env/lib/python3.5/site-packages/celery/worker/consumer/consumer.py", li$ strategy = strategies[type_] KeyError: 'post_jobs' post_jobs is my only celery task, and it's in another module (not my main app module), which may be why I'm encountering this problem. I was forced to do this as my model could not be imported from the main app. My celery conf looks like this (post is not the main module): [program:postr-celery] command=/home/james/postr/env/bin/celery -A post worker --loglevel=INFO directory=/home/james/postr user=james numprocs=1 stdout_logfile=/var/log/supervisor/celery.log stderr_logfile=/var/log/supervisor/celery.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 stopasgroup=true I can successfully receive the task: however when I start my celery beat via celery -A draft1 beat: my celery log returns the error (Received unregistered task of … -
Migrating Django App following error come. Anybody have answer?
//commandline manage.py migrate command// Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\Crisp\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Crisp\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 347, in execute django.setup() File "C:\Users\Crisp\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Crisp\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Crisp\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Crisp\AppData\Local\Programs\Python\Python36-32\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "E:\DjP\blog\idaneram\blog\models.py", line 6, in class Post(models.Model): File "E:\DjP\blog\idaneram\blog\models.py", line 13, in Post author = models.ForeignKey(User, related_name='blog_post') TypeError: init() missing 1 required positional argument: 'on_delete' -
Ubuntu 14.04.4 supervisor run process tcp keep syn_sent state
I use supervisor to run django and django-channel. But django cannot connect mysql and redis on localhost, netstat shows connection keep SYN_SENT state. But connection can establish with command python3 manage.py runserver You can see in the picture that redis and mysql can connect but the process run by supervisor keep SYN_SENT. Here is my supervisor config files directory = /home/judge/onlineTest command = daphne -b 127.0.0.1 -p 8000 onlineTest.asgi:channel_layer autostart = true autorestart = true user = judge redirect_stderr = true Is there something wrong with my configuration? -
Django not rendring correct image path
I have images inside my app media folder but django is not rendering the correct image path. Here is what I have in my setting - STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),] MEDIA_ROOT = BASE_DIR MEDIA_URL = '/' in my html - <img style="" class="card-img-top img-fluid" src="{{object.cover_image.url}}" alt=""> its showing image src src="/accounts/media/images/RAJASTHAN/SIKAR/332001/panshar8688/cover_image/1145452615/1145452615.jpg" which looks correct but when I go in admin panel and click on the image url it shows me error- "c:\Users\lenovo\Desktop\My_Django_Stuff\scratchcommerce10\media\images\RAJASTHAN\SIKAR\332001\Deepkha2623\cover_image\2187831623\2187831623.png" does not exist and the path is incorrect because media is inside accounts, the correct path is c:\Users\lenovo\Desktop\My_Django_Stuff\scratchcommerce10\accounts\media\images\RAJASTHAN\SIKAR\332001\Deepkha2623\cover_image\2187831623\2187831623.png Images is saving in correct directory but not rending correct path, I am unable to figure out this problem, please answer if you can. -
Can't add new field in the django model
Django 2.0 I've created a model in Blog app, class Category(models.Model): field1 = models.... field2 = models.... field3 = models.... and after some time I want to add a new field in that model. class Category(models.Model): field1 = models.... cover_pic = .models.... field2 = models.... field3 = models.... I followed this answer. But it gives me the following error. django.db.utils.OperationalError: (1054, "Unknown column 'blog_category.cover_pic' in 'field list'") -
Require.js with django $ is not a function
I am using a open source template called tabler (https://github.com/tabler/tabler), and by default its using require.js, so i installed django-require (https://github.com/etianen/django-require) and included {% load require %} and {% require_module 'core' %} {% require_module 'dashboard' %} Now i got rid of almost every error i had before except: Uncaught TypeError: $ is not a function at core.js:18 As i understand its like jQuery is not loaded is there anything else i need to do to expose $? -
Django production on a host
every tutorial about django production and deployment is about running site on pythonanywhere.com , digitalocean.com , heroku.com or some other services but I want to upload my django site on my own host. I have a host (not a server) with apache, python3.6. mysql, git 2.15 installed and mod_wsgi is enabled. After spending some days I found this but I don't have access to /var directory. Is there any way to deploy my site on a host? any idea would help me. thanks. -
Update and delete in same Api view without passing id in Url
How to perform crud operation in One URL End point in django rest framework? Currently i am having 2 url end points url(r'^recipient/$', views.RecipientView.as_view()), - in this APiview im performing get all and post url(r'^recipient/(?P[0-9]+)/$', views.RecipientDetail.as_view()), - in this APiview im performing retrieve, update delete. Now the requirement is i have remove 2nd url and perform all operations in first api view? I am new to django framework can anyone please help me achieve this? Below is my code. View.py class RecipientView(APIView): def get(self, request, format=None): Recipients = Recipient.objects.all() serializer = RecipientSerializer(Recipients, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = RecipientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) """ class RecipientDetail(APIView): def get_object(self, pk): try: return Recipient.objects.get(pk=pk) except Recipient.DoesNotExist: raise Http404 def get(self, request, pk, format=None): Recipient = self.get_object(pk) serializer = RecipientSerializer(Recipient) return Response(serializer.data) def put(self, request, pk, format=None): Recipient = self.get_object(pk) serializer = RecipientSerializer(Recipient, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): Recipient = self.get_object(pk) Recipient.delete() return Response(status=status.HTTP_204_NO_CONTENT) """ model.py class Recipient(models.Model): recipient = models.CharField(max_length=32, blank=False, null=False) def str(self): """returns the model as string.""" return self.racipient serializer.py class RecipientSerializer(serializers.ModelSerializer): class Meta: model = Recipient fields = '__all__' i am not … -
Gapps script: using user auth credentials to authorize vs external django app service (which uses google as oauth provider)
The workflow I need: * user authenticated via google to a g-apps spreadsheet with google-apps-script. * The script then calls an external service( a django app) which uses oauth for login with google backend - and authenticates with the user google credentials. Is this even possible? Maybe my google foo is failing me, but I can't find examples/explanations for this scenario