Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django processes interfering with each other
I have a Django web project which will eventually be accessed by multiple users. Through the interface the users will be able to kick off calculations using a module called spiceypy. I don't need to go into details of how this module works, but to make a long story short, it needs to load a library of kernels before performing the calculations. Different users might need different libraries loaded. I'm finding that there is interference, if two users kick off calculations at the same time. (User A loads Library A, and calculations start. Then User B loads Library B, and the calculations requested by User A end up using Library B..! ) So I need to find a way to make the processes independent of each other. Can someone recommend the best way to do this? Do I need to use something like subprocess? Or is there a method within Django that would allow me to run independent processes? Thank you all in advance. -
Django, How to import model class to another model class?
I have this two app name Business and ChartofAccounts, in my business.models i have class businessType(models.Model): Name = models.CharField(max_length=500) Description = models.CharField(max_length=500) RecordStatus = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) and my ChartofAccounts.models i have class ChartOfAccount(models.Model): AccountNo = models.IntegerField() Account_Name = models.CharField(max_length=500) Account_Type = models.CharField(max_length=500) Details_Type = models.CharField(max_length=500) Description = models.CharField(max_length=500) BusinessTypeID = models.ForeignKey(Business, related_name='+', on_delete=models.CASCADE, blank=True) RecordStatus = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) I dont know how to import the business.models in my ChartofAccounts App, any ideas? what i tried is from myAccounting import Business and the error is -
django-table2 - Change background color for entire row depending on the value of specific column
I have been trying to highlight an entire row of a table with django-table2 package. I managed to change font color of one record doing the below: def render_MyValue(self, value, column, record): if record['Warning']: column.attrs = {'td': {'style': 'color:darkorange;'}} else: column.attrs = {'td': {'style': 'color:black;'}} return value Find below my table class: class DetailedReportTable(tables.Table): MyValue = tables.Column(orderable=False, verbose_name='Value') ... Warning = tables.Column(orderable=False, visible=False) The problem is I cannot find how to set the background of the row in orange if Warning is True. Following the doc here I tried also the below: class DetailedReportTable(tables.Table): ... class Meta: row_attrs = { "bg-color": lambda record: "#8B0000" if record['HasWarning'] else "#000000" } But this is not working... How can you change background color for a row using django-table2 ? -
How can i set permissions for every single user?
I need to set permission for example: if i have two users in my website and both of them have the right to write a post and they can delete or edit their posts. so, how can i set delete or edit button without make it are accessible by all users on the website just make it accessible by the user who's made the post question_view.html {% if user.is_authenticated %} <a data-showin=".my-form" class="showin">Comment</a>&nbsp; | &nbsp; <a href="">Edit</a> <span> <a href="">Like</a>&nbsp; | &nbsp; <a href="">Unlike</a> </span> {% endif %} community.models from django.db import models from account.models import UserProfile from django.contrib.auth.models import User from django.utils import timezone import django CHOICE = [('Technology', 'Technology'), ('Computer Science', 'Computer Science'), ('Lawyer', 'Lawyer'), ('Trading', 'Trading'), ('Engineering', 'Engineering'), ('Life Dialy', 'Life Dialy') ] class UserAsking(models.Model): userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person') question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question') field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about') def __str__(self): return self.title class Comment(models.Model): userasking = models.ForeignKey(UserAsking, on_delete=models.CASCADE) comment = models.TextField(max_length=500, blank=True, null=True) def __str__(self): return self.comment account.models from django.db import … -
Django intermediate page and processing multiple items
i'm very new to python and Django and wanted to give it a try by building a web interface for my personnal media library. I created a custom admin action that request TMDB API to store the movies information in my DB. If there's multiple results for a movie, i redirected to an intermediate page with a ChoiceField() to select the appropriate one. Here's the problem, when i validate the intermediate page it add my selection to the DB but stop processing the other requested movies... I assume the problem is coming for the redirection after the form processing but i can't figure it. Thanks for your help fellas ! admin.py def parse(self, request, queryset): if 'apply' in request.POST: form = MovieSelectForm(request.POST) res = ast.literal_eval(request.POST['res']) for r in res: if r['id'] == int(request.POST['Movies']): update_movie_infos(request.POST['_selected_action'], r) return HttpResponseRedirect(request.get_full_path()) SELECTED_MOVIES = [] for movie in queryset: if movie.status == 'UN': # Building API Request api_key = '8a260244852cbd90bc5662e721a2d685' uri = 'https://api.themoviedb.org/3/search/movie' req = requests.get(uri, { 'api_key': api_key, 'query': movie.title, 'year': movie.year, 'language': 'fr-FR' }).json() res = req['results'] if len(res) == 1: update_movie_infos(movie.pk, res[0]) self.message_user( request, '{} parsed successfully.'.format(movie.title)) elif len(res) == 0: self.message_user(request, '{}: no results.'.format( movie.title), level='error') else: self.message_user( request, '{}: Please … -
Django admin panel is only works for one domain in multi-tenant apps
I'm trying to build multi tenant application using django. For testing purpose, I tried this tutorial, Every things is working fine, but when ever i try to login admin panel it gives me error somethings like this.. admin panel is only working for one domain. List of domains polls.local:8000 thor.polls.local:8000 (admin panel only works for this domain) potter.polls.local:8000 Some command which is used for migrating python3 tenant_context_manage.py thor migrate_schemas (to migrate in thor schemas) python3 tenant_context_manage.py potter migrate_schemas (to migrate in potter schemas) python3 manage.py runserver (to migrate in default schema i.e public) Database connection settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shared_schema', 'HOST': 'localhost', 'USER': 'shared_schema', 'PASSWORD': 'password', 'PORT': '5432', } } python tenant_context_manage.py potter createsuperuser even this command is working for potter schema I didn't know why I'm getting error am i doing somethings wrong. -
Filter Django models based on date comparision
I have a Subscription models that has an end_date attribute. class Subscription(models.Model): client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE) trainer = models.ForeignKey(TrainerProfile, null=True, blank=True, on_delete=models.SET_NULL, limit_choices_to={'is_staff': True}) plan = models.ForeignKey(Plan, on_delete=models.CASCADE) transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() I want to send an email to the user having subscription to notify once: (subscription.end_date - timezone.now()).days < 3 How would I filter data from django based on these type of comparision in filter() rather than reading all the Subscription objects in the memory. -
Cors problem when requesting backend server Django and django-cors
CORS is not working properly. Django I'm using lib django-cors to enable this, but it doesn't work. I believe I'm doing something wrongCould someone help me, please? My web application returns a color error when trying to make a request for django I did everything, but it still doesn't work. I am very grateful for everyone's attention. Settings CORS_ORIGIN_ALLOW_ALL = True Middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware' ... ] Application INSTALLED_APPS = [ ... 'corsheaders', ... ] from origin webapp.mwapp.com as been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
How to go about splitting up multiple select in a Django form?
To make a more user-friendly interface on my website I would like to cut up a multiple select in a couple of multiple selects based on an attribute. How would you go about this? Models.py I basically have 4 classes as visualized below. I have a schedule to which tasks can be related. Furthermore the user needs to be able to assign user fields per schedule. An example of a user field could be 'topic' or 'priority: whatever the user decides. Each user field can have multiple user field values. For example, values for 'priority' could be 'Urgent', 'Normal' and 'No rush'. Each task should then have a value assigned to it. Ideally I would like it only to have one possible value per user field. So following the examples above a task can not be 'urgent' and 'normal' at the same time. This is another thing I need to figure out, so any hints are welcome, but outside the scope of this question. Template and forms.py I created a form: class TaskForm(forms.ModelForm): class Meta: model = Task fields = ("title", "start", "end", "userfieldvalues") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].label = 'Task Title' self.fields['title'].widget.attrs['rows'] = 1 self.fields['start'].widget.format = '%H:%Mh, … -
Celery not publishing message to non-task based RabbitMQ Queue
I'm trying to connect a Django Rest Framework backend to RabbitMQ using Celery. I have a few micro-services that use RabbitMQ as a message bus between the backend and those services. When I have the backend call a task that pushes a message to the micro-services message bus the message is never put into the queue for one of those services to grab. The queues I declare in my tasks.py are being created in RabbitMQ but are not being used by any of the producers. testcelery/celery.py ... from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testcelery.settings") app = Celery("testcelery") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() testcelery/settings.py ... CELERY_BROKER_URL = "amqp://testuser@rabbitmq_host:5672" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" backend_processing/tasks.py ... from celery import shared_task from testcelery.celery import app as celery_app from kombu import Exchange, Queue test_queue = Queue("test_queue", Exchange("test"), "test", durable=True) @shared_task def run_processing(data, producer=None): with celery_app.producer_or_acquire(producer) as producer: producer.publish(data, declare=[test_queue], retry=True, exchange=test_queue.exchange, routing_key=test_queue.routing_key, delivery_mode="persistent") What do I need to modify in my configuration to allow celery to publish to queues other than the ones given to celery by the settings.py? -
Django table to grid formatting (data processing)
I'm prompting some data in a table format with django with a very simple table like: {% for column in myresult %} {% endfor %} {% for index, row in myresult.iterrows %} {% for value in row.values %} Pretty standard code found online which works very well in my newbye case. However, now I'm dealing with this table which I would really like to format like a grid, which involves some post processing of these data. The image example of what I have and what I would like to have is in this screenshot, much simpler than explaning it. https://imgur.com/a/tHhBaZC Basically every record represent in which column (variable 1), and in which row (variable 2) every value (variable 3) should fall. Which is the easier way to do this? Hope the question makes sense. -
not able to access Django project through Docker Compose
I have created a simple Docker file for DJango project and when I issue docker run, I am able to access through browser. docker run -p 8000:8000 s3bucket-ms:1 Here is the Docker File: FROM python:3.6.7-alpine ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install --upgrade pip RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install -r requirements.txt RUN mkdir /app WORKDIR /app ADD ./s3bucket /app/ CMD ["python", "./manage.py", "runserver", "0.0.0.0:8000"] However, when I am using Docker Compose , i can't access the project through the browser. Here is the docker-compose.yml version: '3' services: web: build: . command: python ./manage.py runserver 8000 ports: - "8000:8000" With Docker Compose , I also commented CMD within Docker File. Output from Docker Compose UP web_1 | Run 'python manage.py migrate' to apply them. web_1 | February 17, 2020 - 14:29:22 web_1 | Django version 3.0.3, using settings 's3bucket.settings' web_1 | Starting development server at http://127.0.0.1:8000/ web_1 | Quit the server with CONTROL-C. Am I missing something? Any help is appreciated. Thanks, -
Django-cors does not works
CORS is not working properly. Django I'm using lib django-cors to enable this, but it doesn't work. I believe I'm doing something wrongCould someone help me, please? I did everything, but it still doesn't work. I am very grateful for everyone's attention. Settings CORS_ORIGIN_ALLOW_ALL = True Middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware' ... ] Application INSTALLED_APPS = [ ... 'corsheaders', ... ] -
Django server won't run even if django is installed in the environment
I cannot configure Django and Miniconda on my Mac. I receive this error every time when I run python manage.py runserver: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forge t to activate a virtual environment? These are the steps I have followed so far: cd /Users/myuser/projects/My_Django_Stuff conda create --name MyDjangoEnv python=3.7 source activate MyDjangoEnv conda install django=2.2 django-admin startproject first_project cd first_project python manage.py runserver If I run conda list, django package appears to be installed in my environment: ca-certificates 2020.1.1 0 certifi 2019.11.28 py37_0 django 2.2.5 py37_1 libcxx 4.0.1 hcfea43d_1 libcxxabi 4.0.1 hcfea43d_1 libedit 3.1.20181209 hb402a30_0 libffi 3.2.1 h475c297_4 ncurses 6.1 h0a44026_1 openssl 1.1.1d h1de35cc_4 pip 20.0.2 py37_1 python 3.7.6 h359304d_2 pytz 2019.3 py_0 readline 7.0 h1de35cc_5 setuptools 45.2.0 py37_0 sqlite 3.31.1 ha441bb4_0 sqlparse 0.3.0 py_0 tk 8.6.8 ha441bb4_0 wheel 0.34.2 py37_0 xz 5.2.4 h1de35cc_4 zlib 1.2.11 h1de35cc_3 … -
How to write re_path url in django for reading special character?
I am working with Django URL pattern for my project. I am sending a String containing special characters and numbers. While reading a string in python function it won't get the ? in a function. html {% for user_name in userSet%} <a class="dropdown-item" href="/slackNotification/{{user_name}}/{{data.question}}">{{ user_name }}</a> {% endfor %} url path('slackNotification/<str:slack_user_name>/<str:question>',views.slackNotification) When I get the all details through URL then string whichever I received in the python code it won't contain ? mark even though my input contains Special characters and numbers. input: What is your name? output: What is your name(question mark not available;) Question I have tried this: re_path(r'^slackNotification/<str:slack_user_name>/(?P<question>\w+)',views.slackNotification) Output The current path didn't match any of the url I want to know the exact regular expression for my requirement ?? -
Mask with jquery
I applied a money format mask and did not accept the first digit to be 0. However, the following characters are still accepted "e, -, + ,." obs:field is decimal.The mask works but accepts these characters described I applied a money format mask and did not accept the first digit to be 0. However, the following characters are still accepted "e, -, + ,." obs:field is decimal.The mask works but accepts these characters described I applied a money format mask and did not accept the first digit to be 0. However, the following characters are still accepted "e, -, + ,." obs:field is decimal.The mask works but accepts these characters described below code with django valor_compra = forms.DecimalField(label=u'Valor de Compra (R$)', required=False, max_digits=11, decimal_places=2, min_value=1) valor_residual = forms.DecimalField(label=u'Valor Residual (R$)', required=False, max_digits=11, decimal_places=2, min_value=1) below the code in js //Adição das máscaras aos campos //Empresa $('#id_cnpj').mask('00.000.000/0000-00'); $('#id_telefone1').mask('(00) 000000000'); $('#id_telefone2').mask('(00) 000000000'); $('#id_fax').mask('(00) 000000000'); $('#id_cep').mask('00.000-000'); //Adiciona mascara e não aceita numero 0 var options = { onKeyPress: function (valor, e, field, options) { let item = parseInt($('#valor_compra').val().replace(/[,.]/g, '')); if (item === 0) { $('#valor_compra').val('').change(); } var masks = ['000000000.00', 'ZZ']; var mask = (valor.length >= 1) ? masks[0] : masks[1]; $('#valor_compra').mask(mask, options); … -
What will be the best backend for realtime react-native application?
I want to bulid a realtime application in react-native. I wanted to use python django as backend. But after some research, I realize that node.js is better option for this. I think it is easier to implement web sockets with nodejs. -
Bootstrap Modal Forms Posting Twice Django
I am following the instructions from django-bootstrap-modal-forms and what I am finding is that my form is posting or submitting twice when I submit the form. First, the object was simply being created twice, I could see that from the admin. Now it seems the form is creating the object, but also entering its validation state, which I obviously don't want if the form was successful, which it is. Has anyone experienced this? I've done nothing more than what was outlined in the docs that I linked to and I cannot identify any reason why this should be submitting twice. Here is my code: home.html <a href="#" class="create-shipment dropdown-itemcreatenew" onclick="closeNav()">Shipment</a> <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> </div> </div> </div> <script> $(document).ready(function() { $(".create-shipment").modalForm({ formURL: "{% url 'CreateShipmentView' %}" }); }); </script> views.py class CreateShipmentView(BSModalCreateView): template_name = 'create_shipment.html' form_class = CreateShipmentForm success_message = 'Success: Shipment Has Been Created!' success_url = reverse_lazy('HomeView') create_shipment.html (template for modal form) {% load crispy_forms_tags %} <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Create New Shipment</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{form|crispy}} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="submit-btn btn … -
Django: How to select the Columns containing Max and Min values from each row in a table?
I have a table with this shape: id | origin | ABC | DEF | ..... | XPTO 1 | ABC | 0 | a number | a number | a number 2 | DEF | a number | 0 | a number | a number As you can see, the values in origin column, are also columns. And every time a origin match a column, the value is 0. (This represents distances, so from itself the distance is 0). So I need to retrieve, for each row, the min and max values (excluding the value 0, greater than works) and also the columns that contain these values. For e.g, for the following table: id | origin | ABC | DEF | GHI | XPTO 1 | ABC | 0 | 10.2 | 2.5 | 27.0 2 | DEF | 45.8 | 0 | 20.34 | 4.0 Would be perfect if the query returns a list of dictionaries like this: [ {'origin': 'ABC', 'GHI': 2.5, 'XPTO': 27.0}, {'origin': 'DEF', 'XPTO': 4.0, 'ABC': 45.8}, ] -
how to integrate mailchimp and djnago
right now i'm using smtp gmail @api_view(['POST']) def Mail(request): orderId = '123' CreateInvoice(get_info(), DOCUMENTS_LOC + '/create' + '/GST_Invoice_'+str(orderId))#str(request.user.id) subject = "Cred mail" to_email = get_info() print(to_email) print(to_email['email']) from_email = settings.EMAIL_HOST_USER with open(settings.BASE_DIR + "/templates/modify_mail/user_mail.txt") as re: sending_txt = re.read() messages = EmailMultiAlternatives(subject=subject, body=sending_txt, from_email=from_email, to=['abc@gmail.com']) html_template = render_to_string("modify_mail/user_mail.html", {'detail': get_info()}) messages.attach_file(DOCUMENTS_LOC + '/create' + '/GST_Invoice_' + str(orderId) + '.pdf') #str(request.user.id) messages.attach_file(DOCUMENTS_LOC + '/create/' + str(orderId) + ".pdf") #str(request.user.id) messages.attach_alternative(html_template, "text/html") try: messages.send() return Response({'success': 'Mail Send.'}, 200) except: return Response({'error': 'Unable to send mail.'}, 400) its work properly but not i want to use mailchimp -
Django rest framework: How do I send and download xlsx file?
I have been stuck for awhile now trying to send a file to client side using django-rest-framework. I am able to send it as a byte but I don't know how to manage it client side to download it as an xlsx file. Everything I tried ends with a corrupted file. Here is what I have so far: # views.py from django.http import HttpResponse from openpyxl import load_workbook from openpyxl.writer.excel import save_virtual_workbook class DownloadApiView(APIView): authentication_classes = [BasicAuthentication, SessionAuthentication] permission_classes = (IsAuthenticated,) def post(self, request): try: file_path = './temp.xlsx' pk = request.data['xml_id'] report = Report.objects.get(pk=pk) wbrd = load_workbook(filename=file_path) bytes = save_virtual_workbook(wb) response = HttpResponse(bytes, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response['Content-Disposition'] = "attachment; filename=temp.xlsx" return response except Exception as error_msg: logger.error(error_msg) return Response({'error': 'Failed to retrieve file.'}, status=HTTP_400_BAD_REQUEST) # client js called onclick() function downloadFile(xmlID, type) { let url = '/api/download_report/'; let $submit = $.ajax({ type: 'POST', url: url, data: JSON.stringify(inputData), contentType: 'application/json', headers: {"X-CSRFToken": getCookie("csrftoken")}, }); $submit.done(function (data) { console.log(data); let a = window.document.createElement('a'); a.href = window.URL.createObjectURL(new Blob(data, {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})); a.download = 'temp.xlsx'; document.body.appendChild(a); a.click(); document.body.removeChild(a); }); } -
Pass checked items to python using JSON
I am trying to pass checked items to my python code in JSON using an ajax request. The checkboxes are defined in the forms.py file as: NOTES_OPTIONS = ( ('0', 'Please add 15% VAT'), ('1', 'Price is valid for 45 days'), ('2', 'All price is in Ethiopian Birr'), ('3', 'Delivery will be within 45 days after PO, advance and bank foreign currency approval'), ('4', 'Payment Term 50% advance and remaining amount after delivery'), ('5', 'Installation is NOT part of this Quote'), ('6', 'If there is discrepancy in price calculation the unit price will prevail') ) note_choices = forms.MultipleChoiceField(required = False, widget = forms.CheckboxSelectMultiple(attrs={'class': 'form-check-input'}), choices = NOTES_OPTIONS) and in my create_proposal.html file I have rendered this form as: <div class="row col-sm-12"> <div class="col-sm-9" style="margin-left: 10vw;"> <div class="container"style="margin-bottom: 20vw;"> <label><Strong>Choose notes to be included:</Strong></label> <ul> {{form.note_choices}} </ul> </div><br><br> </div> </div> I have a script in which I accept the values from the form inputs and pass them to my merge.py file: generalData = { 'file_name': document.getElementById('id_file_name').value, 'organization_name': document.getElementById('id_organization_name').value, 'project_type': document.getElementById('id_project_type').value, 'reference_number': document.getElementById('id_reference_number').value, 'our_reference_number': document.getElementById('id_our_reference_number').value, 'date': document.getElementById('id_date').value, 'exchange_rate': document.getElementById('id_exchange_rate').value, 'notes': document.getElementById('id_notes').value, 'vat': document.getElementById('id_note_choices').value, } $.ajax({ url: '/ajax/result/', data : { 'values': JSON.stringify(dataJson), 'general': JSON.stringify(generalData) }, method: 'GET', contentType: "application/json", dataType: 'json', success: … -
Django All-Auth django.contrib.auth.backends.ModelBackend invalid syntax
I am fairly new to Django so I have been following tutorials and guides to learn as I go along. I am currently attempting to do a E-commerce Django project following a youtube tutorial by freeCodeCamp. In the beginning you need to install Django-AllAuth which I have done. The issue I am currently having is when you need to migrate the installed apps it throws me a 'Invalid Syntax Error' on the 'django.contrib.auth.backends.ModelBackend' in the Authentication_Backends section in settings. My settings.py import os ENVIRONMENT = os.getenv('ENVIRONMENT', 'development') DEBUG = True BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '-05sgp9!deq=q1nltm@^^2cc+v29i(tyybv3v2t77qi66czazj' ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'core' ] 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' ] ROOT_URLCONF = 'ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_files')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, 'db.sqlite3') } } if ENVIRONMENT == 'production': … -
Django view gives error of Forbidden (CSRF token missing or incorrect.) while using the userdefined decorator for checking the session
I created the userdefined decorator to check the session is active or not. Following is the function defination def session_required(func): """ Decorator to check the session is active or not for logged in user :param func: Name of function for which you have to check the session is active or not :return: """ def wrap(request, *args, **kwargs): """ Wrapper function for the decorator :param request: request parameter for called URL :return: """ if not request.session.get("admin_id"): return redirect("/") func_return = func(request, *args, **kwargs) return func_return return wrap I am using this decorator on the respective function based view. At some places it works absolutely fine but when I do some POST or PUT operation then it gives me error Forbidden (CSRF token missing or incorrect.): My function based view is like @csrf_exempt @session_required def mover_profile_handler(request): """ mover profile handler function for viewing and editing the details :param request: :return: """ try: if request.method == "GET": login_id = request.session.get("admin_id") login_info_obj = Login.objects.get(id=login_id) mover_info_obj = Mover.objects.get(fk_login=login_info_obj) country_obj = Country.objects.all() currency_obj = CurrencyType.objects.all() subscription_detail = SubscriptionMoverDetail.objects.filter(fk_mover=mover_info_obj).order_by("-id") # Extracting data for showing the subscription package details current_subscription_detail = {} subscription_detail_history = [] for index, item in enumerate(subscription_detail): subscription_master_detail = SubscriptionMaster.objects.get(id=item.fk_subscription_master_id) subscription_detail_json = { "plan_name": subscription_master_detail.subscription_plan_name, … -
how to calculate leave entitlement of staff base on the number of years he/she was hire
I am having difficulty to put this calculation together in my views.py : base on my hire date, I should be entitle for an annual only after serving one year in office otherwise i should not be entitle for a and annual leave