Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the JSON object must be str, not 'bytes'-django for user validation
I have three different fileds username,password and role if all these three values matches then user will be able to login else he will not be able to login. def loginemployee(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) payload = body['username'] passwordcheck = body['password'] rolecheck = body['role'] if payload: employee=models.Employees.objects.filter(Q(username=payload['username']) & Q(password=passwordcheck['password']) & (Q(role=rolecheck['role']) | Q(backup_role=payload['role']))) # employees1=models.Employees.objects.filter(Q(email=payload['username']) & Q(role=payload['role'])) # empl=(employee+employees1); if employee: emp = serializers.serialize('json', employee) return HttpResponse(emp,content_type='application/json') can you help me the fix the issue in the above code. -
Pyhton/Django: I need some code to run between requests, which concept to look for?
I am trying Django for my project, which contains server-side code, which should work between requests. It should be initialized at server start, keep state, and polled sometimes between HTTP requests. I can write own server with python http.server but it seems overkill at the moment, simple (Django built-in HTTP) server is ok for my project for now. Which is simplest way to implement server-side code for typical Django project? -
Nginx whitelist API requests from server as client, block all others
I have a Django application with a couple of API endpoints using Django Rest Framework that I want to only be accessible by the Django application itself. I'm trying to restrict access those endpoints via nginx but everything I've tried either results in a 403 fobidden response on all clients or is able to be accessed by all clients. Below is my nginx config. I've also tried replacing 127.0.0.1 with the IP of the server but that results in the same responses mentioned above. upstream app_server { server 127.0.0.1:9000 fail_timeout=0; } upstream api_server { server 127.0.0.1:9001 fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; location /endpoint1/ { allow 127.0.0.1; deny all; } location /endpoint2/ { allow 127.0.0.1; deny all; } location /static/ { autoindex on; alias /path/to/static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } TL;DR I have a Django API that should only accept requests from the Django app running alongside it. What is the best way to accomplish that? -
Safari recognises JavaScript files as "text/plain"
I'm using Mezzanine 4.2.3 running on Django 1.10.8. JavaScript files load fine on Chrome, Firefox, Opera, and Edge. But Safari doesn't recognise them. In Network in Web Inspector, every JS file is recognised as "text/plain". Based on various solutions I've read, I've added type="text/javascript", and then type="application/javascript", like so: {% compress js %} <script type="application/javascript" src="{% static "mezzanine/js/"|add:settings.JQUERY_FILENAME %}"></script> <script type="application/javascript" src="{% static "js/bootstrap.js" %}"></script> <script type="application/javascript" src="{% static "js/bootstrap-extras.js" %}"></script> ... {% endcompress %} I have this at the top of the template too: <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> ... </head> Neither works. Console shows no errors. CSS files are recognised as "text/plain" too, but they actually load perfectly. What else should I try? -
With Django AnyMail with MailGun, does the MAILGUN_SENDER_DOMAIN have to match the domain in the DEFAULT_FROM_EMAIL?
Consider the following settings.py snippet from https://github.com/anymail/django-anymail: INSTALLED_APPS = [ # ... "anymail", # ... ] ANYMAIL = { # (exact settings here depend on your ESP...) "MAILGUN_API_KEY": "<your Mailgun key>", "MAILGUN_SENDER_DOMAIN": 'mg.example.com', # your Mailgun domain, if needed } EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" # or sendgrid.EmailBackend, or... DEFAULT_FROM_EMAIL = "you@example.com" # if you don't already have this in settings In this example, both the MAILGUN_SENDER_DOMAIN and DEFAULT_FROM_EMAIL have the domain example.com. We've recently made a change such that the two domains are different, and it seems that I am no longer able to send emails using the AnyMail backend. My theory is that MailGun 'enforces' the two domains to be the same, but it is not clear to me from the documentation whether this is indeed the case. Can anyone confirm whether this is required? -
Django how to read a file in the app subdirectories folder?
I am using Django to build a Web application, and there is python module inside the app folder. This python module needs to interact with yaml in the subdirectories "input" and "output". map_local_path = "./input/map.yaml" I just tried to read this path, it will work at my local spyder ide, but it wont work when it comes to Django. I want to call my own python module api in views.py, and what I am doing is to: openFile = open("./input/map.yaml", "r") and I cannot make it work at Django. How can I fix it? T_T Thanks! IOError: [Errno 2] No such file or directory: './input/map.yaml' -
difference between Django Spatial Field Types
I am going to use one of Spatial fields in my project but I don't know the difference between all of them, the Django documentation has two example(PolygonField and RasterField) model: from django.contrib.gis.db import models class Zipcode(models.Model): code = models.CharField(max_length=5) poly = models.PolygonField() class Elevation(models.Model): name = models.CharField(max_length=100) rast = models.RasterField() database api example: >>> from zipcode.models import Zipcode >>> z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))') >>> z.save() >>> from elevation.models import Elevation >>> dem = Elevation(name='Volcano', rast='/path/to/raster/volcano.tif') >>> dem.save() I wanna example code for other fields to understand them : GeometryField PointField LineStringField MultiPointField MultiLineStringField MultiPolygonField GeometryCollectionField -
Edit django 'through' model inline in wagtail admin?
As per the title I am trying to allow for inline editing for a very simple shop page in Wagtail (will probably make it into a simple package): With the following models: class Order(ClusterableModel): fields... class Product(ClusterableModel): fields... class OrderProducts(Orderable): product = ParentalKey(Product, related_name='chosen_products') order = models.ForeignKey('Order') quantity = models.PositiveIntegerField() panels = [ Fieldpanels... ] class OrderModelAdmin(ModelAdmin): model = Order menu_label = 'Orders' ... modeladmin_register(OrderModelAdmin) The tricky thing is that I get the error Cannot set values on a ManyToManyField which specifies an intermediary model. Or I simply don't get an inline panel, but rather a select. I am assuming this is the case because the create and add methods do not work on through models, is that the case? If so could you suggest a way I can rewrite the app so as to allow me to create orders with products in the admin and in my code? -
How can I read a URL without using urlib2.urlopen in Python?
I've been reading and displaying a Facebook Graph api url form the Facebook Graph API like this: facebook_info = urllib2.urlopen("https://graph.facebook.com/%s/me?fields=first_name,last_name,email&access_token=" % settings.FACEBOOK_API_VERSION + access_token) facebook_info = facebook_info.read() return facebook_info I was wondering if there is a better way to do this in Python I was thinking something like Request.get(...). Where I don't use urllib2.urlopen and the the '+' sign to concatenate. -
Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order:
I've been going through the Tango With Django 1.7 guide and I've come up with the following issue that I'm having troubles fixing: Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order: 1. ^$ [name='index'] 2. ^about/$ [name='about'] 3. ^category/(?P<category_name_slug>[\w\-]+)/$ [name='category'] 4. ^admin/ 5. ^rango/$ 6. ^about/ 7. ^category/ 8. ^media/(?P<path>.*) The current URL, rango/category/python, didn't match any of these. This is my rango/urls.py file from django.conf.urls import patterns, url from rango import views urlpatterns = patterns(' ', url(r'^$', views.index, name='index'), url(r'^about/$', views.about, name='about'), url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category') ) In tango_with_django_project/urls.py I have from django.conf.urls import patterns, include, url from django.contrib import admin from rango import views from django.conf import settings urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^about/$', views.about, name='about'), url(r'^admin/', include(admin.site.urls)), url(r'^rango/$', include('rango.urls')), url(r'^about/', include('rango.urls')), ) if settings.DEBUG: urlpatterns+= patterns( 'django.views.static', (r'^media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}), ) In rango/views.py I have: from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render from rango.models import Category from rango.models import Page def index(request): category_list = Category.objects.order_by('-likes')[:5] context_dict = {'categories': category_list} return render(request, 'rango/index.html', context_dict) def about(request): return HttpResponse("Rango says: Hello world! <br/> <a href='/rango/about'>About</a>") def category(request, category_name_slug): context_dict = {} try: category = Category.objects.get(slug=category_name_slug) context_dict['category_name'] = … -
Pre populating editable fields in the django admin from other table
this is the django admin panel with a table named Committees. there is a field named committee type in committees table. There is a table named default, with the model defined below, class default(models.Model): committee_type = models.CharField() description = models.CharField() quorum = models.InetgerField() What i wanted to do is, 1) when i select the committee type to city council in committees table in admin(like in screenshot), I wanted to populate the description and quorum from the default table in to the description and quorum in committees table in the admin itself 2) these populated data should be retrieved from default table where the committee type is city council 3) these fields should be editable in the committees table in admin after getting populated from the default table and should be able to be saved in this committee object Thanks in advance! -
'int' object has no attribute '_committed' Django
I'm trying to add 5 image field to my table, 3 are required and 2 are not .. I get the error when I try to upload only 3 images,, but everything is fine when I upload 5 images. here are my files : models.py where the main table is created : class Item(models.Model): # custom validators alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') # fields dress_name = models.ForeignKey(Name, on_delete=models.DO_NOTHING, blank=False, verbose_name='نوع الفستان',) dress_rate = models.ForeignKey(Rate, on_delete=models.DO_NOTHING, blank=False, verbose_name='تصنيف الفستان',) dress_size = models.ForeignKey(Size, on_delete=models.DO_NOTHING, verbose_name='مقاس الفستان', blank=False) dress_color = models.CharField(max_length=50, verbose_name='لون الفستان', blank=False) dress_description = models.TextField(max_length=800, verbose_name=' وصف إضافى للفستان', blank=False, default='وصف الفستان') dress_image1 = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, blank=False, verbose_name='الصورة الأساسية للفستان', help_text='لا يمكنك تركها فارغة',default=1) dress_image2 = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, blank=False, verbose_name='صورة إضافية ',default=1) dress_image3 = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, blank=False, verbose_name='صورة إضافة ',default=1) dress_image4 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, blank=True, verbose_name='صورة إضافة ',default=1) dress_image5 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, blank=True, verbose_name='صورة إضافة ',default=1) dress_action = models.ForeignKey(Action, on_delete=models.DO_NOTHING, verbose_name='الفستان معروض لل ', help_text='للبيع او للإيجار ', blank=False) dress_price = models.IntegerField(default=1, verbose_name='السعر', blank=False) dress_mobile = models.CharField(max_length=20, validators=[alphanumeric], verbose_name='رقم الهاتف ', blank=False) created_by = models.CharField(max_length=250,) created_username = models.CharField(max_length=250, default='unknown') created_at = models.DateTimeField(auto_now=True) dress_active = models.BooleanField(default=False) dress_special = models.BooleanField(default=False) dress_town = models.ForeignKey(Town, on_delete=models.DO_NOTHING, verbose_name='المحافظة', blank=False) views.py where the view … -
Django migrations - django.db.migrations.exceptions.NodeNotFoundError
I get the following error when I run any python manage.py function: raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0010_user_following dependencies reference nonexistent parent node ('accounts', '0002_auto_20180615_2021') It happened after I tried to reset my migrations by manually deleting the migration files in the migration folders (except the init files - no other files are left in the migration folders). I have tried dropping the database with python manage.py flush, which also doesn't run. Any suggestions? Thanks! -
Django graphene relay restricting queries to objects owned the user
I am doing the graphene tutorial on filtering with relay from: http://docs.graphene-python.org/projects/django/en/latest/filtering/ where the user is restricted to query objects that they previously created. class AnimalFilter(django_filters.FilterSet): # Do case-insensitive lookups on 'name' name = django_filters.CharFilter(lookup_expr=['iexact']) #changed this to work class Meta: model = Animal fields = ['name', 'genus', 'is_domesticated'] @property def qs(self): # The query context can be found in self.request. return super(AnimalFilter, self).qs.filter(owner=self.request.user) I am having an inserting the self.request.user part, where the user data is loaded. When I do a query like: query { allAnimalss { edges { node { id, name } } } } I get an error in the query field: { "errors": [ { "message": "'NoneType' object has no attribute 'user'", "locations": [ { "line": 2, "column": 3 } ] } ], "data": { "allAnimals": null } } If I remove the filter it works fine. The tutorial mentioned "owned by the authenticated user (set in context.user)." what does this mean? I tried adding a get_context_data function to the views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user'] = self.request.user return context and also changing self.request.user to self.context.user but it does not work -
Django Server Error When First Loading App
I am new to programming. So bear with me. I am following a tutorial to learn Django and Python. I tried to start running a server to see if my basic app would work, but I get the below error. I welcome any guidance you can provide. tom-python@linux:~/todolist$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f58d8103d08> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 540, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 533, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked … -
django update_or_create gets "duplicate key value violates unique constraint "
Maybe I misunderstand the purpose of Django's update_or_create Model method. Here is my Model: from django.db import models import datetime from vc.models import Cluster class Vmt(models.Model): added = models.DateField(default=datetime.date.today, blank=True, null=True) creation_time = models.TextField(blank=True, null=True) current_pm_active = models.TextField(blank=True, null=True) current_pm_total = models.TextField(blank=True, null=True) ... more simple fields ... cluster = models.ForeignKey(Cluster, null=True) class Meta: unique_together = (("cluster", "added"),) Here is my test: from django.test import TestCase from .models import * from vc.models import Cluster from django.db import transaction # Create your tests here. class VmtModelTests(TestCase): def test_insert_into_VmtModel(self): count = Vmt.objects.count() self.assertEqual(count, 0) # create a Cluster c = Cluster.objects.create(name='test-cluster') Vmt.objects.create( cluster=c, creation_time='test creaetion time', current_pm_active=5, current_pm_total=5, ... more simple fields ... ) count = Vmt.objects.count() self.assertEqual(count, 1) self.assertEqual('5', c.vmt_set.all()[0].current_pm_active) # let's test that we cannot add that same record again try: with transaction.atomic(): Vmt.objects.create( cluster=c, creation_time='test creaetion time', current_pm_active=5, current_pm_total=5, ... more simple fields ... ) self.fail(msg="Should violated integrity constraint!") except Exception as ex: template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) self.assertEqual("An exception of type IntegrityError occurred.", message[:45]) Vmt.objects.update_or_create( cluster=c, creation_time='test creaetion time', # notice we are updating current_pm_active to 6 current_pm_active=6, current_pm_total=5, ... more simple fields ... ) count = Vmt.objects.count() self.assertEqual(count, 1) … -
How to get Task ID in celery django from the currently running Shared Task itself?
In my views.py I am using celery to run a shared task present in tasks.py. Here is how I call from views.py task = task_addnums.delay() task_id = task.id tasks.py looks as from celery import shared_task from celery.result import AsyncResult @shared_task def task_addnums(): # print self.request.id # do something return True Now, as we can see we already have task_id from task.id in views.py . But, Let's say If I want to fetch task id from the shared_task itself how can I ? The goal is to get task id from the task_addnums itself so I can use that to pass into some other function. I tried using self.request.id considering the first param is self . But it didn't worked. -
get the session time in django rest framework
I am a really new bird to python and using Django rest framework. I have followed the tutorial "http://www.django-rest-framework.org/tutorial/quickstart" and created a login logout page for admin. I wanted to track the session time or basically for how long the user has been logged in, I tried doing the same by following many tutorials like these 'https://github.com/GetBlimp/django-rest-framework-jwt' but I think I'm deviating from what I want, please suggest any tutorial or any help. Thanks -
python manage.py migrate (error)
I have trouble when I execute the command python migrate.py migrate. I'm learning a little about django, and I need synchronize django with a mysql database. In settings.py file, I put the right database, username and root password, I don't know why is not having access for root. So here's my error: (Ambientepython3) leonardo.oliveira@dss-skinner:~/django-tutorials/mysite$ python manage.py migrate Traceback (most recent call last): File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 229, in get_new_connection return Database.connect(**conn_params) File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/MySQLdb/init.py", line 86, in Connect return Connection(*args, **kwargs) File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in init super(Connection, self).init(*args, **kwargs2) _mysql_exceptions.OperationalError: (1698, "Access denied for user 'root'@'localhost'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/home/leonardo.oliveira/django-tutorials/Ambientepython3/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check … -
Django Rest Framework API Testing PUT getting unexpected argument
I have been writing tests for my Kanban-style board application and have run in to a seemingly unusual problem. The APIClient put() function is giving me an unusual error. I have done the rest of my endpoint testing in the same way but for some reason it is when I provide 3 arguments to format that it complains. Perhaps I am not seeing something simple. test_views.py excerpt def test_api_can_update_a_comment(self): response = self.client.put( '/api/v1/boards/{board_pk}/cards/{card_pk}/comments/{comment_pk}/'.format(board_pk=self.board.pk, card_pk=self.card.pk, comment_pk=self.comment.pk), { "message": "Test Message 2 edited.", "updated_at": None, "created_by": self.user.pk, "updated_by": self.user.pk } # TODO // Figure out whether it's possible not to provide all fields ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['message'], 'Test Message 2 edited.') self.assertEqual(response.data['updated_by'], self.user.pk) Error message: TypeError: put() got an unexpected keyword argument 'board_pk' Any help would be greatly appreciated. Thanks! -
Search Suggestion on the go using MYSQL
I want to implement an Amazon type search such that while typing in the search bar the suggestion can be shown. How to show suggestions while writing the word to be searched. How Database is queried such that it gives results on the go. -
Extending a Django model with custom field and save logic
I'm using an open source Django app that logs all requests to a model. It stores things like path, ip, user, queryset, etc. However, I'm interested in see which paths take the longest, so I can optimize them, yet the app doesn't store the explicit start and end time it takes to process the request, so I want to extend this model to seamlessly support this without adding any new models. The maintainer of the Django app doesn't want to add this functionality, and I don't want to fork it, extend it, and maintain a completely separate app. So I've decided to implement just these new features by dynamically adding a couple fields using Django's class_prepared signal, and a custom save process to update these field values using Django's post_save signal. My code looks like: from django.db.models.signals import class_prepared, post_save def add_request_fields(sender, **kwargs): """ class_prepared signal handler that checks for the model named MyModel as the sender, and adds a CharField to it. """ if sender.__name__ == 'Request': # Create a field to record when we first receive the request. field = DateTimeField(_('start time'), default=None, db_index=True, blank=True, null=True, editable=False) field.contribute_to_class(sender, 'start_time') # Create a field to record to total seconds … -
Django Model Issue In Multilevel Inheritance
class Registration(models.Model): user = models.OneToOneField(User, related_name='customer', on_delete=models.CASCADE) DOB = models.DateField(null=True, blank=True, default='') post_code = models.CharField(max_length=10) area = models.TextField() # account type choices OWNER = 'OW' WRITER = 'WR' ANALYST = 'AN' REFEREE = 'RE' ACCOUNT_TYPE_CHOICES = ( (OWNER, 'League wner'), (WRITER, 'Sports Writer'), (REFEREE, 'Referee'), (ANALYST, 'Analyst'), ) account_type = models.CharField( max_length=2, choices=ACCOUNT_TYPE_CHOICES, default=REFEREE, ) activation_key = models.CharField(max_length=255, null=True, blank=True) activation_time = models.DateTimeField(auto_now_add=True, null=True, blank=True) is_activate = models.BooleanField(default=False, blank=True) is_admin_accepted = models.BooleanField(default=False, blank=True) # this is included to keep record . Eiher this user has already been rejected by Admin is_admin_rejected = models.BooleanField(default=False, blank=True) def __str__(self): return (self.user.username) class Match(models.Model): GAME_HOUR = ( (9, '9'), (10, '10'), (11, '11'), (12, '12'), (13, '13'), (14, '14'), (15, '15'), (16, '16'), (17, '17'), (18, '18'), (19, '19'), (20, '20'), (21, '21') ) GAME_TIME = ( (00, '00'), (10, '10'), (15, '15'), (20, '20'), (30, '30'), (45, '45') ) MATCH_FORMAT = ( ('11v11', '11v11'), ('9v9', '9v9'), ('8v8', '8v8'), ('7v7', '7v7'), ('6v6', '6v6'), ('5v5', '5v5'), ('3v3', '3v3') ) MATCH_TYPE = ( ('League', 'League'), ('Friendly', 'Friendly'), ('KickAbout', 'Kick-About') ) team1 = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='team1', null=False) team2 = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='team2', null=False) DUE TO THE INHERITANCE OF Registration CAUSING AN ERROR User matching query does not … -
Django: getting access to related fields in other modles
I have the below class Chore(models.Model): title = models.CharField(max_length=300) reward = models.PositiveIntegerField( default= 1) def __str__(self): return self.title class Child(models.Model): created_by = models.ForeignKey(User,on_delete=models.PROTECT, blank = True, null = True) name = models.CharField(max_length=300) age = models.DecimalField (max_digits=2, decimal_places=1, default=3.0, blank = True ) class ChildChore(models.Model): child = models.ForeignKey(Child, on_delete=models.PROTECT) chore = models.ForeignKey(Chore, on_delete=models.PROTECT) points = models.PositiveIntegerField( default= 0, blank = True, null = True) Form: class ProgressForm(ModelForm): class Meta: model = ChildChore exclude = () ProgressFormSet = modelformset_factory(ChildChore, form=ProgressForm, extra=0, can_delete=[False]) html page: {{ formset.management_form }} {% for form in formset %} {{form.chore}} # will return the title {{form.child}} # will return the child name my question here is how to get the other models fields in the template? For example, I want the "reward" from Chore Model and I need the "age" form Child. something like {{form.child.age}} will not work and creating a function in the child model to return the age didn't work as well. I tried to make -
How to apply jwt django rest token to access other Apis
I am generating jwt token with this url http://127.0.0.1:8000/api/token/ HTTP 200 OK Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTUyOTQyOTUwMSwianRpIjoiZmYxOTFmN2JhN2NhNDY2MWI0OTUzZGU2NmVlNjg3ODEiLCJ1c2VyX2lkIjoyfQ.SssEuSxKj09vshLq74h5NPMZFg8V-0oee9ZqLHzINV4", "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTI5MzQzNDAxLCJqdGkiOiJlNDNlZTE2MTlmOTM0ZjQxOWM4NWRiZGYxMzZkMzk2ZiIsInVzZXJfaWQiOjJ9.l9CPDVg371uIvXAVlLdV_uhzYYn9ejzEpCZLFKo1fU4" } And i have an API (http://127.0.0.1:8000/api/userdetails/) which lists the user code is like below class UserDetailsAPIView(APIView): serializer_class = UserLoginSerializer def get(self, request, format=None): @permission_classes((IsAuthenticated, )) usernames = [user.username for user in User.objects.all()] return Response(usernames) When i access API (http://127.0.0.1:8000/api/userdetails/) it is displying error "detail": "Authentication credentials were not provided." So how will i access API (http://127.0.0.1:8000/api/userdetails/) by providing generated jwt token?