Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load static css file inside extended template
I have a base.html file which contains the base of all of the HTML pages. I want to create 404.html page: {% extends 'base.html' %} {% block title %} Page 404 {% endblock title %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static '404_style.css' %}"/> {% block content %} <!-- HTML code here --> {% endblock content %} The tree: ./app/app |-- ./app/app/settings.py |-- ./app/app/static | |-- ./app/app/static/404_style.css | `-- ./app/app/static/style.css |-- ./app/app/templates | |-- ./app/app/templates/404.html | |-- ./app/app/templates/base.html | |-- ./app/app/templates/homepage.html |-- ./app/app/urls.py |-- ./app/app/views.py I don't understand why it does not load 404_style.css. My guess is that it is not inside the head tag (which is in base.html. So I tried to add {% block extra_head_content %}{% endblock %} inside the head tag inside base.html but it does not work. How can I load static css file inside extended template? -
Sort objects by interaction time grouped by users in Django
I have a Django app (I use Postgresql for the database), and I have these models of Customers, Products and Transactions that are connected as follows: class Customer(models.Model): products = models.ManyToManyField(Product, through='Transaction') class Product(models.Model): ... class Transaction(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) transaction_timestamp = models.DateTimeField(auto_now=True) The transaction model tracks the time when a customer interacted with a product. I have a list of user ID-s users. I want to get a list of say 1000 products they last interacted with for every customer in users. Is there any way of doing this faster than iterating all the users? I assume this might be done through Aggregation somehow, but I couldn't find anything that worked in my case. -
How to handle PUT request for a model with an extended user(onetoone field) relationship django rest framework
I have a profile model with a onetoone relationship with the django User model, I created an API endpoint which works fine for get and post request but when I try to do a put request to edit some part of the data, it gives me this error. { "user": [ "This field is required." ] } This is my Profile model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) This is my Serializer class class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id' ,'username', 'first_name', 'last_name', 'email', 'password') extra_kwargs = { "password": {"write_only": True}, } class ProfileSerializer(serializers.ModelSerializer): """ A student serializer to return the student details """ user = UserSerializer() class Meta: model = Profile fields = ('uid', 'user', 'bio', 'location') # read_only_fields = ('user',) def update(self, instance, validated_data): user_data = validated_data.pop('user') user = instance.user instance.bio = validated_data.get('bio', instance.bio) instance.location = validated_data.get('location', instance.location) instance.save() user.username = user_data.get('username', user.username) user.first_name = user_data.get('first_name', user.first_name) user.last_name = user_data.get('last_name', user.last_name) user.save() return instance -
How to install cruds_adminlte correctly?
I'm going round in circles here. I followed the basic installation instructions here, which seemed simple enough: pip install django-cruds-adminlte As I was reading the page from top to bottom (that's English) I then installed the following: pip install django-crispy-forms pip install easy-thumbnails pip install django-image-cropping pip install djangoajax I then started to hit a series of problems: 1: ModuleNotFoundError: No module named 'six' Applied this fix: $ pip install six 2: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Applied this fix: $ pip install --user --editable git+git://github.com/oscarmlage/django-cruds-adminlte/@0.0.17+git.081101d#egg=django-cruds-adminlte 3. django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'cruds_adminlte.templatetags.crud_tags': cannot import name 'six' from 'django.utils' (C:\Python\Python39\lib\site-packages\django\utils\__init__.py) Applied this fix: pip install six change templatestags/crud_tags.py line 11, from 'from django.utils import six' to 'import six' 4: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'crispy_forms.templatetags.crispy_forms_field': No module named 'django.utils.lru_cache' and, having re-read the documentation to learn that dependencies have to be installed first, decided to uninstall and start again: pip uninstall django-cruds-adminlte pip uninstall django-crispy-forms pip uninstall easy-thumbnails pip uninstall django-image-cropping pip uninstall djangoajax pip uninstall django-select2 This left me with the … -
How to set daily Update limit on Django model
I'm new to Django. I have created one Django App where users can update their Shift Timing(Morning/Evening/General) and based on this Shift Timing I am taking real-time data from Django Model and running Linux script which will be evaluating user shift timing and allowed timing to use the application. I have used Django import and export which allow the user to upload multiple users' data by using a .xls file from the front-end. Now here I want to apply some limit for example suppose my model is having 5000 records so I want that only 50% of its records should be allowed to modified whether it is added through .xls file or by clicking on update single records(I am doing this because I don't want that more than 50% of users should update Shift Timing). Is there any easiest way to implement this requirement? I have checked https://pypi.org/project/django-limits/ (django-limits 0.0.6)but did not understood from step 3. I am adding my models.py class CTS(models.Model): AConnectID = models.CharField(max_length=100,) Shift_timing = models.CharField(max_length=64, choices=SHIFT_CHOICES, default='9.00-6.00') EmailID = models.EmailField(max_length=64, unique=True, ) Vendor_Company = models.CharField(max_length=64, ) Project_name = models.CharField(max_length=25, default="") SerialNumber = models.CharField(max_length=19, default="") Reason = models.TextField(max_length=180) last_updated_time = models.DateTimeField(auto_now=True) class Meta: ordering = ['-id'] def … -
IntegrityError UNIQUE on blog_post.slog despite creating unique slug function
I am new to django and somewhat new to python too. I am trying to create a simple blog application and as we all know you want to have unique slugs for your blog links. However I cannot seem to rid myself of this UNIQUE error. Problem description When I create a blog post I create a slug from the title. Then I see if that slug matches any others in the database. If it does, I add a little string to the end. Nevertheless, the database keeps throwing an IntegrityError. What I've tried I have been using import pdb; pdb.stack_trace() to try to trace the issue. It seems to me to happen after setting self.object.slug and then doing self.object.save(). Somehow the unique slug is may not be be being passed to save.(). But I'm not sure how to debug beyond this point. I'd appreciate help in the debugging process. The confusing thing is that I'm working from a (functioning) django blog app. I cannot find the difference between my code and that one, and I've tried changing the methods.py and views.py to match that of the other blog, and yet that app produces unique slugs and throws no errors, … -
Django / Visual Studio Class has no Object Errro
I am receiving the following error in my Visual Studio code. There are no errors in my models.py file that this views.py file draws from, but when I debug in views.py in visual studio I get this error. Based on other posts, I've pip installed pylint but that has not resolved the issue. Any suggestions on how to resolve this? view.py from .models import Question, Owner, Stakeholder class StakeholdersView(generic.ListView): template_name = 'polls/stakeholders.html' context_object_name = 'stakeholder_list' def get_queryset(self): return Stakeholder.objects.order_by('id') Class 'Stakeholder' has no 'objects' member -
#djangoMigrationerror #manage.pyError
Currently I'm using Django 3.1.4 and when I migrate or make migrations, it was able to do the migration, but it also show this following message (please note that mysite is the name of app that I making on project): No changes detected in app 'mysite' Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable` python manage.py makemigrations mysite No changes detected in app 'mysite' Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, … -
Django AppRegistryNotReady Exception after import from django.contrib.auth.models
Here is my folder structure: . ├── app ├── project ├── scripts └── tests ├── fuctional -> test_views.py └── unit Here is my test_script.py from django.test import TestCase from django.urls import reverse from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password from rest_framework.test import APIClient from mrx.views import LoginView, LogoutView When I launch python -m unittest tests/fuctional/test_views.py I get this error: Traceback (most recent call last): File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/runpy.py", line 86, in _run_code exec(code, run_globals) File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/__main__.py", line 18, in <module> main(module=None) File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/main.py", line 147, in parseArgs self.createTests() File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/main.py", line 158, in createTests self.test = self.testLoader.loadTestsFromNames(self.testNames, File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/loader.py", line 220, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) File "/home/edx/PycharmProjects/mrx_3/tests/fuctional/test_views.py", line 3, in <module> from django.contrib.auth.models import User File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/apps/registry.py", line 136, in … -
Calling other docker container by name doesn't work when using Nginx (Docker, Django, React/Next.js)
I am working on a project with Docker using Django in the backend and Next.js in the front. I currently have it working without using Nginx by binding the ports of each container to the host machine's port 8000 and 3000 respectively, with the Next.js's serverside calling from environment variable set as 'backend:8000/users/auth_api/google/' for authentication (backend is the container name for the backend). However, upon including Nginx, it doesn't seem to work anymore. I had to include a '/backend/' prefix to my backend container with the proxy_pass setting as I intend for the root '/' to be for the frontend. I've tried setting different environment variables and verified that uri call from the serverside from the logs but it just doesn't reach the backend (logs show that the api call to the environment variable uri was made by the frontend but not received by the backend meaning the api uri is wrong). Environment variables I've tried: SS_BACKEND_GOOGLE_AUTH=http://0.0.0.0:8000/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://0.0.0.0:8000/backend/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://backend:8000/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://backend:8000/backend/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://backend/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://backend/backend/users/auth_api/google/ Docker-compose file version: '3.8' services: backend: restart: unless-stopped build: context: ./backend dockerfile: Dockerfile.test command: sh entrypoint.prod.sh container_name: backend expose: - 8000 ports: - 8000:8000 volumes: - ./backend/:/usr/src/backend/ - static_volume:/usr/src/backend/staticfiles - media_volume:/usr/src/backend/mediafiles env_file: - ./.env.test depends_on: - db - … -
How do I solve a python cursor connection error?
Performing system checks... System check identified no issues (0 silenced). Traceback (most recent call last): File "G:\Shares\Website\Development\Intranet\HealthcareProject2\manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\commands\runserver.py", line 104, in run self.inner_run(None, **options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\recorder.py", line 61, in applied_migrations if self.has_table(): File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\backends\base\base.py", line 255, … -
I get 'django.db.utils.IntegrityError: FOREIGN KEY constraint failed' when attempting to load json data
I am trying to load some data from a json file into the website,but whenever i type required commands and want to save , i get the following error: Traceback (most recent call last): File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\backend\website1\test\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 3, in <module> File "C:\backend\website1\test\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "C:\backend\website1\test\lib\site-packages\django\db\models\base.py", line 790, in save_base updated = self._save_table( File "C:\backend\website1\test\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\backend\website1\test\lib\site-packages\django\db\models\base.py", line 933, in _do_insert return manager._insert( File "C:\backend\website1\test\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\backend\website1\test\lib\site-packages\django\db\models\query.py", line 1254, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\backend\website1\test\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql cursor.execute(sql, params) File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\backend\website1\test\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 84, in _execute … -
Django+ HTML: how do i filter my own post away such that I am only querying other people's post and not my own posts
does anyone know how I can filter away my own blog posts so that only other people's blog posts are shown? I roughly know you need to use filter() but im unsure of what I must put into the function. Pls Help! Please let me know if you require more information :) def home_feed_view(request, *args, **kwargs): context = {} blog_posts = BlogPost.objects.all() context['blog_posts'] = blog_posts type_of_tinc = TypeoftincFilter(request.GET, queryset=BlogPost.objects.all()) context['type_of_tinc'] = type_of_tinc paginated_type_of_tinc = Paginator(type_of_tinc.qs, 4) page = request.GET.get('page') tinc_page_obj = paginated_type_of_tinc.get_page(page) context['tinc_page_obj'] = tinc_page_obj return render(request, "HomeFeed/snippets/home.html", context) models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField(max_length=5000, null=False, blank=False) slug = models.SlugField(blank=True, unique=True) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) -
Why Nginx add "?next=" for my URL on Django Webapp
My Django have 5 apps central, mails, insure, redbooks, dshop urls.py urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='central/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(next_page='login'), name='logout'), path('home/', c_view.home, name='home'), path('mails/', include('mails.urls')), path('insure/', include('insure.urls')), path('redbooks/', include('redbooks.urls')), path('dshop/', include('dshop.urls')), path('adminpage/', admin.site.urls), ] My Django deployed on Digital Ocean https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 Run with $ python manage.py runserver 0.0.0.0:8000, WORKS FINE also $ gunicorn --bind 0.0.0.0:8000 lskweb.wsgi, WORKS FINE but When Nginx started with basic config sudo nano /etc/nginx/sites-available/lskweb server { listen 80; server_name 68.183.111.111; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/pawin/lskweb-ocean; } location / { include proxy_params; proxy_pass http://unix:/home/pawin/lskweb-ocean.sock; } } Nginx add "?next=" in front of my Django url ex. http://68.183.111.111/?next=/home/ instead of http://68.183.111.111/home/ http://68.183.111.111/?next=/mails/ instead of http://68.183.111.111/mails/ but when i click browser go back and click link again sometime nginx give the correct url in one click sometime more clicks .. for Now, my landing page is http://68.183.111.111/login/ (type in browser addr box) is OK /static/ no problem its serv files OK sorry for my English language. Thank you for your helps :) -
Django count using raw query
I'm having a trouble on how can I count query in Django raw using this query below. This is what should looks like.I just want to count number of paid. It would be great if anybody could help me thanks in advance!. rpts_paid_count.append(p.paid).count() #Error AttributeError: 'NoneType' object has no attribute 'count' What I've tried in Django rpts_paid_count = [] blank = "" for p in Person.objects.raw('SELECT * FROM app_person WHERE paid_by != %s GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid', [blank]): rpts_paid_count.append(p.paid).count() #Error Part results = {'rpts_paid_count':rpts_paid_count} return JsonResponse(results) -
TypeError: expected string or bytes-like object in Django
I'm learning django and testing how it works with API and currently I'm trying to display records from an localhost API, but it seems like I missed something def fetchapi_patients(request): url = 'http://localhost:8000/core/users/roles/superuser' headers={"Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDYzMDg3MzYsImlkIjoiYWRtaW4iLCJvcmlnX2lhdCI6MTYwNjMwNTEzNn0.J2wBp8ecA9TebP6L73qZ1OZmo02DwQy9vTySt0fil4c"} response = requests.get(url, headers=headers) #Read the JSON patients = response.json() #print(patients) #Create a Django model object for each object in the JSON and store the data in django model (in database) for patient in patients: #print(patient['ID']) Patient.objects.create(first_name=patient['first_name'], last_name=patient['last_name'], email=patient['email'], coreapi_id=patient['ID'], created_date=patient['CreatedAt']) return JsonResponse({'patients': patients}) #return HttpResponse('ok') I tried different thing to make it work and I end up to test if it prints something with print(patients) and this gives the list in the terminal from my localhost API, and I found that the API works, but can't find why they don't printed in my frontend part of the websystem. This is my model for Patient: class Patient(models.Model): coreapi_id = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) language = models.CharField(max_length=20) created_date = models.DateTimeField(default=True) lastmodified_date = models.DateTimeField(default=True) def str(self): return self.email and my jquery script for visualization: // load the database with fetchapi from database $(document).ready(function() { var data; fetch("http://192.168.2.85:7575/fetchapipatients/") .then(response => response.json()) .then(json => data = json) .then(() => {console.log(data); $('#datatable').DataTable( { data: … -
production issue: sqlite3 to postgresql migration issue in django
I am trying to migrate my django project from sqlite3 to postgresql. I have done this succesfully in development but getting errors in production. i have used this command to create dumps: manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json then i changed database in my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } then i exclude contenttypes as follow: python3 manage.py shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() but i am getting this error: django.db.utils.IntegrityError: Problem installing fixtures: insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_content_type_id_c4bce8eb_fk_django_co" DETAIL: Key (content_type_id)=(7) is not present in table "django_content_type". please help -
Styling django filter form in html
Here's how my django filter form currently looks: And here's my html code: <form action="" method="get" class="form-inline"> {{myfilter.form|bootstrap}} <button class="btn btn-primary" type="submit"> Search</button> </form> I am having trouble with the following: How do I bring the filters in center of the page? How do I change the "Name contains" to "Name"? How do I change the color of text to white in order to make them more visible? I have tried to search it online but no luckk. Little help will be appreciated. THANKS! -
Get initial value on nested serializer with many=True
class SomeSerializer(ModelSerializer): class Meta: fields = ("currency", "amount") model = SomeModel def get_amount(self, value): if getattr(self, "initial_data", None): currency = self.initial_data.get("currency") # for a case when serializer used directly else: currency = self.root.initial_data[self.source]["currency"] # for a case when serializer is nested # do some stuff return amount My serializers works fine, bith when is's used directly or as nested serializer. Here is serializer that uses previous one as nested: class OperationSerializer(Serializer): ... operation = SomeSerializer() Everything works fine until I try to use OperationSerializer with many=True. In this case I cannot get initial value of currency, because I need to specify an index for the root element which is not known for me. -
How to hide Python & Django technologies from Wappalyzer
I have a Django site and I want to hide Python and Django technologies from the eyes of Wappalyzer hackers. I've been searching this topic in the net and found nothing useful. How can I do that in Django version 3 and python version 3.7? How to do that in different versions of Django and python? Any help would be appreciated. -
whats the most sensible way of keeping the current user when using mobile auth on login?
I want mobile auth on login, but am wondering what the best way would be to store the current user, before giving them a session id (which would be granted on successful mobile auth). does it make sense to store a jwt in cookies for the user after they enter their password, while they're on the 2fa auth page? I've looked at a few sites with 2fa, and cant see any that do this, so figure there must be a better way? -
Django RecursionError on A2 Hosting server with basic project
I recently set up Python hosting for my Django application. I used A2Hosting with cPanel, and followed these instructions that they gave. So now I have a Django project and application, with a few modifications they asked for; I can confirm that the app is running, but… Now I'm doing the standard procedure, creating a simple HttpResponse view, creating an app-local urls.py, linking that urls.py to the project-wide urls.py, and removing this url block that they had me use, which WORKS, but I really don't want to render the templates raw like this: url(r'^$', TemplateView.as_view(template_name='static_pages/index.html'), name='home'), Well now I'm getting this error: (DOMAIN, APP, and USERNAME removed for privacy) RecursionError at / maximum recursion depth exceeded while calling a Python object Request Method: GET Request URL: http://APP.DOMAIN.TLD/ Django Version: 3.1.4 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded while calling a Python object Exception Location: /home/USERNAME/virtualenv/APP/3.7/lib/python3.7/site-packages/django/urls/resolvers.py, line 258, in match Python Executable: /home/USERNAME/virtualenv/APP/3.7/bin/python Python Version: 3.7.8 Is my version too high? I assumed the documentation just used lower numbers because it hasn't been updated in a while. -
Channels_redis causing the error AttributeError: 'Redis' object has no attribute 'bzpopmin'
I am facing the following error message on my Django application: Exception inside application: 'Redis' object has no attribute 'bzpopmin' Traceback (most recent call last): File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/routing.py", line 160, in __call__ send, File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/utils.py", line 58, in await_many_dispatch await task File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/utils.py", line 50, in await_many_dispatch result = task.result() File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels_redis/core.py", line 469, in receive real_channel File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels_redis/core.py", line 524, in receive_single index, channel_key, timeout=self.brpop_timeout File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels_redis/core.py", line 361, in _brpop_with_clean result = await connection.bzpopmin(channel, timeout=timeout) AttributeError: 'Redis' object has no attribute 'bzpopmin' This seems to be after a WebSocket connection is created with the WebSocket disconnecting after the error is thrown. At first I tried other, similar, issues that were caused by … -
MultiValueDictKeyError Django : Uploading Image from HTML Form
I've included MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') URL in urls.py enctype="multipart/form-data" request.FILES["find"] ::find is the name of input. user = Register.objects.get(id=pk) user.profile_pic = request.FILES["find"] But it is not giving the error MultiValueDictKeyError at /updateUserData/7/ -
How can I change text displayed when user put wrong data?
I'm working in Python (django) now. I'm building a simple login page. I'm working with forms, and I want to add an infromation (ex. "Your data is wrong") when user put invalid username or password. How can I do it? Where can I change it?