Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Addition to the word category in various translations (programmatically)
In language dictionary books, there are abbreviations kind of: abbrev. abbreviation Aborig. Aboriginal adj. adjective adv. adverb Afr. African Afrik. Afrikaans ... ... ult. ultimately usu. usually v. verb var. variant vars variants W. West In my case I have to have same abbreviations but in different languages, lets say: | English | Germany | Spanish ult. ultimately | ult. letztendlich | ult. última usu. usually | usu. normalerweise | usu. general v. verb | v. verb | v. verb var. variant | var. variante | var. variante vars variants | vars varianten | vars variantes W. West | W. West | W. West From front-end side it will be something choosable in the form(dropdown/select) like: Detoxification - med. or detoxication (detox for short)[1] is the physiological or medicinal removal of toxic substances from a living organism So in wich way should I implement such a relationship? I have Word model class WordModel(models.Model): value = models.CharField(max_length=255) category = this should point to the abbreviations I could do this just creating Separate model like class AbbreviationModel: and define inside all attributes like: abr_eng = CharField descr_eng = CharField abr_ger = CharField descr_ger = CharField abr_spa = CharField descr_spa = CharField In … -
python manage.py migrate won't connect to separate postgresql inside another docker container
Good day, I have a docker-compose.yml that contains the setup for PostgreSQL and a Dockerfile for creating an image in for Django. When I run python manage.py migrate it throws an error: django.db.utils.OperationalError: could not translate host name "db" to address: Name does not resolve I'm new to Django, Docker, and PostgreSQL so I've search for some solutions online but no luck. docker-compose.yml version: "3" services: db: build: ./postgres volumes: - db-data:/var/lib/postgresql/data ports: - "5432:5432" env_file: - .dev.env networks: - backend redis: image: "redis:5.0-alpine" volumes: - redis-data:/data ports: - "6379:6379" networks: - backend networks: backend: volumes: db-data: redis-data: Dockerfile FROM python:3.6-alpine WORKDIR /usr/src/app COPY requirements.txt ./ RUN mkdir -p /root/.ssh/ ADD id_rsa /root/.ssh/id_rsa RUN chmod 700 /root/.ssh/id_rsa RUN echo "http://dl-cdn.alpinelinux.org/alpine/edge/testing">>/etc/apk/repositories\ && apk add --no-cache --virtual .build-deps gcc git openssh-client \ && apk add --no-cache musl-dev \ postgresql-dev \ jpeg-dev \ zlib-dev \ gdal-dev \ proj4 \ openssl-dev \ libmagic \ libffi-dev \ python3-dev \ musl-dev \ && ssh-keyscan github.com >> ~/.ssh/known_hosts \ && pip install --no-cache-dir -r requirements.txt # todo SHOULD NOT DO THE SSH KEYSCAN. SHOULD USE PUBLIC REPO INSTEAD COPY . . EXPOSE 8000 VOLUME ["/usr/src/app/storage"] CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] setting.py DATABASES = { 'default': { 'ENGINE': … -
How to Pre-cache rendered Django views with Workbox (URL Routing)
I'm using Workbox to pre-cache files for my Django Site. I'm struggling to setup the URL routing so that workbox will pre-cache fully rendered HTML Pages. I'm building the serviceworker.js as part of my Gulp task. This currently works for any .js or .css file and it properly injects the manifest into my serviceworker.js. The question is: How can I get Workbox to pre-cache html pages (along with dependency files like .js and .css) as rendered through Django's Views? Below, is my code to attempt to pre-cache the homepage (http://127.0.0.1:8000/). I'm sure that my setting for globDirectory is wrong. And since I'm using Djangos URL routing to render views I suspect I'll need to make axios call to that view? This is where the solution becomes unclear to me... // This file resides in [root directory]/GulpApp/Gulpfile.js: // This will precache all of the pages and inject them into the serviceworker.js for offline use gulp.task('service-worker', () => { return workboxBuild.injectManifest({ maximumFileSizeToCacheInBytes: 4 * 1024 * 1024, swSrc: '../browsepagesAPP/templates/browsepages/workbox-sw.js', swDest: '../browsepagesAPP/templates/browsepages/serviceworker.js', globDirectory: '../browsepagesAPP/', globPatterns: [ '**\/*.{js,css}', ], globIgnores: ['app-assets\/**'] }).then(({count, size, warnings}) => { // Optionally, log any warnings and details. warnings.forEach(console.warn); console.log(`${count} files will be precached, totaling ${size} bytes.`); }); }); … -
Django's MonthArchiveView returns "Table 'mysql.time_zone' doesn't exist"
I want to view the archive with the following URL: example.com/2019/06 example.com/2018/11 However, when accessed, django.db.utils.ProgrammingError: (1146, "Table 'mysql.time_zone' doesn't exist") is returned. If i change USE_TZ in settings.py to False, the error goes away and i can access it normally, but I don't want to False. urls.py path('<int:year>/<int:month>', ArchiveList.as_view(month_format='%m'), name='archive_list'), views.py class ArchiveList(MonthArchiveView): model = BlogPost template_name = 'blog/post_list.html' date_field = 'created_date' month_format = '%m' year_format = '%Y' allow_future = True def get_month(self): month = super(ArchiveList, self).get_month() return month def get_year(self): year = super(ArchiveList, self).get_year() return year settings.py USE_I18N = True USE_L10N = True USE_TZ = True What should I do now? -
Can I make the update code run late in Class View?
Can I make the update code run late in Class View? What I want is that update code must be executed first. because I have to update the user model before outputting the category list class MyShortcutListByCategory(ListView): def get_queryset(self): user = self.request.user.profile.shortcut_user_id # print("user : ", user) print("self.request.user : ", self.request.user) if user == "me": user = self.request.user else: user = User.objects.get(username=user) slug = self.kwargs['slug'] if slug == '_none': category = None else: category = Category.objects.get(slug=slug) pf = Profile.objects.filter(Q(user=self.request.user)).update(selected_category_id = category.id) print('category id update 성공') return MyShortCut.objects.filter(category=category, author=user).order_by('created') def get_context_data(self, *, object_list=None, **kwargs): context = super(type(self), self).get_context_data(**kwargs) context['category_list'] = Category.objects.all() context['posts_without_category'] = MyShortCut.objects.filter(category=None,author=self.request.user).count() slug = self.kwargs['slug'] if slug == '_none': context['category'] = '미분류' else: category = Category.objects.get(slug=slug) context['category'] = category return context update category = Category.objects.get(slug=slug) pf = Profile.objects.filter(Q(user=self.request.user)).update(selected_category_id = category.id) -
How to get only date after subtraction of two date field
I'm trying to have subtraction of two data fields and the result in days. But I'm having time also at the output. How do I get only days not the time. Here is my code: class ItemTable(models.Model): expdate = models.DateField("EXP Date", null=True, blank=True) def days_to_exp(self): if self.expdate: now = datetime.date.today() exp = str(self.expdate - now) if exp > "1": return exp elif exp < "1" and exp > "0": return "Today" else: return "Expired" output: 12 days, 0:00:00, 4 days, 0:00:00... etc I just want the result as: 12 days, 4 days..... etc -
How to calculate and show a sale value in a Django App/class?
So I'm quite new to Django and I have to make this little program ASAP. It basically consists of two apps, (Sales and Registration). In the Registration app, there is a class called Product that has three attributes: Name, Price, and Quantity (in stock). In the Sales app, there is a class of the same name that has four attributes: date, product, quantity (quantity of the same product that i'm selling) and seller (you can select one of the registered users). What I have to do is show the total value of the sale as soon as you select the product and the quantity of that product that you are selling. (Price * Quantity). If it's not clear, I'm trying to 'sell' via this class in the sales app. Later on I'll try to implement to reduce the quantity in stock and etc. Unfortunately, I simply don't know how to do it, and I'd appreciate any help. The total price can be shown after I click save, there's no problem with that. I am mainly concerned if it's even possible to obtain what's selected in 'product' to obtain its 'Price", before clicking in the Save option. (registration app) models.py from … -
django>=1.7 django.setup() is raising AppRegistryNotReady
I have a Django project which contains multiple apps and I'm in the middle of migrating this project to Django >=1.7. Model is successfully loaded for all the other app, however, one app keeps running into AppRegistryNotReady; Models aren't loaded yet. I googled and the most popular answer was os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xx.settings") then django.setup() at the __init__.py of the problematic app, but these are not helping and even setup() raises AppRegistryNotReady. This app hooked with lamson which I need to turn on this app in a different way (lamson start) than other apps and I guess this is why I have this problem? (i.e. this app can't connect to other apps) Any suggestion on how to approach this issue? -
Bootstrap Carousel with 3 objects Django implementation
I need a carousel displaying 3 team-member objects per slide. <div class="carousel-inner" role="listbox"> {% for m in memb %} {% if forloop.first %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <div class="row"> <div class="col-sm-4"> <div class="team-member"><img class="rounded-circle mx-auto" src="{{ m.image1.url }}"> <h4>{{ m.name1 }}</h4> <ul class="list-inline social-buttons" style="margin-top: 20px;"> <li class="list-inline-item"></li> <li class="list-inline-item"><a href="#{{ m.facebook1 }}"><i class="fa fa-facebook"></i></a></li> <li class="list-inline-item"><a href="#{{ m.instagram1 }}"><i class="fa fa-instagram"></i></a></li> </ul> </div> </div> <div class="col-sm-4"> <div class="team-member"><img class="rounded-circle mx-auto" src="{{ m.image2.url }}"> <h4>{{ m.name2 }}</h4> <ul class="list-inline social-buttons" style="margin-top: 20px;"> <li class="list-inline-item"></li> <li class="list-inline-item"><a href="#{{ m.facebook2 }}"><i class="fa fa-facebook"></i></a></li> <li class="list-inline-item"><a href="#{{ m.instagram2 }}"><i class="fa fa-instagram"></i></a></li> </ul> </div> </div> <div class="col-sm-4"> <div class="team-member"><img class="rounded-circle mx-auto" src="{{ m.image3.url }}"> <h4>{{ m.name3 }}</h4> <ul class="list-inline social-buttons" style="margin-top: 20px;"> <li class="list-inline-item"></li> <li class="list-inline-item"><a href="#{{ m.facebook3 }}"><i class="fa fa-facebook"></i></a></li> <li class="list-inline-item"><a href="#{{ m.instagram3 }}"><i class="fa fa-instagram"></i></a></li> </ul> </div> </div> </div> </div> </div> {% endfor %} <div><a class="carousel-control-prev" href="#carousel-3" role="button" data-slide="prev" style="width: 50px;"><span class="carousel-control-prev-icon border rounded-circle" style="background-color: #000000;"></span><span class="sr-only">Previous</span></a> <a class="carousel-control-next" href="#carousel-3" role="button" data-slide="next" style="width: 50px;"><span class="carousel-control-next-icon border rounded-circle" style="background-color: #000000;"></span><span class="sr-only">Next</span></a> </div> <ol class="carousel-indicators"> <li data-target="#carousel-3" data-slide-to="0" class="active"></li> <li data-target="#carousel-3" data-slide-to="1"></li> <li data-target="#carousel-3" data-slide-to="2"></li> </ol> </div> </div> I was unable to figure out how to … -
"[Errno 13] Permission denied" When trying to update/change a document only on Ubuntu server
When changing/updating infromation in the Admin backend of Django app, I'm met with a permission error. A couple of things to note: -It only happens when I try to upload a document, or change an entry with a document in it. -Adding/editing database entries with no files attached to them is fine! -On my local version, everything works fine. The next logical step for me is to check file/folder permissions, so I changed everything to on my testing server 'lrwxrwxrwx', including the uploads folder, the entirty of Python3.5 (I changed back after that did not solve it, I know it's pretty risky to leave it at all permissions). [Errno 13] Permission denied Request Method: POST Request URL: https://admin/inhouse/document/1704/change/ Django Version: 1.11 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied Exception Location: /usr/lib/python3.5/subprocess.py in _execute_child, line 1551 Python Executable: /home/ubuntu/.virtualenv/bin/python Python Version: 3.5.2 Python Path: ['/home/ubuntu/.virtualenv/lib/python35.zip', '/home/ubuntu/.virtualenv/lib/python3.5', '/home/ubuntu/.virtualenv/lib/python3.5/plat-x86_64-linux-gnu', '/home/ubuntu/.virtualenv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/ubuntu/.virtualenv/lib/python3.5/site-packages', '/home/ubuntu/foodlegal/foodlegal-repo', '/home/ubuntu/foodlegal', '/home/ubuntu/.virtualenv/lib/python3.5/site-packages/IPython/extensions'] And this is the function that is causing this entire issue @receiver(post_save, sender=Document) def convert_pdf_upload(sender, instance, **kwargs): if not instance.document_file: return current_path = settings.BASE_DIR+'/foodlegal/'+instance.document_file.url pdf_path = settings.BASE_DIR+'/foodlegal/uploads/documents/'+str(instance.id)+'.pdf' swf_path = settings.BASE_DIR+'/foodlegal/uploads/documents/'+str(instance.id)+'.swf' txt_path = settings.BASE_DIR+'/foodlegal/uploads/documents/'+str(instance.id)+'.txt' pdf2swf_path = settings.BASE_DIR+'/foodlegal/tools/pdf2swf' pdftotext_path = settings.BASE_DIR+'/foodlegal/tools/pdftotext' try: os.rename(current_path, pdf_path) except OSError: pass … -
Generate pdf of chart obtained through chart.js in django
I want generate pdf of a template containing chart generated through chart.js and also table ,I have used reportlab but I neither get chart generated through chart.js nor css is applied over the table in django ? -
gcc error when trying to download mysqlclient
I pretty much a complete beginner when it comes to databases and mysql so please forgive my lack of knowledge. I have been trying to migrate python models into a mysql database. When ever i issue the following command in terminal: (sl_env) Nolans-MBP:student_loans NolanMorrow$ python3 manage.py makemigrations I get django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.''' At which point i enter (sl_env) Nolans-MBP:student_loans NolanMorrow$ pip3 install mysqlclient and get the following error. Running setup.py install for mysqlclient ... error ... ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 -
how to fix: typeerror: 'Catg_id' is an invalid keyword argument
On running the above code, i get error "TypeError: 'Catg_id' is an invalid keyword argument for this function" for the function named as 'ch' above. How to fix this error? from categories.models import Catg, Type, Product, Choice from django.shortcuts import render def ch(request, Type_id, Product_id, Catg_id): ca = Catg.objects.get(pk=Catg_id) p = Type.objects.get(pk=Type_id) cho = Product.objects.get(pk=Product_id) alls = Choice.objects.all() context3 = { 'p': p, 'alls': alls, 'cho': cho, 'ca': ca, } return render(request, "service providers.html", context3) ALSO IN URLS.PY ```python url(r'^categories/(?P<Catg_id>[0-9])/(?P<Type_id>[0-9]+)/(?P<Product_id>[0-9]+)/$', views.Choice, name='choice'), AND IN MODELS.PY class Choice(models.Model): chname = models.ForeignKey(Product, on_delete=models.CASCADE) chn = models.CharField(max_length=1000, default=" ") def __str__(self): return self.chn -
Django queryset result not include newly added data in database
I use Django with Postgresql and my database exist before using Django. I follow this doc with command "python manage.py inspectdb" to generate the models. Then it works fine and all query result seems fine. However, after I use "psql" to import more records into tables. The result shows the newly added records are not included in queryset. For example, the "SELECT * FROM Table1" would have 8044 records. However, in Django, Table1.objects.raw('SELECT * FROM Table1') would only have 7149 records. Django version is 2.2 and Postgresql version is 11.2. I have run "python manage.py makemigrations" and "python manage.py migrate" but they intend to create some existing models again. I have turned on logging on both Django and Postgresql, and the log shows Django did send query to Postgresql. Below is example code to get all records from one table. getAllQs = Table1.objects.raw('SELECT * FROM Table1') I expect the length of queryset is the same as what is currently in database tables. -
How to fix "name 'self' is not defined" for a Django Singleton Model
I'm trying to create an editable Help page for users on my website using Django and Trumbowyg. What I'm trying to accomplish is: Only allowing a superuser to edit the page via a button visible to them Using the Trumbowyg editor to enter and edit the text Saving that text and then displaying it as html on the page Naturally, I thought that I should create a model for the HelpText which would hold the text put into the Trumbowyg editor. However, this model would have to be special in that there can only be one of them. So I turned to the Singleton Model. I followed this tutorial and created a SingletonModel model and subclassed it for my HelpText model like so. class SingletonModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): self.pk = 1 super(HelpText, self).save(*args, **kwargs) def delete(self, *args, **kwargs): pass @classmethod def load(cls): obj, created = cls.objects.get_or_create(pk=1) return obj class HelpText(SingletonModel): text = models.TextField(blank=True) However, after registering HelpText to my admin.py this gave me an error. the model s is abstract so it cannot be registered with admin.' model.__name__ From a couple of google searches, I found that the problem was that in class Meta, … -
Error when migrating: 'There is already an object named 'table_name' in the database.'
I'm getting this error when I'm trying to migrate on an Azure SQL Server db. This project also has a local mysql database and relationships between the two DB's but that doesn't seem to be at issue here I've tried deleting and squashing the migrations. I've tried --fake-initial. I have realized, though, that the issue is just that django isn't preventing itself from trying to create the table if it already exists during the migration. I'm curious if there's a setting to prevent django from just sending a create command during the migration if the table already exists. For now since I'm just developing I can just nuke the DB and start over, but this isn't going to work if I modify a column and try to migrate it in production Anyone run into this? -
How to upload files to S3 bucket from Django lambda deployment using Zappa?
I have a basic web application that allows users to upload files. There is no processing involved, I just need them to be stored in a specific Amazon S3 bucket. I have the application deployed using Zappa on AWS Lambda. The document upload functionality works perfectly on the local test server, but I am not sure how to make it work on the actual deployed instance. I get the same error if I directly try to add a file through the admin panel. Does anyone know what I'm doing wrong or how to get around this? I'll include the traceback here: File "/var/task/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/var/task/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/var/task/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/task/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/var/task/django/contrib/auth/mixins.py" in dispatch 52. return super().dispatch(request, *args, **kwargs) File "/var/task/django/contrib/auth/mixins.py" in dispatch 85. return super().dispatch(request, *args, **kwargs) File "/var/task/django/views/generic/base.py" in dispatch 97. return handler(request, *args, **kwargs) File "/var/task/django/views/generic/edit.py" in post 172. return super().post(request, *args, **kwargs) File "/var/task/django/views/generic/edit.py" in post 142. return self.form_valid(form) File "/var/task/myapp/views.py" in form_valid 83. return super(UploadView, self).form_valid(form) File "/var/task/django/views/generic/edit.py" in form_valid 125. self.object = form.save() File "/var/task/django/forms/models.py" in save … -
Django hosting on a domain
So far, the only websites I've put in a hosted domain were with PHP. But since I work with Django I wonder if there would be any "barrier" or trouble when it comes about hosting a project, since Linux and IOS have Python installed by default but Windows not. Also it would be necessary to install tools such as Django itself, pillow, mysqlclient, etc... I just want to know any possible barrier before going ahead. Thanks! -
Why doesn't JWT seem to recognize my created users in django
I'm setting up a project's back end using django rest framework I override django's default User by inheriting AbstractBaseUser (I use phone_number as a unique id) and i also created my own UserManager when I use simple jwt package for authentication I get the error message "No active account found with the given credentials" I had some debugging and saw that the user creation view works seamlessly and the user is indeed added to server but the jwt doesn't recognize it when i want to obtain token here is my user manager: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone_number, password, **extra_fields): if not phone_number: raise ValueError('The given phone must be set') user = self.model( phone_number=phone_number, **extra_fields, ) user.set_password(password) user.save(using=self._db) return user def create_user(self, phone_number, password=None, **extra_fields): # extra_fields.setdefault('is_superuser', False) return self._create_user(phone_number, password, **extra_fields) def create_superuser(self, phone_number, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(phone_number, password, **extra_fields) -
Can´t load more than 100 records in apache web server
I have an application that uses django rest framework, when I use django's web development server I can fetch up to 1000 records, but when I migrate the application to apache, I can only access ranges of 100 records (using pagination), otherwise, the request remains blocked and It never ends. Settings.py in development server REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 500 } Settings.py in apache server REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } Apache Alias /static/ /dashboard/equipment/project/static/ Require all granted <Directory /dashboard/equipment/project/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject processes=4 threads=2 python-home=/path_to/env/ python-path=/path_to/python_path WSGIProcessGroup myproject WSGIScriptAlias / /dashboard/equipment/project/dashboard_project/wsgi.py The apache server log does not show any errors, it only crashes because the request never ends -
Execute migrations in production but they are not created in my server
I try to create the migrations with the command but not copy the files sudo docker-compose -f production.yml run --rm django python manage.py makemigrations -
How do I properly pass JSON array to an HTML template in Django?
I want to certainly preface this question with "I'm a newb" I've been working with Python and Django for a short period of time now and I'm running into a problem passing JSON Arrays to my HTML Templates. The array that returns looks similar to this; [ { "id": "Tex" "color": "Purple" } ] The actually array is much larger but this will work for my example. Here is my Form. class PlayerForm(forms.Form): id = forms.CharField(max_length=100) def search(self): result = {} id = self.cleaned_data['id'] endpoint = 'https://api.littleleague.com/players/v1/path/{ID}/playertracking' url = endpoint.format(ID=id) headers = {'Authorization': settings.E_AUTH, 'Accept': "*/*", 'accept-encoding': "gzip, deflate", 'Connection': "keep-alive",} response = requests.get(url, headers=headers) if response.status_code == 200: # SUCCESS result = response.json() result['success'] = True else: result['success'] = False if response.status_code == 404: # NOT FOUND result['message'] = 'No entry found for "%s"' % id else: result['message'] = 'The API is not available at the moment. Please try again later.' return result Here is my Views: def player(request): search_result = {} if 'id' in request.GET: form = PlayerForm(request.GET) if form.is_valid(): search_result = form.search() else: form = PlayerForm() return render(request, 'app/player.html', {'form': form, 'search_result': search_result}) And here is my HTML Template: {% extends "app/layout2.html" %} {% block content %} … -
How to have single form on multiple pages
I am looking for ways to best handle a single form on multiple pages. Like how a newsletter signup might be on a home page, an about page, and several blog pages. I've handled this exact scenario in these 2 ways. Write an API (using DRF) that takes a POST request, and then point the normal HTML form at that API. This works, and is very flexible, but feels like overkill. Pass the form object into the context of each view I want the form to be on, and then include that into the template with includes form_snippet with form=form The first approach is more flexible with wagtail, wherein all that needs to happen on the admin side is an inclusion of the newsletter as a snippet, where the admin user is able to choose if they want the newsletter on the page or not. While both approaches work just fine, neither of them "feels" right, as I would think there is a simple way to do this without creating a big API, or passing around the form object to every single view. -
Logging the Activity Log in Django
Hi I am new to Django framework. I want to log all the incoming and outgoing request. I can see [11/Jun/2019 21:17:21] "GET /idealweight/1509196/ HTTP/1.1" 200 38 [11/Jun/2019 21:17:27] "GET /idealweight/1509196/ HTTP/1.1" 200 38 [11/Jun/2019 21:17:29] "GET /idealweight/1509196/ HTTP/1.1" 200 38 [11/Jun/2019 21:17:40] "GET /idealweight/1534042/ HTTP/1.1" 200 22 in the console but i don't know how to put them into the logs. I followed this example and I can see error logs clearly though. https://www.youtube.com/watch?v=Ypppo-7qrJY LOGGING = { 'version':1, 'disable_existing_loggers': False, 'formatters':{ 'large':{ 'format':'%(asctime)s %(levelname)s %(process)d %(pathname)s %(funcName)s %(lineno)d %(message)s ' }, 'tiny':{ 'format':'%(asctime)s %(message)s ' } }, 'handlers':{ 'errors_file':{ 'level':'ERROR', 'class':'logging.handlers.TimedRotatingFileHandler', 'when':'midnight', 'interval':1, 'filename':'logs/ErrorLoggers.log', 'formatter':'large', }, 'info_file':{ 'level':'INFO', 'class':'logging.handlers.TimedRotatingFileHandler', 'when':'midnight', 'interval':1, 'filename':'logs/InfoLoggers.log', 'formatter':'large', }, }, 'loggers':{ 'error_logger':{ 'handlers':['errors_file'], 'level':'WARNING', 'propagate':False, }, 'info_logger':{ 'handlers':['info_file'], 'level':'INFO', 'propagate':False, }, }, } Any idea how can I log all incoming and outgoing requests? Thanks -
Django Rest Framework : Pagination with annotated Queryset
I am currently doing a project which requires pagination. A list of Images is provided to the user and whether they were Favorited or not by user. Favorited Images are kept in a separate table. In order to provide a list of images and ones that were Favorited by the user an annotate. def _get_queryset(self, request): user_favorited = DjImagingImagefavorites.objects.filter(ifv_img_recordid__exact=OuterRef('pk'), ifv_user_id__exact=request.user.profile) queryset = DjImagingImage.objects.all().annotate(favorited=Exists(user_favorited)) return queryset Then in the list function def list(self, request): images = self._get_queryset(request) page = self.paginate_queryset(images) #Breaks here The Query then throws an error. ]Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. Due to an oddities of how the paginate function performs the count and constructs an illegal sql statement. Question is - Is their a better way about going to do this or should this work perfectly as I thought it should have?