Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i pass params to init method of each form in django model formset factory
I have get_custom_formset function that return formset of a passed django model. I would like to be able to pass parameters to the constructor of each form when the formset is created. def get_custom_formset(model=None, fields=None, action=None, elements=None): show_fields = [] for field in fields: show_fields.append(field.name) formset = modelformset_factory( model = model, extra = extra, fields = show_fields, form = CustomModelForm ) return formset class CustomModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.action = None if 'action' in kwargs: self.action = kwargs.get('action') del kwargs['action'] super(CustomModelForm, self).__init__(*args, **kwargs) if self.action is not None: if self.action == 'detail': for field in self.fields: self.fields[field].widget.attrs['readonly'] = True class ClientForm(CustomModelForm): class Meta: model = app_models.Client fields = '__all__' Anybody know how to do that ? Thank you so much -
Django Crispy Form Shows {'id': ['This field is required.']}
I'm receiving the following error when I click the save button on my inline formset using Crispy Forms: [{'id': ['This field is required.']}, {'id': ['This field is required.']}, {'id': ['This field is required.']}, {}, {}] The formset is bound but not valid because of the missing id, but I'm not sure how to set the id. #views.py class View(LoginRequiredMixin, TemplateView): template_name = "example.html" MyFormSet = modelformset_factory( model=MyModel, form=MyModelForm, formset=MyModelFormset, can_delete=True, extra=1, fields=('field_1','field_2', )) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) my_formset = self.MyFormSet() context['my_formset'] = MyModel.objects.all().order_by('field_1') return context def post(self, request, *args, **kwargs): my_formset = self.MyFormSet(request.POST, request.FILES) if my_formset.is_valid(): try: my_formset.save() except: messages.add_message(request, messages.ERROR, 'Cannot delete: this parent has a child 1 !') else: context = self.get_context_data() context['my_formset'] = my_formset return render(request, self.template_name, context) return HttpResponseRedirect(reverse_lazy("example")) #forms.py class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ['field_1', 'field_2'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( Column('field_1'), Column('field_2'), Column('DELETE'), ) ) #template <form action="" enctype="multipart/form-data" method="post">{% csrf_token %} {{ my_formset.management_form|crispy }} {% for form in my_formset.forms %} {% crispy form form.helper %} {% endfor %} <button class="btn btn-success" type="submit">Save</button> </form> -
Django Rest - Serializer: must be a instance on create
I'm trying to create create a nested serializer using the Django Rest framework. The relationship is Profile X User but when i use Profile.objects.create(user=profile, **user_data) i get ValueError: Cannot assign "<Profile: Profile object (7)>": "Profile.user" must be a "User" instance.. This should be some rookie misunderstanding of models relationship definitions or the serializer declaration itself but I can't find anything around the docs. If someone can point me a direction I'll be gracefull. models.py class User(models.Model): name = models.CharField(max_length=100, blank=False) email = models.CharField(max_length=100, blank=True, default='') password = models.CharField(max_length=100, blank=True, default='') timestamp = models.DateTimeField(default= timezone.now) class Meta: ordering = ['timestamp'] class Profile(models.Model): # choices [...] user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) profile_type = models.CharField(max_length=2,choices=PROFILE_CHOICES,default=TEAMMEMBER) authentication_token = models.CharField(max_length=100, null=True) avatar_url = models.CharField(max_length=100, default='') permissions = models.CharField(max_length=100, null=True) timestamp = models.DateTimeField(default= timezone.now) class Meta: ordering = ['timestamp'] serializer.py class UserSerlializer(serializers.ModelSerializer): class Meta: model = User fields = ['name', 'email', 'password'] class ProfileSerializer(serializers.ModelSerializer): user = UserSerlializer() class Meta: model = Profile fields = ['user', 'profile_type'] def create(self, validated_data): user_data = validated_data.pop('user') profile = Profile.objects.create(**validated_data) Profile.objects.create(user=profile, **user_data) return Profile POST { "profile_type" : "ST", "user": { "name" : "test", "email" : "test@test.com", "password" : "123456" } } -
url returning none in django
I am running a website with python and Django . I have made all changes that are required to run. urls.py: urlpatterns = [ url('index.html', views.index, name='index'), url('admin/', admin.site.urls), url('', views.user_login, name='user_login'), url('dashboard', views.obs_index, name='admin_dash'), url('halls/active', views.obs_halls_active, name='active-halls'), url('halls/pending', views.obs_halls_pending, name='pending-halls') ] obs_index.html: {% block bookings %} <li> <a href="javaScript:void();" class="waves-effect"> <i class="fa fa-calendar-o"></i> <span>Bookings</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="sidebar-submenu"> <li><a href="{% url 'obsadmin:bookings_user' %}"><i class="zmdi zmdi-star-outline"></i> By Users</a></li> <li><a href="{% url 'obsadmin:bookings_owner' %}"><i class="zmdi zmdi-star-outline"></i> By Owners</a></li> </ul> </li> {% endblock %} When i run and click on the bookings menu, it is not working. Why is that? -
Is there any api for revoking one drive acess token?
how to revoke the acess_token granted by onedrive using api? Microsoft account users can revoke an app's access to their account by visiting the Microsoft account manage consent page. When consent for an app is revoked, any refresh token previously provided to your application will no longer be valid. You will need to repeat the authentication flow to request a new access and refresh token from scratch. one drive documentation does not state any api for token revokal -
Randomly select from a set of questions
I am trying to recreate the game of hacks because there isn't an API to create my own questions, and implement on external site , however I am using django with restful framework for this task. (I am not sure , if this is the right to achieve this). I will do this via server because I dont want people to change js and bypass the stuff or even disable js and stop time , and continue with the same question, but how can I translate into django this? from django.shortcuts import get_object_or_404 from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Question, Choice from .serializers import QuestionListPageSerializer, QuestionDetailPageSerializer, ChoiceSerializer, VoteSerializer, QuestionResultPageSerializer @api_view(['GET', 'POST']) def questions_view(request): if request.method == 'GET': questions = Question.objects.all() serializer = QuestionListPageSerializer(questions, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = QuestionListPageSerializer(data=request.data) if serializer.is_valid(): question = serializer.save() return Response(QuestionListPageSerializer(question).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class QuestionListPageSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) question_text = serializers.CharField(max_length=200) pub_date = serializers.DateTimeField() was_published_recently = serializers.BooleanField(read_only=True) # Serializer is smart enough to understand that was_published_recently is a method on Question code = serializers.CharField(max_length=200) def create(self, validated_data): return Question.objects.create(**validated_data) def update(self, instance, validated_data): for key, value in validated_data.items(): setattr(instance, key, … -
Django REST Framework TypeError: register() missing 1 required positional argument: 'viewset'
Im learning Django REST Framework and Im trying to get to work a simple ViewSet but I keep getting this error on the console when trying to run the server File "C:\Users\anahu\Projects\guatudu-api\api\api\locations\urls.py", line 13, in <module> router.register(r'countries', country_views.CountryViewSet, basename='country') TypeError: register() missing 1 required positional argument: 'viewset' this is my app's urls.py """Locations Urls""" # Django from django.urls import path, include # Django Rest Framework from rest_framework.routers import DefaultRouter # Views from api.locations.views import countries as country_views router = DefaultRouter router.register(r'countries', country_views.CountryViewSet, basename='country') urlpatterns = router.urls And this is my ViewSet """Countries view""" # Django REST Framework from rest_framework import viewsets # Serializers from api.locations.serializers import CountryModelSerializer # Models from api.locations.models import Country class CountryViewSet(viewsets.ModelViewSet): """Country viewset""" queryset = Country.objects.all() serializer_class = CountryModelSerializer and this is my serializer """Country Serializers""" #Django Rest Framework from rest_framework import serializers from rest_framework.validators import UniqueValidator #Model from api.locations.models import Country class CountryModelSerializer(serializers.ModelSerializer): """Country Model Serializer""" class Meta: """Meta class""" model = Country fields = ( 'id', 'name', 'image' ) is pretty basic stuff, but I keep getting that error. All I can imagine is that for some reason Im not getting the ViewSet from on the urls.py correctly? I hope you guys can help … -
How to check a div color by checking a variable true or False in Django Template
I want to show all readed notification in white color and unreaded notification in another color . I am able to pass the message is unreaded or readed into Django template. But I am unable to check it and correct it {{#each data.data as | unread_list |}} <div class="dropdown-item bg-light border-bottom"> <div class="row"> <div class="col-10 notification-content-align"> <span class="pl-1"> {{unread_list.verb}} </span> <p class="text-mute"><i class="la la-comment-alt text-{{unread_list.level}}" aria-hidden="true"></i> {{unread_list.timeslice}} ago</p> </div> </div> </div> {{/each}} If I called {{unread_list.unread}} I can see whether it is true or false . But I am unable to check it I just tried {{#each data.data as | unread_list |}} {% if unread_list.verb is True %} <div class="dropdown-item bg-light border-bottom"> {% else %} <div class="dropdown-item bg-dark border-bottom"> {% endif%} <div class="row"> <div class="col-10 notification-content-align"> <span class="pl-1"> {{unread_list.verb}} </span> <p class="text-mute"><i class="la la-comment-alt text-{{unread_list.level}}" aria-hidden="true"></i> {{unread_list.timeslice}} ago</p> </div> </div> </div> {{/each}} -
Django load more comments with AJAX
In the profile page, I want to display posts of a user. Each post might have several comments, I don't want to display all the comments to the post instead I want to display only few comments and add load more comments option. If a user clicks load more comments then I want to display some more comments. What is better way to do this? I am already using infinite scroll using pagination for posts. I think this may not work for comments. My currents code looks like below {% for post in post_queryset %} <div class="title"> {{ post.title }} </div> {% for comment in post.comments.all %} </div> {{ comment.text }} </div> {% endfor %} {% endfor %} Above code simplified version of original to make things easier. -
How to use iregex with ORM filter in Django?
Model class A(models.Model): t = models.CharField(max_length=255, blank=True, null=True) // X250630-1001axc Database: Mysql I tried this, but the result queryset is empty. I went to the official documentation, but nothing helped. A.objects.filter(t__iregex=r'X\d{6}-\d{4}[\da-z]{,3}') I thought my regex was wrong, but it worked through re.search -
Get random questions in a quizgame django API
I am trying to recreate game of hacks because there isnt an API to create my own questions , and implement on external site , however I am using django with restful framework for this task. (I am not sure , if this is the right to achieve this). I will do this via server because I dont want people change js and bypass the stuff or even disable js and stop time , and continue with the same question apiview.py @api_view(['GET', 'POST']) def questions_view(request): if request.method == 'GET': questions = Question.objects.all() serializer = QuestionListPageSerializer(questions, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = QuestionListPageSerializer(data=request.data) if serializer.is_valid(): question = serializer.save() return Response(QuestionListPageSerializer(question).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers class QuestionListPageSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) question_text = serializers.CharField(max_length=200) pub_date = serializers.DateTimeField() was_published_recently = serializers.BooleanField(read_only=True) # Serializer is smart enough to understand that was_published_recently is a method on Question code = serializers.CharField(max_length=200) def create(self, validated_data): return Question.objects.create(**validated_data) def update(self, instance, validated_data): for key, value in validated_data.items(): setattr(instance, key, value) instance.save() return instance question list my app HTTP 200 OK Allow: POST, OPTIONS, GET Content-Type: application/json Vary: Accept [ { "id": 1, "question_text": "helllo", "pub_date": "2020-01-15T02:30:40Z", "was_published_recently": false, "code": "int main (int argc, char *argv[])\r\n{\r\n\tchar … -
DRF and Knox Authentication: Allow login for non-staff users
I have created a Login API which authenticates users from django.contrib.auth.models.User. I am using DRF and implementing a token authentication with django-rest-knox and so far so good. The application I am developing is a bit complicated but I'm gonna use one of our sub-apps as an example. So we have a sub application called jobnet and the goal of this application is to allow people to register an account thru the website and be able to apply for available jobs in our company online. The application shall have separate login pages for 2 different types of users (i.e. staff users (the company's employees) and those online applicants. The process here is a online applicant will register for an account and that will be marked is_staff=False. Every time he logs in, he shall be redirected to his non-staff dashboard where he can apply for jobs and manage applications. Once he gets officially hired, his account will be updated to is_staff=True. Now, he can either login via the applicant's login interface, or via the staff's login page. Either way, the system will detect that he is already a staff and will redirect him to the staff's dashboard instead. I already have a … -
When you use DRF(Server API) + React(public Web Client), how do you implement for OAuth2 social login?
I am developing Django(Server) with React(Web Client). And I want to use facebook social login. I knew that client is public client, server is confidential. So I want to use authentication code grant way for authenticating user. So I find out the way but there is no way to implement that. All the python oauth2 library limplements is just for django server side rendering.(Django Server + Web client). So I confused about I am wrong or just the others just did not make the grant way. When you use DRF(Server API) + React(public Web Client), how do you implement for OAuth2 social login? I wonder that. please give me some advise to me. Thanks. -
Django delete_or_create
Is there a method delete_or_create in django ORM similar to get_or_create? something similar to: p, deleted = Person.objects.create_or_delete( first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)}, ) # create_or_delete() has created the object >>> deleted False p, deleted = Person.objects.create_or_delete( first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)}, ) # create_or_delete() has deleted the object as it does exist in the DB >>> deleted True -
Speeding up a Django query
My company has a pretty complicated web of Django models that I don't deal too much with. But sometimes I need to do queries on it. One that I'm doing right now is taking an inconveniently long time so I was hoping someone here could help figure out how to do a better job at getting this result quicker. Here's a facsimile of the relevant models in our database. class Company(models.Model): name = models.CharField(max_length=255) @property def active_humans(self): if hasattr(self, '_active_humans'): return self._active_humans else: self._active_humans = human.filter(active=True, departments__company=self).distinct() return self._active_humans class Department(models.Model): name = models.CharField(max_length=225) company = models.ForeignKey( 'muh_project.Company', related_name="departments", on_delete=models.PROTECT ) humans = models.ManyToManyField('muh_project.human', through='muh_project.job', related_name='departments') class Job(models.Model): name = models.CharField(max_length=225) department = models.ForeignKey( 'muh_project.Department', on_delete=models.PROTECT ) human = models.ForeignKey( 'muh_project.human', on_delete=models.PROTECT ) class Human(models.Model, LiveContentBase, GoldIncentivizedBase): active = models.BooleanField(default=True) _favorite_dog = models.ForeignKey( 'muh_project.Dog', null=True, related_name="favorite_for_human", on_delete=models.PROTECT ) @property def fixed_happy_dogs(self): return self.solutions.filter(is_neutered_spayed=True, disposition="happy") class Dog(models.Model): is_neutered_spayed = models.BooleanField(default=True) disposition = models.CharField(max_length=225) age = models.IntegerField() human = models.ForeignKey( 'muh_project.human', related_name="dogs", on_delete=models.PROTECT ) human_job = models.ForeignKey( 'muh_project.Job', blank=True, null=True, on_delete=models.PROTECT ) What I'm trying to do (in the language of this silly toy example) is to get the number of humans with at least one of a certain type of dog … -
Django: how to access indirect values within a model, two levels down
I would like to access a list of values two levels down in a model to be displayed in a template. In the below model, you have a shopping basket within which you can put different kinds of meat. Assume you now have put two types of meat in your shopping basket, Ribeye, and Rump steak, what level of protein has each of the two types got? My models looks like this: class ShopOrder(models.Model): order_date = models.DateField() meatbasket = models.ManyToManyField('food.Meat', blank=True) # App food class Meat(models.Model): name = models.CharField(max_length=20) nutrition = models.OneToOneField(Nutrition, blank=True, null=True, on_delete=models.SET_NULL) class Nutrition(models.Model): protein = models.IntegerField() fat = models.IntegerField() I have no problem to create a list on the first level down (list of 'meat' names from the Model 'Meat' below: meat_names = list(object.meatbasket.values_list('name', flat=True)) However, how do I access the next level down, i.e. in my example to get number of 'protein' for each Meat name? -
Using Foreign Keys in Django Template w/django-simple-history
I'm trying to display values associated with a foreign key while rendering a Django Template. I've emulated other answers on this site to no avail. I'm using the package django-simple-history to track changes to all the records in my database's primary table. This table has a foreign key named history_user_id which corresponds to the id in the django table auth_user. According to this example (Display foreign key value in django template) I should be able to display the usernames of users who have amended the database by using the following code: <ul>{% for item in history %} <li>{{item.history_user_id.username}}</li> </ul>{% endfor %} where history is defined in my views.py as def view_history(request,pk): project = Project.objects.get(pk=pk) history = project.history.all() return render( request, "projects/view_history.html", { "project": project, "history": history, } ) The template I create can interpret item.history_user_id, and I can manually look into the table auth_user to the corresponding username, but when I try to use the template to render the username I get a blank instead. Am I missing a step? -
How to add tags using taggit in Django admin
I am trying to add tags to my blog app using django admin but every-time I add a tag through the admin console, I get this error Can't call similar_objects with a non-instance manager Is this because I am not saving the the tags in the admin or is this because I implemented taggit wrongly? This is where I define my view and display and article, I try to grab similar articles using taggit def article(request, slug): article = Post.objects.filter(slug=slug).values() article_info = { "articles": article, "related_articles" : Post.tags.similar_objects() } return render(request, 'article.htm', article_info) -
How to change a field in one object while adding another object from Django Admin?
Django admin pic I have a trouble in finding a way for "Purchase Invoice" to add a number which is set in field "Quantity" to field "In Stock" of a specific "Product" (which is set in field "Product" of Purchase Invoice). Is it possible to override a method which adds (writes) Purchase Invoice to DB somehow and add there a code which affects "Products" object? If you have a realization of this idea, I would be glad to hear the solution. Thanks in advance. Purchase Invoice pic Model of Purchase Invoice: class PurchaseInvoice(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) purchase_price = models.IntegerField() quantity = models.IntegerField() date_of_income = models.DateField() supplier = models.ForeignKey(Suppliers, on_delete=models.CASCADE) class Meta: ordering = ('-date_of_income',) verbose_name = 'Purchase Invoice' verbose_name_plural = 'Purchase Invoices' Product pic Model of Product: class Products(models.Model): header = models.CharField(max_length=128) supplier = models.ForeignKey(Suppliers, on_delete=models.CASCADE, related_name='Supplier') in_stock = models.IntegerField() price = models.IntegerField() class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' def __str__(self): return self.header -
extend django-allauth user model by adding UUID
I'm using cookiecutter-django which uses django-allauth. I want to be able to assign each user a UUID at signup. After running ./manage.py/makemigrations, I run ./manage.py migrate and I get the following error: django.core.exceptions.FieldDoesNotExist: User has no field named 'uuid' users/models.py from django.contrib.auth.models import AbstractUser from django.db.models import CharField, UUIDField from django.urls import reverse from django.utils.translation import ugettext_lazy as _ import uuid class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) uuid = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) settings/base.py ... ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_ADAPTER = "finance_tracker.users.adapters.AccountAdapter" SOCIALACCOUNT_ADAPTER = "finance_tracker.users.adapters.SocialAccountAdapter" ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ... -
Add Depandent drop down list for Django admin user
I have created 4 models in my django Country, State, and City, and also add them in admin.site.register How Can I add dependent drop down list for Country State City for admin user whenever user try to create Aplications object, they get state name list depends on Country name selected by admin user, and also for city. Models.py from django.db import models from django.db.models import ForeignKey from multiselectfield import MultiSelectField class Country(models.Model): name = models.CharField(max_length=250) phone_code = models.CharField(max_length=250) currency = models.CharField(max_length=250) def __str__(self): return self.name class State(models.Model): name = models.CharField(max_length=250) country = models.ForeignKey(to=Country, on_delete=models.CASCADE) def __str__(self): return self.name class City(models.Model): state = models.ForeignKey(to=State, on_delete=models.CASCADE) name = models.CharField(max_length=250) def __str__(self): return self.name class Applications(models.Model): country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=20) phone_number = models.IntegerField() email_id = models.EmailField() home_address = models.CharField(max_length=255, blank=True, null=True) birthdate = models.DateField(null=True, blank=True) current_company = models.TextField(max_length=250, blank=True, null=True) def __str__(self): return str(self.name) -
i am learning to deploying django project on pythonanywhere.com. What should i write to create virtual envirnment (mkvirtualenv --python=python3.??)
(djangoenv) C:\Users\GAGAN\Desktop\area_pro3>python --version Python 3.7.5 20:45 ~ $ mkvirtualenv --python=python3.7.5 djangoenv The path python3.7.5 (from --python=python3.7.5) does not exist -
Django getting UnicodeDecodeError when using local chars
I have started a new project and app in Django 2.2.5 and I use Python 3.7.4 in Pycharm 2019.1.3 I run the django dev server from Pycharm terminal and everything works fine until I use some local signs in the html templates like: "í" after that I get UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 345: invalid continuation byte In settings.py the Language code is set to local language: LANGUAGE_CODE = 'sk' I am lost as to what to do with this. I tried trans and autoescape, setting the encoding at the top of the html file ... but it didn't work. Any ideas? -
How to I divide a cost by a length of time (say 12 months) in order to return a monthly cost
I am trying to do this calculation: divide a cost by a length of time (say 12 months) in order to return a monthly cost. I am able to return a value from the db but I am doing this totally wrong and I am stuck. I have also tried to use annotate instead of aggregate with no luck. From views.py def dashboard(request): total_cost = Apprentice.objects.all().aggregate(Sum('cost__cost'))['cost__cost__sum'] monthly_cost = Apprentice.objects.all().aggregate(Sum('p_time__duration'))['p_time__duration__sum'] return render(request, 'dashboard.html', {'total_cost': total_cost, 'monthly_cost': monthly_cost}) From template <div class="card"> <div class="card-body"> <h5 class="card-title">Total monthly spend</h5> <p class="card-text"><strong></strong>£{{ monthly_cost | intcomma }}</strong></p> </div> </div> -
How to accept requests from specific domains using Django Rest Framework?
So I have configured my project using CORS headers to accept request from all domains. However, I want to filter out requests in views using user provided data. Let me explain: each user can create projects and these projects have a field called whitelisted_domain which is set by the user. When a request hits for one of these projects, I want to make sure the request is from the whitelisted domain. For example: class CreateTask(APIView): def post(self, request, project_id, format=None): project = Project.objects.get(id=project_id) # Here, I want to check if the two domains match or not if project.whitelisted_domain == request.META['REMOTE_HOST']: # Create task else: # Raise authentication error The problem is when I am testing my view using services like Postman or Reqbin, the meta element is empty. Is there a way to securely match the request domain and the user set domain in a view? If not, how can I secure end-point? A secret key header is an option, but what if the requests are coming from the user's front-end, where it is basically impossible to hide credentials.