Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Sync Django HTTP Login Session with Websocket Session/Cookie?
I am using Django DjangoChannelsGraphqlWs which is Graphene version of Django Channels. It allows me to transfer data using graphql style. I wrote a login login on my mutation schema. class Login(graphene.Mutation): class Arguments: email = graphene.String() password = graphene.String() ok = graphene.Boolean() user = graphene.Field(UserType) def mutate(root, info, email, password, **kwargs): ok = False user = authenticate(info.context, username=email, password=password) if user is not None: login(info.context, user) update_or_create_user_login_info(info=info) ok = True return Login(ok=ok, user=user) else: return Login(ok=ok) And I wrote my client side Websocket using Apollo-client like this: class WebSocketService { static instance = null; callbacks = {}; static getInstance() { if (!WebSocketService.instance) WebSocketService.instance = new WebSocketService(); return WebSocketService.instance; } constructor() { this.socketRef = null; this.connect(); } connect() { const client = new SubscriptionClient(BASE_URL + '/graphql/', { reconnect: true, }); const link = new WebSocketLink(client); const cache = new InMemoryCache(); this.socketRef = new ApolloClient({ link, cache, }); } query = (query, variables={}, context={}, fetchPolicy='no-cache', errorPolicy='all') => this.socketRef.query({ query: gql`${query}`, variables, context, fetchPolicy, errorPolicy }) mutate = (mutation, variables={}, context={}, fetchPolicy='no-cache', errorPolicy='all') => this.socketRef.mutate({ mutation: gql`${mutation}`, variables, context, fetchPolicy, errorPolicy }) } const WebSocketInstance = WebSocketService.getInstance(); export default WebSocketInstance; Lastly, here is my consumer. class MyGraphqlWsConsumer(channels_graphql_ws.GraphqlWsConsumer): """Channels WebSocket consumer which provides … -
Google authentication works for users that didn't registered?
I have a Django website and I want my users can login with google account after they registered in my app. I did by using social-auth-app-Django package. But now I see that someone who doesn't have registered in my website can login to site. What is the problem? -
Django ORM key error with lost MySql connection
This is the environment: AWS Aurora database compatible with MySql. Django 2.0.3 (Python 3.6) Pip-Mysql dependencies: django-mysql==2.2.2, mysqlclient==1.3.12. Master-Slave database configuration. It seems that django or mysql engine always fails on certain queries resulting in this specific error: Traceback (most recent call last): File "/home/ubuntu/ivs/vpython/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 158, in __get__ rel_obj = self.field.get_cached_value(instance) File "/home/ubuntu/ivs/vpython/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'assigned_to' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/ivs/vpython/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/ubuntu/ivs/vpython/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/home/ubuntu/ivs/vpython/lib/python3.6/site-packages/MySQLdb/cursors.py", line 253, in execute self._warning_check() File "/home/ubuntu/ivs/vpython/lib/python3.6/site-packages/MySQLdb/cursors.py", line 148, in _warning_check warnings = db.show_warnings() File "/home/ubuntu/ivs/vpython/lib/python3.6/site-packages/MySQLdb/connections.py", line 381, in show_warnings self.query("SHOW WARNINGS") File "/home/ubuntu/ivs/vpython/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') Yes, one of my models have "assigend_to" field which is a foreign key. But I have no idea why would it fail with a KeyError? Did anyone have any similar KeyErrors and MySql lost connections as a result? -
Python - Is a dict or list better suited for efficiently storing and searching this data?
Here's the scenario: I'm parsing a log file and turning each individual line (string) from the log file into a hierarchical structure. I want to be able to categorize each message as belonging to a particular event on a particular day. I'm trying to send this data structure to the front-end of my Django app and display this hierarchical structure, and prevent the front-end from having to handle all these computations. On the front end I would like to be able to search by key words and display results that do this. Either I can search the data structure the back-end sends over, or I can search the rendered DOM. I have the following data: Day 1 Event 1 message message message Event 2 message message message Event 3 message message message Day 2 Event 1 message message message Event 2 message message message ... The data One event in the log file would look something like this: 2019-08-05 09:18:45 -- INFO -- all buttons -- THOR: All button were pressed. 2019-08-05 09:18:48 -- WARNING -- THOR1: The system failed to connect. Is the asset online? If so, did the password change? 2019-08-05 09:18:51 -- WARNING -- THOR2: The system … -
Is it necessary to type in '$ pipenv install django==2.x.x' and '$ pipenv shell' everytime?
I'm reading 'Django for Beginners' by William S.Vincent to teach myself how to use the django framework and the author makes it seem like I have to type in '$ pipenv install django==2.x.x' and '$ pipenv shell' into the command line every time I launch PowerShell to use the framework. Is that necessary or is the author showing how one would normally start a django project for the first time and is this just a one-time command? -
Adding 'x-total-count' with django corsheaders
How do i manage to add the 'x-total-count' in my django cors response header? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'languages' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_HEADERS = [ 'x-total-count', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] . . . This is how my setting.py looks like This is what the error looks like: Warning: Missing translation for key: "The X-Total-Count header is missing in the HTTP Response. The jsonServer Data Provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose- Headers header?" I wasnt able to solve this problem even tho i looked at many related questions. The django cors-headers docs do not include an guide how to add the 'x-total-count' -
how to send an image with out attachment while sending email
I have succeeded in sending an email with image attachment but I want to send an image above my email_approval.html as not of the image attachment. I want my image to be part of my message.I also have tried putting it as image tag on the html file but it does not appear on the gmail... please help me... html_content=render_to_string('email_approval.html',{'result':result}) message = strip_tags(html_content) email = EmailMultiAlternatives('인증 메일', message, to=[request.POST['email']]) email.attach(logo_data()) email.attach_alternative(html_content, "text/html") email.send() def logo_data(): with open(finders.find('../static/logo.jpeg'), 'rb') as f: logo_data = f.read() logo = MIMEImage(logo_data,_subtype="jpeg") logo.add_header('Content-ID', '<logo>') return logo html_content=render_to_string('email_approval.html',{'result':result}) message = strip_tags(html_content) email = EmailMultiAlternatives('인증 메일', message, to=[request.POST['email']]) email.attach(logo_data()) email.attach_alternative(html_content, "text/html") email.send() def logo_data(): with open(finders.find('../static/logo.jpeg'), 'rb') as f: logo_data = f.read() logo = MIMEImage(logo_data,_subtype="jpeg") logo.add_header('Content-ID', '<logo>') return logo I have succeeded in sending an email with image attachment but I want to send an image above my email_approval.html as not of the image attachment. I want my image to be part of my message. I also have tried putting it as image tag on the html file but it does not appear on the gmail... please help me... -
Best practices for sharing database across multiple sites (specifically code versioning with schema changes)
We would like to run multiple django sites with the same codebase, but different versions due to different deploy dates, and would like to share a common content database. We are unsure how to deal with schema changes if all django server instances cannot be guaranteed to be updated at the same time. This is the beginning of the project, we current have one site and are looking to extend this to two sites, thereby introducing the problem. We foresee an issue if we make a schema change by updating the django code and running migrations on one site, but cannot deploy to the site for some time (due to deployment restrictions) that the other site would suffer because there would be a schema mismatch between the django expectation of the database structure and the actual database structure. Since we want to share a content database across multiple sites, we are looking for ways to solve this issue. We have considered having a local copy of the master content database for each site, which the master would replicate to in near real time. If there was a version mismatch then the older site would have the replication disabled. However then … -
Wagtail: Prefered way to disable the admin dirty forms check
Ive written my own custom panels that link to adminmodels to be able to add some extended functionality to my pageobjects. But I am having trouble with the dirtycheck added by wagtails admin (onbeforeunload hook that opens an alert), that keeps on nagging the users about not leaving the page, even though I havent changed anything in the input forms. Is there a reliable way to disable the dirtycheck for certain pagetypes? -
how to get django forms.Form dynamic form in python based on other form user mark
how to create dynamic form choice based in other form choice in django ? in python 2.7 django 1.11, i want to make forms.ChoiceField dynamic in thr python code based on other choice field choosing of the user . my code is : def get_mgmnt_form(): from django import forms mode_list = ['first_mode', 'second_mode'] modes = sorted(zip(mode_list, mode_list), key=lambda x: x[0]) class CustomForm(forms.Form): mode = forms.ChoiceField(modes, required=True, label='Runnning Mode', ) mail = forms.EmailField(required=True, label='Email', min_length=9) categories_names = ['category_1','category_2','category_3'] categories = zip(categories_names, categories_names) category_names = forms.ChoiceField(categories, required=True, label='Categorys', ) category_field = forms.ChoiceField('dynamic field from DB based on selected category_names', required=True, label='dynamic field of chosen Category', ) return CustomForm -
Django prefetch_related and performance optimisation with multiple QuerySets within loops
Effectively I have multiple Queries within loops that I am just not happy with. I was wondering if someone had the expertise with prefetch_related and other Django Query construction optimisation to be able to help me on this issue. I start with: users = User.objects.filter(organisation=organisation).filter(is_active=True) Then, I start my loop over all days starting from a certain date "start_date": for date in (start_date + datetime.timedelta(n) for n in range((datetime.datetime.now().replace(tzinfo=pytz.UTC) - start_date).days + 1)): I then within this loop over a filtered subset of the above users for date in (start_date + datetime.timedelta(n) for n in range((datetime.datetime.now().replace(tzinfo=pytz.UTC) - start_date).days + 1)): for user in users.filter(created_date__lte=date).iterator(): Ok, so firstly, is there any way to optimise this? What may make some of the hardcore Django-ers loose their tether, I do all of the above inside another loop!! for survey in Survey.objects.all().iterator(): for date in (start_date + datetime.timedelta(n) for n in range((datetime.datetime.now().replace(tzinfo=pytz.UTC) - start_date).days + 1)): for user in users.filter(created_date__lte=date).iterator(): Inside the last loop, I perform one final Query filter: survey_result = SurveyResult.objects.filter(survey=survey, user=user, created_date__lte=date).order_by('-updated_date')[0] I do this because I feel I need to have the user, survey and date variables ready to filter... I have started thinking about prefetch_related and the Prefetch object. … -
ModuleNotFoundError: No module named 'ebcli'
When I tried to check the version of elastic-beanstalk by 'eb --version' in visual studio code terminal, there happened an error : ModuleNotFoundError: No module named 'ebcli'. How to solve this problem? Terminal: input : $ eb --version output : Traceback (most recent call last): File "C:/Users/likelion_MC/AppData/Roaming/Python/Python37/Scripts/eb", line 12, in <module> import ebcli.core.ebcore ModuleNotFoundError: No module named 'ebcli' This is my eb file: import sys import ebcli.core.ebcore def main(): return ebcli.core.ebcore.main() if __name__ == '__main__': sys.exit(main()) -
Success redirect to profile form gives TypeError at /profile/ join() - argument must be str or bytes, not 'NoneType'
I have an extended User model called UserProfile, and the update view uses the SuccessMessageMixin to redirect on successful update. The problem is that something in the django code is trying to join an unset var (paths) to the path, and I'm not sure why. user_profile/views.py class UserProfileView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = UserProfile form_class = UserProfileChangeForm success_url = reverse_lazy("user_profile:profile") # success_url = "/success/" success_message = "Profile updated" def get_object(self, *args, **kwargs): return self.request.user def post(self, request, *args, **kwargs): form = self.form_class(request.POST, instance=request.user) if form.is_valid(): profile = form.save(commit=False) profile.save() return render(request, self.template_name, {"form": form}) Stack trace on submit of form with changed data (the data does actually get updated, so this is purely a redisplay issue). File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\ntpath.py" in join 89. for p in map(os.fspath, paths): During handling of the above exception (expected str, bytes or os.PathLike object, not NoneType), another exception occurred: File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\contrib\auth\mixins.py" in dispatch 52. return super().dispatch(request, *args, **kwargs) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "D:\users\mjnic\OneDrive\Workspaces\Django\pyp\src\pyp\user_profile\views.py" in post … -
How to encode an uploaded image using base64 and create a brand new PNG image by decoding it?
Currently, I created a Django html page that'll allow a user to upload an image. Images are restricted to only JPG, JPEG, PNG and SVG. If uploaded correctly, the image is stored as in a png extension. After this, I want to grab the path and encode it using base64. Using this string, I want to then create a brand new image which should hold a PNG extension and then store it in the database. How should I do this? Or better yet, is there a better way to do it? I feel that converting an existing png image to a new png image again might be tedious. Please do help. Code below: validators.py def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] # [0] returns path+filename valid_extensions = ['.jpg', '.png', '.jpeg', '.svg'] if not ext.lower() in valid_extensions: raise ValidationError(u'Unsupported file extension.') models.py from django.db import models import os from PIL import Image from datetime import date import datetime from .validators import validate_file_extension import base64 def get_directory_path(instance, filename): today = date.today() t = datetime.datetime.now() day, month, year = today.day, today.month, today.year hour, minutes, seconds = t.hour, t.minute, t.second filename = str(day) + str(month) + str(year) + str(hour) + … -
Django middleware skipping data attribute in static url
i have a simple middleware builded in django app. It works for push notification image tracking. Logic: if push shows up, middleware should see it by data attribute and update status of my Push object. My middleware code: class PushStatistic: def process_request(self, request): if request.GET.get('pushid'): print('entered push id for readed') pushid = request.GET.get('pushid') print(f'Push id - {pushid}. Updating...') if pushid: pushid = int(pushid) if Push.objects.filter(id=pushid).exists(): Push.objects.filter(id=pushid).update(status=4) print('status updated') so when i send notification, icon url for push looks like this: https://test.com/static/img/pic.png?pushid=9403687 When push showing up, i see the picture, but middleware not working. I use the same middleware logic for push-clicks tracking, and it works well. I cant understand what im doing wrong now, cause as i see it, its just the same GET request. Maybe its because its static url? Also i build django-view with same logic for push tracking AND IN VIEW IT WORKS: def fileresp(request, filename): if request.GET.get('pushid'): pushid = request.GET.get('pushid') Push.objects.filter(id=pushid).update(status=4) image_data = open(f"{project_settings.BASE_DIR}/media/{filename}", "rb").read() return HttpResponse(image_data, content_type="image/png") But i want to build it in django-middleware for more universality. Is it possible? -
Pycharm gives error "TypeError: 'NoneType' object is not callable" in debug mode for Python-Django Project
I have set up the python-django project in Pycharm. On python manage.py runserver command in run mode, its works fine but when I run the project in debug mode I get following exception: Traceback (most recent call last): File "/home/usmanmaqbool/Downloads/pycharm-community-2018.3/helpers/pydev/pydevd.py", line 2060, in <module> main() File "/home/usmanmaqbool/Downloads/pycharm-community-2018.3/helpers/pydev/pydevd.py", line 2054, in main globals = debugger.run(setup['file'], None, None, is_module) File "/home/usmanmaqbool/Downloads/pycharm-community-2018.3/helpers/pydev/pydevd.py", line 1405, in run return self._exec(is_module, entry_point_fn, module_name, file, globals, locals) File "/home/usmanmaqbool/Downloads/pycharm-community-2018.3/helpers/pydev/pydevd.py", line 1412, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "/home/usmanmaqbool/Desktop/proj/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 58, in execute super(Command, self).execute(*args, **options) File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 97, in handle self.run(**options) File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 106, in run autoreload.main(self.inner_run, None, options) File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 333, in main reloader(wrapped_main_func, args, kwargs) File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 304, in python_reloader exit_code = restart_with_reloader() File "/home/usmanmaqbool/Envs/proj/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 290, in restart_with_reloader exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ) File "/home/usmanmaqbool/Downloads/pycharm-community-2018.3/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 496, in new_spawnve return getattr(os, original_name)(mode, path, args, env) File "/home/usmanmaqbool/Envs/proj/lib/python2.7/os.py", line 573, in spawnve return _spawnvef(mode, file, args, env, … -
Django doesnt' read second templatetags folder
Say I have a project and two registered apps. Inside my apps I created templatetags package with custom tags that I want to use in corresponding html templates: Project --App1 | |----templatetags | |----custom_tags.py |----__init__.py --App2 | |----templatetags | |----custom_tags.py |----__init__.py And it looks like django sees only one templatetags folder. I use {% load custom_tags %} in html templates in both apps. When there is only one templatetags folder then corresponding custom tags work (so there is no error in custom_tags.py). I tried to rename one file to eg 'custom_tags_app1' and then {% load custom_tags_app1 %} in html templates in app1, but then it throws error saying: 'custom_tags_app1' is not a registered tag library. Must be one of: . . custom_tags ... When I renamed it I tried to import 'custom_tags_app1' in the shell and it worked What am I missing here? What should I do to make it work, when they both work independently, but don't work together? -
Cannot open ContentFile containing BytesIO content again once it is closed
Once a ContentFile object containing binary data is closed, it isn't possible to open it again: >>> content = ContentFile(b'\x00\x01\x00\x02\x00\x00\x00\x03') >>> content.closed False >>> content.file <_io.BytesIO object at 0x7fa0cd33c8e0> >>> content.file.closed False >>> content.file.close() >>> content.file.closed True >>> content.closed True >>> content.open() *** ValueError: I/O operation on closed file. >>> content.read() *** ValueError: I/O operation on closed file. >>> content.file.read() *** ValueError: I/O operation on closed file. This process naturally occurs when a serializer writes a content file to a field, making it impossible to open the file from memory later on during another process without downloading it first. Versions: Python 3.6 Django 1.11 -
How to get dictionary value in Django Template with Key
I have two dict in my view function policy = {{'policy_no':'123'},{'policy':'456'}} claim = {{'123':'ACTIVE'}} In my template file I dont want to iterate 'claim' dict. view.py policies = {{'policy_no':'123'},{'policy':'456'}} claims = {{'123':'ACTIVE'}} template file {% for policy in policies %} {{claims[policy.policy_no]}} # I want to access directly 'ACTIVE' {% endfor %} -
Python testing: mocking a function that's imported AND used inside another funciton
Due to circular-import issues which are common with Celery tasks in Django, I'm often importing Celery tasks inside of my methods, like so: # some code omitted for brevity # accounts/models.py def refresh_library(self, queue_type="regular"): from core.tasks import refresh_user_library refresh_user_library.apply_async( kwargs={"user_id": self.user.id}, queue=queue_type ) return 0 In my pytest test for refresh_library, I'd only like to test that refresh_user_library (the Celery task) is called with the correct args and kwargs. But this isn't working: # tests/test_accounts_models.py @mock.patch("accounts.models.UserProfile.refresh_library.refresh_user_library") def test_refresh_library(): Error is about refresh_library not having an attribute refresh_user_library. I suspect this is due to the fact that the task(refresh_user_library) is imported inside the function itself, but I'm not too experienced with mocking so this might be completely wrong. -
Problem with 'Cannot assign' error in django
I have something like this in my template. <form action="" method="POST"> {% csrf_token %} <select name='section'> {% for item in all_sections %} <option>{{ item.SectionName }}</option> {% endfor %} </select> </form> and in my view.py page: obj=models.Section.objects.all() context={ 'all_sections':obj, } return render(request,'matab/add-service.html',context) but i get this is error while saving data: Cannot assign "'{item}'": "Services.Section" must be a "Section" instance. also my models.py is like this: class Section(models.Model): SectionName=models.CharField(max_length=50) SectionId=models.CharField(max_length=10) class Services(models.Model): Section=models.OneToOneField( Section, on_delete=models.CASCADE, ) how can i solve it? -
"http://127.0.0.1:8000/ might be temporarily down" after dockerized badgr-server
I'm trying to dockerize django/python project cold badgr-server from here: https://github.com/concentricsky/badgr-server I succeed to deployed it on localhost on ubuntu 18.04 without docker. the build went well. when I did : docker container run -it -p 8000:8000 badgr python root/badgr/code/manage.py runserver and there is nothing on localhost:8000 note: docker container run -it -p 8000:8000 badgr python ./manage.py won't work. output: ?: (rest_framework.W001) You have specified a default PAGE_SIZE pagination rest_framework setting,without specifying also a DEFAULT_PAGINATION_CLASS. HINT: The default for DEFAULT_PAGINATION_CLASS is None. In previous versions this was PageNumberPagination. If you wish to define PAGE_SIZE globally whilst defining pagination_class on a per-view basis you may silence this check. System check identified 1 issue (0 silenced). August 06, 2019 - 10:01:22 Django version 1.11.21, using settings 'mainsite.settings_local' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. I changed in setting_local.py the ALLOWED_HOSTS to : ALLOWED_HOSTS = ['*'] Thanks! ** extra advises are more than welcome!** this is the Dockerfile : FROM ubuntu:18.04 # Preparation RUN apt-get update # Install server dependencies RUN apt-get install -y curl git git-core python-virtualenv gcc python-pip python-dev libjpeg-turbo8 libjpeg-turbo8-dev zlib1g-dev libldap2-dev libsasl2-dev swig libxslt-dev automake autoconf libtool libffi-dev libcairo2-dev libssl-dev RUN pip install virtualenv --upgrade #RUN … -
While using reverse for redirecting, passing optional kwargs is causing the url to retain the parameter always
When I am using reverse() to redirect to a different view with some optional kwargs, as a response from the view I want to display an alert message on load of a template if a key is passed in context dictionary based on that kwarg arg which came in. This is happening fine. But as the url contains the optional path parameter any call to same view with filters is displaying the alert again and again.I want to remove that optional path parameter on display of that alert. This is my view to calling reverse - return HttpResponseRedirect(reverse('data_asset_formats_msg', kwargs={'msg':"Unauthorized to delete DAF-%s"%data_asset_format.data_asset_format_id})) This is my urls - url(r'^data_asset_format/(?P<msg>.*)/', views.data_asset_formats, name='data_asset_formats_msg'), This is the implementation of the view data_asset_formats - def data_asset_formats(request, **kwargs): logr.info(kwargs) msg = kwargs.get('msg', '') logr.info(msg) data_asset_format_list = EdfDataAssetFormat.objects.order_by('data_asset_format_name') field_filter = DataAssetFormatFilter(request.GET, queryset=data_asset_format_list) context = {'data_asset_format_list': data_asset_format_list, 'filter': field_filter, 'msg':msg} return render(request, 'edf/data_asset_formats.html', context) In the template - edf/data_asset_formats.html <script> {% if msg %} var msg = '{{msg}}'; alert(msg); {% endif %} </script> As the url path param contains the optional argument whenever the filters are filtering on this form , the param is passed along and the alter is shown on any search. I want the template … -
Converting attributes of class to a django models subclass
I have a bunch of classes that I'm now trying to incorporate into django. For example, I have a Base class that all my other classes derive from: class Base: def __init__(self, label: str = 'Base'): self.label = label An example of a sublcass would be a Person class: from typing import Any, Dict class Person(Base): def __init__(self, name: str, attributes_to_options: Dict[str, Any], **kwargs): super().__init__(**kwargs) self.name = name self.attributes_to_options = attributes_to_options I would use this as: alex = Person(name='Alex', attributes_to_options={'age': 10, 'is_happy': True}, label='Person:Alex') My question is, how do I incorporate such a class into django? Is it as simple as inheritting from models.Model? e.g. from django.db import models class Person(Base, models.Model): def __init__(self, name: str, attributes_to_options: Dict[str, Any], **kwargs): super().__init__(**kwargs) self.name = name self.attributes_to_options = attributes_to_options But then how do I specify the models.CharField for the two attributes name and attributes_to_options? Thanks for any help here. -
Django uninstalled after installing django-debug-toolbar in docker container, how to install it without un installing django?
I was trying to install django debug toolbar in my container using [shub@debian teamwave](task-details-api)$ docker exec -it teamwave_backend_1 pip install django-debug-toolbar Collecting django-debug-toolbar Downloading https://files.pythonhosted.org/packages/01/9a/3db232bd15882d90d3c53de1f34ce0a522327849593c9198899713267cfe/django_debug_toolbar-1.11-py2.py3-none-any.whl (201kB) 100% |████████████████████████████████| 204kB 426kB/s Collecting sqlparse>=0.2.0 (from django-debug-toolbar) Downloading https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl Collecting Django>=1.11 (from django-debug-toolbar) Downloading https://files.pythonhosted.org/packages/61/cb/e3c6bfccdf23c48dd4ce014b96178aa048b9450739eaa5f11d4d23d9d5d6/Django-1.11.23-py2.py3-none-any.whl (6.9MB) 100% |████████████████████████████████| 7.0MB 544kB/s Requirement already satisfied: pytz in /usr/local/lib/python2.7/site-packages (from Django>=1.11->django-debug-toolbar) (2015.2) Installing collected packages: sqlparse, Django, django-debug-toolbar Found existing installation: sqlparse 0.1.15 Uninstalling sqlparse-0.1.15: Successfully uninstalled sqlparse-0.1.15 Found existing installation: Django 1.8.18 Uninstalling Django-1.8.18: I have tried running the container and installing the django Starting teamwave_backend_1 ... done Attaching to teamwave_backend_1 backend_1 | Traceback (most recent call last): backend_1 | File "manage.py", line 8, in <module> backend_1 | from django.core.management import execute_from_command_line backend_1 | ImportError: No module named django.core.management teamwave_backend_1 exited with code 1 I later fixed my django by docker-compose build but I want django-debug-toolbar too. This is my docker-compose.yml version: '3' services: db: image: postgres:10-alpine environment: - POSTGRES_PASSWORD=dsdbadmin - POSTGRES_DB=tm_v1.1 volumes: - pgdata:/var/lib/postgresql/data - ./docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d backend: build: . volumes: - .:/backend ports: - "8000:8000" depends_on: - db - redis redis: image: redis:4-alpine volumes: pgdata: And this is my Dockerfile FROM python:2 ENV PYTHONUNBUFFERED 1 WORKDIR /backend ADD req.txt /backend/ RUN pip install --upgrade …