Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Capturing Group with Django 2.0
I am following an older tutorial on creating Django apps. In the section on modifying page URLs the tutorial uses a regex expression with a capturing group to pass the parameter in the url to views. I am using Django 2.0 so I am using path rather than url, and I am wondering what the correct substitution for the regex is. I have gotten around it for now by using re_path, but I'd like to know how it should actually be done in Django 2.0. The old code is: url(r'([^/]*)', views.index, name='index'), I have made numerous attempts to adapt this to path, including (pagename is the parameter in the index function): path('/<pagename>', views.index, name='index'), path('/<str:pagename>', views.index, name='index'), path('/<str:pagename>/', views.index, name='index'), etc. None of the permutations I could come up with worked and I got a 404 Error every time. I'm sure I am missing something, any help is much appreciated. -
Django debug {% include '' %} tag within template not working
Sometimes I get an empty string returned for my include tags which is impossible, because I have some static elements in it. This is happening sometimes in my productive environment. How can I debug such an issue? For example my footer or header disappears in some cases (Which I include within my "base.html") which I can't reproduce. Thx -
Django Model Function Performance
I'm not sure how to title this question, please propose something better if you can! I have two models. The first model stored info for a tree (Tree). The second is a model to store information when a tree is replanted (TreeResettlement). A function in Tree called 'planted_date_real()' calculates the last time the tree was planted by looking at the latest record in TreeResettlement. trees = Tree.objects.all() for tree in trees: date = tree.planted_date_real() I have performance issues with this. Let's say 10000 trees are in the database. If I call those 10000 trees, and want to know the last planted date, Django calls the TreeResettlement table 10000 times. I'm aware of the 'select_related routine', however that only works if a Foreign Key is used in the table being worked on. Any help will be appreciated! Tree model class Tree(models.Model): name = models.CharField(max_length=200,blank=True) planted_date = models.DateTimeField(default = timezone.now,blank=True) def planted_date_real(self): resettlements = TreeResettlement.objects.filter(tree=self) if len(resettlements) > 0: return(resettlements[len(resettlements)-1].date) else: return(self.planted_date) TreeResettlement model class TreeResettlement(models.Model): tree = models.ForeignKey(Tree,on_delete=models.CASCADE) date = models.DateTimeField(default = timezone.now,blank=True) keep_main_stem = models.BooleanField() -
How to create two interdependent admin ChoiceFields when both fields belong to the same Model
This question bothered me for a while now and I can't seem to find any resource on how I can achieve it. I'm using the latest django version. The question is simple enough. Let's say we have a model which looks like this: class Environment(models.Model): name = models.CharField(max_length=64) organization = models.CharField(choices=UsdDBActions().get_organizations()) configuration = models.CharField(choices=UsdDBActions().get_configurations()) def __str__(self): return f'{self.name}' The above choices are actualy selects which return organizations and configurations as a list of tuples. E.g queries: SELECT id, organization FROM some_table SELECT id, configuration FROM some_other_table And in the admin we register it: class EnvironmentAdmin(admin.ModelAdmin): list_display = ( 'name', 'configuration', 'organization', ) admin.site.register(Environment, EnvironmentAdmin) When a user picks up an organization, I'd like the configuration field to prepopulate with the configurations that belong to that organization. The problem is that organizations and configurations are two different tables in an external DB and so I can't mess with the DB setup. Any ideas on how can I achieve this? -
Django , ajax for button onclick
I have this code in flask, It sends 2 lists to html, one is just number like [1,2,3] and the other some names like [file1,file2,...] This is the html that makes a table, a column for the first list and the other for the second one and a corresponding button that onclick will send a function to flask that deletes the corresponding file: <div class="row"> <div> <table id="mytables" class="table table-striped" style="float: inherit;"> <thead> <tr> <th>id</th> <th>Name</th> <th>file_size</th> </tr> </thead> <tbody> {% for id in ids %} <tr href="#"> <td>{{id+1}}</td> <td>{{file_name[id]}}</td> <td> <button onclick="delete_f('{{file_name[id]}}')" id="d{{id}}" type="button" class="btn btn-xs btn-primary">Delete </button> </td> </tr> {% endfor %} </tbody> </table> </div> </div> and this is the javascript: <script> function delete_f(name) { $.ajax({ url: '/delete_f', data: name, contentType: 'application/json;charset=UTF-8', type: "POST", async: false, success: function (response) { document.location.reload(true); } }); } </script> and this is the flask: @app.route('/delete_f', methods=['POST']) def delete_f(): name = request.data os.remove('E:/Office/DLP/sourceCode/Flask/newwork/static/files/' + name) return "das" this works fine, I want to make it in django, my first problem is that django doesn't support this line : {{file_name[id]}} The second problem is that whatever I do, django won't accept the ajax function's POST variables, this is the django code in views.py: @csrf_exempt … -
Using Django and Bootstrap Studio together
I've recently leanred about Bootstrap Studio to create web pages and it looks like a simple and easy tool. I was wondering if it is possible to gerenate HTML files and then use those with my Django web app? Am I just going to waste my time trying to make both those frameworks work together? edit: I am already using Bootstrap, just not Bootstrap Studio -
SyntaxError: Generator expression must be parenthesized
I just installed Django and created a new project. Then, I tried to run development server using command: python manage.py runserver after that I am getting the error: SyntaxError: Generator expression must be parenthesized -
Creating superuser in django
I modified the user model as shown below, to make users log in via phone. `from django.db import models import datetime from django.core.mail import send_mail from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from django.contrib.staticfiles.templatetags.staticfiles import static from django.core.validators import RegexValidator class UserManager(BaseUserManager): def get_by_natural_key(self, username): case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD) return self.get(**{case_insensitive_username_field: username}) def create_user(self,phone_number,password=None,is_staff=False,is_active = True, is_admin = False, is_vendor = False): if not phone_number: raise ValueError("Users Must Have a phone number") if not password: raise ValueError("Users must have a password") user = self.model( phone_number ) user.set_password(password) user.is_staff = is_staff user.is_active = is_active user.is_admin = is_admin user.is_vendor = is_vendor user.save(using=self._db) return user def create_staffuser(self,phone_number, password=None): user = self.create_user( phone_number, password=password, is_staff=True ) return user def create_superuser(self,phone_number, password=None): user = self.create_user( phone_number, password=password, is_admin=True, is_staff=True ) return user def create_vendoruser(self,phone_number, password=None): user = self.create_user( phone_number, password=password, is_vendor=True ) return user class User(AbstractBaseUser): phone_number = models.CharField(max_length=20, unique=True) date_joined = models.DateField(auto_now_add = True) is_active = models.BooleanField(default = True) is_staff = models.BooleanField(default = False) is_admin = models.BooleanField(default = False) is_vendor = models.BooleanField(default = False) is_basic = models.BooleanField(default = False) REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.phone_number # def save(self, *args, **kwargs): # self.email = self.email.lower() # return super(User, self).save(*args, **kwargs) def get_full_name(self): … -
Django celery beat doesn't see periodic task on Elastic Beanstalk
I have configured celery worker and celery beat on EB. There are no errors in logs during deploy and celery worker works fine, but doesn't see periodic tasks. On local machine everything works smoothly. Here is my config file for the celery files: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash # Create required directories sudo mkdir -p /var/log/celery/ sudo mkdir -p /var/run/celery/ # Create group called 'celery' sudo groupadd -f celery # add the user 'celery' if it doesn't exist and add it to the group with same name id -u celery &>/dev/null || sudo useradd -g celery celery # add permissions to the celery user for r+w to the folders just created sudo chown -R celery:celery /var/log/celery/ sudo chown -R celery:celery /var/run/celery/ # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/%/%%/g' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` celeryenv=${celeryenv%?} # Create CELERY configuration script celeryconf="[program:celeryd] directory=/opt/python/current/app ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery worker -A config.celery:app --loglevel=DEBUG --logfile=\"/var/log/celery/%%n%%I.log\" --pidfile=\"/var/run/celery/%%n.pid\" user=celery numprocs=1 stdout_logfile=/var/log/celery-worker.log stderr_logfile=/var/log/celery-worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase … -
Django best app for tracking user behaviour (actionable metrics, lean startup)
Being a vivid reader and practiser of the Lean Startup it is very important to be able to track user behaviour from end to end. Those numbers would ultimately be put in a simple one-page report (i.e. not google analytics) kind of like this. What would you recommendations for apps tracking this type of behaviour be? -
django admin remove login page
Is there anyway to delete django admin login page (mySite.com/admin) and use the user session which has logged in in main site (mySite.com)? If any code is needed please tell me to add. My middleware in settings.py is: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', . . . . . ] -
Forking shipping app has no effect in Django oscar
I had forked my shipping app into a folder called forked_apps using oscar_fork_app command and also added in settings.py get_core_apps(['forked_apps.shipping']), I just want to create two shipping methods mentioned, standard and express in the docs in this link:https://django-oscar.readthedocs.io/en/latest/howto/how_to_configure_shipping.html. In the init.py I have this code pre-existing: default_app_config = 'forked_apps.shipping.config.ShippingConfig' In repository.py I have written like this: from oscar.apps.shipping import repository from .methods import * class Repository(repository.Repository): def get_available_shipping_methods( self, basket, user=None, shipping_addr=None, request=None, **kwargs): methods = (Standard()) print("\n\nFetch availble shipping methods") if shipping_addr: # Express is only available in the UK methods = (Standard(), Express()) return methods And in the methods.py I had written: from decimal import Decimal as D from oscar.apps.shipping import methods from oscar.core import prices class Standard(methods.FixedPrice): code = 'standard' name = 'Standard shipping' charge_excl_tax = D('5.00') class Express(methods.FixedPrice): code = 'express' name = 'Express shipping' charge_excl_tax = D('10.00') What should happen is, the shipping_methods.html page should show up, but instead, after entering the shipping address it goes to the payment details page directly; this would usually happen only if there are no shipping methods defined, but I have implemented two shipping methods, standard and Express in the above code.I can't figure out how to make this … -
POST request to create a resource with bulk data from a csv file
I have used Python for many of my projects but new to django and the django rest framework, which I am using to design and develop a set of Web APIs for my current project. Weaving the backend, we are using Postgres for user information and DynamoDb for other set of resources users have to work upon. In the basic implementation, I tried to write the viewset as below: class WorkViewSet(viewsets.ViewSet): serializer_class = serializers.WorkSerializer permission_map = { 'create' : [IsAuthenticated, IsUser, ], # post 'list' : [IsAuthenticated, ], # get 'retrieve' : [IsAuthenticated, ], # get 'work_approval' : [IsAuthenticated, IsAdmin, ], # post 'work_disapproval' : [IsAuthenticated, IsAdmin, ], # post } def list(self, request): ... def create(self, request): ... def retrieve(self, request, pk=None): ... @action(methods=['post'], detail=True, url_path='approve', url_name='work_approval') def work_approval(self, request, pk=None, *args, **kwargs): ... @action(methods=['post'], detail=True, url_path='disapprove', url_name='work_disapproval') def work_disapproval(self, request, pk=None, *args, **kwargs): ... def get_permissions(self): try: return [permission() for permission in self.permission_map[self.action]] except KeyError: return [permission() for permission in self.permission_classes] and the serializer as below: class WorkSerializer(serializers.Serializer): STATUSES = ( '0', '1', '2', ) work_id = serializers.IntegerField(read_only=True) work_name = serializers.CharField(max_length=256) work_type = serializers.CharField(max_length=256) work_status = serializers.ChoiceField(choices=STATUSES, default='0') def create(self, validated_data): ... def update(self, instance, validated_data): ... This … -
DRF - How to add authorization token in incoming http request header
I'm a noob so please bear with me if this seem like stupid question. I've implementing token authentication via DRF(Django-rest-framework). So far I've understood that in token authentication you exchange your credential with a token which server had had already generated for every user. Then you put that token in every request header to the API, without worrying about the cookies. Now I know how to generate token and write to view to authenticate and issue token. BUT I haven't figured out how to put token in the http header, which I suppose need to be done in front-end. I tried to search but there doesn't seems to a clear answer on the internet how to do it. -
Add constraint to ManyToMany table on Django model
I have next models (I left only columns which are connected to the question): class Student(models.Model): student_examin = models.ManyToMany("Examin", verbose_name=u"Examin", blank=True, null=True, on_delete=models.SET_NULL, through="ExaminResult") student_group = models.ForeignKey("Group", verbose_name=u"Група", blank=False, null=True, on_delete=models.PROTECT) class Examin(models.Model): examin_group = models.OneToOne("Group", verbose_name=u"Група", blank=False, null=True, on_delete=models.CASCADE) class ExaminResult(models.Model): student = models.ForeignKey("Student", verbose_name=u"Студент", blank=False, null=False, on_delete=models.CASCADE) examin = models.ForeignKey("Examin", verbose_name=u"Екзамін", blank=False, null=False, on_delete=models.CASCADE) So I have Student model who has a Group and many Examins. I have an Examin model for specific Group. And I have connection table ExaminResult which connects students with their examins (later on I will add here grades column). My question is how to add constraint to table ExaminResult so that student was added to examin for the same group (so that student and examin in this table have the reference to the same Group model). So to prevent situation when student is added to examin for different group. -
I want to represent django model as table in html page with table heading same as django field name. How can I implement this?
I am new to Django. I'm stuck to a problem which I feel is beyond my current abilities in Django. The problem is about using heading for table columns same as string representation of its relative model field.To elaborate this further, assume I have a model as below: class Car(models.Model): company_name = models.ForeignKey(Company,related_name='cars') transmission_type = models.CharField(max_length=50) color = models.CharField(max_length=25) age = models.PositiveIntegerField(blank=True,null=True) For this model I want to generate HTML table as below: <table> <thead> <th>Company Name</th> <th>Transmission Type</th> <th>Color</th> <th>Age</th> </thead> <tbody> <tr> <td>{{company_name}}</td> <td>{{transmission_type}}</td> <td>{{color}}</td> <td>{{age}}</td> </tr> </tbody> </table> How can I achieve this in Django? -
Graphene/Django (GraphQL): How to execute a query with the exclusion of some fields from access?
My scheme is simple. Model is custom user from django. class UserFilter(django_filters.FilterSet): class Meta: model = User fields = ['username', 'email', ] class UserNode(DjangoObjectType): class Meta: model = User only_fields = ( 'username', 'email', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'profile', ) interfaces = (graphene.relay.Node, ) @classmethod def get_node(cls, info, id): try: user = cls._meta.model.objects.get(id=id) except cls._meta.model.DoesNotExist: return None if user: return user return None class Query(graphene.ObjectType): users = DjangoFilterConnectionField( UserNode, filterset_class=UserFilter, ) def resolve_users(self, info): user = info.context.user if user.is_anonymous: raise Exception('You aren't autorized') elif not user.is_superuser: return get_user_model().objects.defer("email") elif user.is_superuser: return get_user_model().objects.all().select_related('profile') else: raise Exception('Error') When I make a request from a user who is not superuser, and in the schema I specify the field "email", the answer gives the value of this field.: query{ users{ edges{ node{ id username email isSuperuser } } } } I get: { "data": { "users": { "edges": [ { "node": { "id": "VXNlck5vZGU6NQ==", "username": "Test4", "email": "Test4@test.ru", "isSuperuser": false } } ] } } } Whether it is possible as that to differentiate access to fields in resolve_users? The exception in the filter does not work. Perhaps I do not correctly understand the design of the DjangoFilterConnectionField, and I should use the … -
Python-Flask Exception: Unexpected data type <type 'unicode'>, <type 'list'>.
Hi I am trying to download an excel file from the below mentioned code, I am querying the data's from the firebase database. But when i try to run this it is giving me a unicode Exception. can anyone help me solve this? Thanks in advance. @mod_drprax_backend.route('/download-excel/', methods=['GET']) def export_db(): array = [] args = get_query_args(request) ref = db.collection(u'Providers') providersList, total = firebase_admin_query_helper(ref, args) pro = providersList[0] collect = zip(pro.keys(), pro.values()) for data in collect: providerDetails = [data] array.append(providerDetails) return excel.make_response_from_array([array],"xls",file_name=u"excel_doc" ) -
Improper format of Registration Form in Django
Right now, I'm working on the registration form in Django. In my registration form, there is the total of six fields like Username, First Name, Last Name, Email, Password, Password Confirmation. During my testing of the registration form, I figured out such a weird thing. Every time fields change their positions. I mean sometime Password comes at first place and Last Name at last place. And whenever I shut down the server and run it again then again fields positions changed again. See below some screenshot. So you can understand what I mean to say. And If I shut down the server and run it again then It happens every time. According to the logic which I write in the code it must in one proper manner like Username, First Name, Last Name, Email, Password, Password Confirmation. Here below my views.py: from django.shortcuts import render, redirect from accounts.forms import RegistrationForm # Create your views here. def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) And below one is forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): … -
output information to the template (from the next array)
Stalled, but I can not understand how to display the next array Have this: return render(request, 'main.html', {'arrImages': arrImages,'title': arrTitle}) The arrImages array is output without any problems. But how to get the title? I do not understand where i have to loop. <div class="container"> {% for images in arrImages %} <hr> <p class="text-justify"> {{ /////????title }}</p> <img class = "col-12 ml-auto col-12 mr-auto" src={{ images }}> {% endfor %} Where i have to put {% for title in arrTitle %}{% endfor %} , or is it done in one loop? Sorry for such questions, but in the internet did not find) I work through the API. Without a database. If it's necessary i can attach all the code of views.py -
how to make a search in post (in django)
I am working on making a search form in the website through which we can search for a particular blog title till now I have created a form: <form action="GET" action="{% url 'posts:search' %}"> <input name="q" type="text" placeholder="Search" value="{{ request.GET.q }}"> <input type="submit"> </form> url for that in urls.py: url(r'^results/$', views.search, name='search'), function under views.py: def search(request): query = request.GET.get('q') posts = Posts.objects.filter(Q(title__icontains=query)) return render(request, 'posts/posts.html', {'posts': posts}) Whenever I click on search button it goes to the URL http://127.0.0.1:8000/GET/?q=lots+of and gives the error Posts matching query does not exist. trackback for the error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/GET/?q=lots+of Django Version: 2.0.5 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site- packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site- packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site- packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Fruity_Dude\Projects\Django\devflow\posts\views.py" in post_details 17. posts = Posts.objects.get(slug=slug) File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Fruity_Dude\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\query.py" in get 403. self.model._meta.object_name Exception Type: DoesNotExist at /GET/ Exception Value: Posts matching query does not exist. -
Django - Celery ValueError: Related model u'user.User' cannot be resolved
When I am executing celery task it is giving me: ValueError: Related model u'user.User' cannot be resolved The stacktrace is Traceback (most recent call last): File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/celery/app/trace.py", line 375, in trace_task R = retval = fun(*args, **kwargs) File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/celery/app/trace.py", line 632, in __protected_call__ return self.run(*args, **kwargs) File "/Users/prince/work/magneto/set/facebook_pages/tasks.py", line 23, in analyze_page connected_facebook_page = get_connected_facebook_page(connected_facebook_page_id) File "/Users/prince/work/magneto/set/facebook_pages/utils.py", line 49, in get_connected_facebook_page return ConnectedUserPage.objects.get(id=connected_facebook_page_id) File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 374, in get num = len(clone) File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 232, in __len__ self._fetch_all() File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 876, in execute_sql sql, params = self.as_sql() File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 428, in as_sql extra_select, order_by, group_by = self.pre_sql_setup() File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 46, in pre_sql_setup self.setup_query() File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 37, in setup_query self.select, self.klass_info, self.annotation_col_map = self.get_select() File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 194, in get_select for c in self.get_default_columns(): File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 569, in get_default_columns column = field.get_col(alias) File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1008, in get_col return super(ForeignKey, self).get_col(alias, output_field or self.target_field) File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 909, in target_field return self.foreign_related_fields[0] File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 653, in foreign_related_fields return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field) … -
DRF : user getting lost -> 403, Authentication credentials were not provided
I am trying to make an API call from within a react app. My endpoint is returning 403 Forbidden with detail "Authentication credentials were not provided." My DRF settings are, I just intend to use SessionAuthentication : REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } CSRF validation is not failing, CSRF is being sent in the header properly. When I put in debugger on the middleware I can see a correct self.request.user till the last middleware. -
How can I access the DRF APIs from other site?
I have a django/django-rest-framework project. in the settings.py: there use rest_auth and rest_framework.authtoken for authentation: INSTALLED_APPS = [ .... 'rest_framework.authtoken', 'rest_framework_docs', 'rest_auth', in the urls.py: urlpatterns = [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), when I login the application (The app providers many APIs), I will get a token, for authentication, but now, there I get an issue, I have another site, when I login the other site, I want to request DRF site's API data from the other site. How to solve this requirement? -
Django make a custom field name
I know that I can have verbose_name on each model's field like so form_name = models.CharField('Form Name', max_length = 100) How if I want to change a specific field's name just for a specific view/case? For example, on a certain case I want it to be "Your Form Name", and on another case I want it to be "His Form Name", etc. Thanks in advance.