Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to send django formset data to server with ajax?
I try send data to server after submit form, but my script not working. I have multiple forms. One of them used from django-formset. Forms: class UploadReceiptForm(forms.ModelForm): class Meta: model = Receipt fields = ('payment_type', 'payment_mandatory_code', 'payment_optional_code', 'payment_date', 'payment_amount', 'image', 'description') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['payment_type'].required = True self.fields['payment_mandatory_code'].required = True self.fields['payment_date'].required = True self.fields['payment_date'].input_formats += ['%Y/%m/%d'] self.fields['payment_amount'].required = True self.fields['image'].required = True def save(self, rrr): receipt: Receipt = super().save(commit=False) receipt.review_request = rrr receipt.save() return receipt def clean(self): cleaned_data = self.cleaned_data payment_type = cleaned_data['payment_type'] if payment_type == Receipt.PaymentTypes.LETTER_OF_ATTORNEY.value: cleaned_data['payment_amount'] = 0 return cleaned_data def clean_payment_date(self): j_date = self.cleaned_data['payment_date'] try: j_year, j_month, j_day = [int(x) for x in str(j_date).split('-')] except ValueError: raise ValidationError("تاریخ به فرمت صحیحی وارد نشده است") try: date = jdatetime.date(j_year, j_month, j_day).togregorian() except Exception as ex: raise ValidationError("تاریخ به فرمت صحیحی وارد نشده است") return date def clean_description(self): desc = self.cleaned_data['description'] if desc and len(desc) > 300: raise ValidationError("توضیحات باید کمتر از 300 حرف باشد") return desc UploadReceiptFormSet = formset_factory(UploadReceiptForm, extra=0, can_order=False, can_delete=False, max_num=20,validate_max=20, absolute_max=20, can_delete_extra=False) Class base view: class ReceiptReviewRequestView(PermissionRequireMixin, TemplateView): template_name: str = "gentelella/rrr_form.html" admin_view = False data = [] def get(self, request, *args, **kwargs): if not self.has_permission(): return self.redirect_to_login() context = self.get_context_data(**kwargs) context["form"] … -
django-dash: callback generated div id tag not found by other callback
I have been working with plotly dash and especially django-dash for a while, and I am now facing an issue that I am not able to resolve. I am confusedbecause I have successfully used the same structure in the past. Hopefully a pair of fresh eyes could help me see what I am messing up. Here is what I have: => first callback acquires data from a django session and that is used to create a dropdown menu that contains some dataframe extracted values: @app.expanded_callback( Output('output_two', 'children'), [Input('dummy', 'value')] ) def clean_data(file_path,**kwargs): file_path = file_path path = kwargs['request'] path = path.session.get('path') print("path", path) ifc_file = ifcopenshell.open(path) work_plans = ifc_file.by_type("IfcWorKPlan") work_plans_df = pd.DataFrame({ 'id': [schedule.id() for schedule in work_plans], 'StartTime': [schedule.StartTime for schedule in work_plans], 'FinishTime': [schedule.FinishTime for schedule in work_plans], }) work_plans_df['StartTime'] = pd.to_datetime(work_plans_df['StartTime']).dt.date work_plans_df['Status'] = "En cours" work_plan_id = work_plans_df['id'].unique() return html.Div(children=[html.Div( className='five columns', children=[ dcc.Dropdown( id="dropdown", options=list({'label': Id, 'value': Id} for Id in work_plan_id ), value='', ), ], ), ], ) Now, the second call should be using the submited dropdown value and use it to output something (I won't put the details of the calculations) @app.callback( Output('dd-output-container', 'children'), Input('submit-val', 'n_clicks') ,State('dropdown','value') ) def process_workplans(path, n_clicks,value,*args,**kwargs): if value … -
Duplicate Data Stored in django via celery task
I think celery task is calling twice Here is my code @task(run_every=crontab(minute="*/1"), queue="accountability") def analyse(): with transaction.atomic(): analyzed_record, _ = Model.objects.get_or_create( invoice_tag=invoice_tags, product_name="demo" ) analyzed_record.current = 0 analyzed_record.prev = 1 analyzed_record.invoiced = 2 analyzed_record.save() I am using this celery args celery worker --beat --app=demo --concurrency=10 --loglevel=INFO -Q calculate_cost,accountability,scriptQ,ScriptQ,defaultQ I am expecting that if i am using get_or_create then object data must be unique -
What is U0 in postgresql?
I have a django query: review_and_rating_objs = ReviewAndRating.objects.filter(rating__gte=4) products = Product.objects.distinct().filter(reviewandrating__in=review_and_rating_objs) The silmilar query in raw sql(when I print products.query): SELECT DISTINCT * FROM product_product INNER JOIN product_reviewandrating ON (product_product.id = product_reviewandrating.product_id) WHERE product_reviewandrating.id IN (SELECT U0.id FROM product_reviewandrating U0 WHERE U0.rating >= 4) I can't understand what U0 is doing here in the sql. What is meant by U0? I have searched in google and youtube. No explanation found on this question(may be I couldn't search properly). I'm a newbie in django and postgresql. Please experts help me understand this. Thanks in advance. -
How to test methods in models.py related to filters in django using pytest?
I have models which contains lots of classmethods for filtering different kinds of data. Now the problem is, these classmethods are called in views for several functionality. For example, I have Order table as shown below: class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) total = models.DecimalField(max_digits=12, decimal_places=2, default=0) order_date = models.DateTimeField(auto_now_add=True) cancelled = models.BooleanField(default=False) items = models.ManyToManyField(Items, through='OrderItems') status = models.CharField(max_length=30, choices=choice_status, default='waiting') restaurant = models.ForeignKey(Restaurant, on_delete=models.SET_NULL, related_name='orders', null=True) razorpay_payment_id = models.CharField(max_length=100, null=True, blank=True) razorpay_order_id = models.CharField(max_length=100, null=True, blank=True) mode = models.CharField(max_length=10, choices=choice_mode, default='COD', null=True, blank=True) paid = models.BooleanField(default=False, null=True, blank=True) delivery_charges = models.DecimalField(max_digits=12, decimal_places=2, default=0) user_address = models.TextField(max_length=500) user_address_lat = models.DecimalField(max_digits=9, decimal_places=6) user_address_long = models.DecimalField(max_digits=9, decimal_places=6) restaurant_address = models.TextField(max_length=500) restaurant_address_lat = models.DecimalField(max_digits=9, decimal_places=6) restaurant_address_long = models.DecimalField(max_digits=9, decimal_places=6) @classmethod def get_order_with_search_params(cls, params, queryset): search_order_id = None with contextlib.suppress(ValueError): search_order_id = int(params) return queryset.filter( Q(user__username__icontains=params) | Q(restaurant__name__icontains=params) | Q(id=search_order_id) ) @classmethod def get_order_from_status(cls, params, queryset): return queryset.filter(Q(status=params.lower())) @classmethod def get_order_from_restaurant_id(cls, params, queryset): restaurant_id = None with contextlib.suppress(ValueError): restaurant_id = int(params) return queryset.filter(Q(restaurant_id=restaurant_id)) @classmethod def get_object_from_pk(cls, pk): return get_object_or_404(cls, pk=pk) @classmethod def get_total_of_all_orders(cls, queryset=None): if not queryset: queryset = cls.objects.all() return queryset.filter(status='delivered').aggregate(total_sum=Sum('total'))['total_sum'] Now to test these functionality, I have to first have to do following: register user (restaurant type) activate this user … -
How to send smtp email using python django project in cpanel?
When tried to send email using smtp in cpanel but so error error: [Errno 111] Connection refused. Here is my code in django view.py subject = 'Requested For Application Form' message = f'Email successfully send' email_from = settings.EMAIL_HOST_USER recipient_list = ['bedag12032@fanneat.com'] send_mail(subject, message, email_from,recipient_list,fail_silently=False) return redirect('/home') setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'pematep658@lubde.com' EMAIL_HOST_PASSWORD = 'okoik9sa54as' Tried to send email using smtp in cpanel in python django but error [Errno 111] Connection refused. -
How can i achive atomicity just like django orm in fastapi with sqlalchmey orm
How can i achive atomicity just like django orm in fastapi with sqlalchmey orm. What i am trying to do is making a cron script which will delete data from s3 bucket and DB a lot of data. If some how s3 operation fails and it creates inconsistency or either case s3 pass and DB fails. So I want to achive atomicity like we have in django "with atomic transactions". What i am trying to do is making a cron script which will delete data from s3 bucket and DB a lot of data. -
How can I know whether the code is running under testing? Globally?
Now that we can know whether the code in running under DEBUG mode: https://stackoverflow.com/a/16648628/2544762 But at the same time, when we run the code in a unittest, we always got debug == False. https://docs.djangoproject.com/en/4.1/topics/testing/overview/#other-test-conditions In my own case, I just really want to make some code under debug condition, and want it to be tested with debug == True, how can I do? So, is there any way to detect whether the code is running with test? In any place. -
How to load static file of a model in a html templates
I have a static file structure like this -----> static/images/article_images/images.png here's my settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static", # '/css/', # 'images/article_image/', ] here's what I tried: {% extends "base.html" %} {% block content %} {% load static %} ---> i have this in my base.html <div class="article-block" method="GET"> {% for article in articles %} <!-- <img src="{{ article.image }}" alt="Article image"> --> <img src="{% static '{{article.image}}' %}" alt="Article image"> <h2>{{ article.title }}</h2> <p>{{ article.content }}</p> {% endfor %} </div> {% endblock %} -
How to run "SELECT FOR UPDATE" instead of "SELECT" when changing and deleting data in Django Admin?
I have the code below: # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): pass Then, when changing data as shown below: SELECT is run instead of SELECT FOR UPDATE as shown below: And, when clicking Delete button of Change person as shown below: Then clicking Yes, I'm sure button to delete data as shown below: SELECT is run instead of SELECT FOR UPDATE as shown below: Now, I want to run SELECT FOR UPDATE instead of SELECT for both cases as shown above. So, how can I do this? -
Get model from multiple apps at once using apps.get_model
I am creating an API that can access multiple apps in a single project and get model from from all of these apps for that I tried this: def get(self, request, **kwargs): m = request.GET['model'] depth = request.GET['depth'] print("model") model = apps.get_model('masters', str(m)) obj1 = model.objects.all() It is working fine when I wanna import model from a single app but in my project I have multiple apps linked together and for this I tried: model = apps.get_model(['masters','dockets'], str(m)) but got an error TypeError: unhashable type: 'list'. apps.get_model doesn't take list but is there any workaround to this? -
In Django version(4.1.4) I am not able to access CSS file I m beginner, searched in google tried everything but still not able to solve this problem
setting.py static file congfigured in setting.py STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'Ecommerce/static/css' ] store.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> I am creating project Ecommerce with python and django and want to use external css, image ,JS in project but my css in not working i tryed googling it but nothing helped me i am using django 4.1.4 version -
When adding a record in django admin, when a field is selected, the other field comes automatically
In order to make the problem easier to understand, I am writing the codes as short as possible here. models.py: ---------- class Room(models.Model): room_no = models.CharField() class Unit(models.Model): unit_name = models.CharField() room = models.ManyToManyField(Room, related_name='roomunit') class Employee(models.Model): employee_name = models.CharField() unit = models.ForeignKey(Unit) room = models.ForeignKey(Room) admin.py: --------- class EmployeeAdmin(admin.ModelAdmin): list_display('employee_name', 'unit', 'room',) class RoomAdmin(admin.ModelAdmin): list_display=('room_no',) class UnitAdmin(admin.ModelAdmin): list_display=('unit_name', 'roomno',) def roomno(self,obj): r = Room.objects.get(roomunit=obj) return r admin.site.register(Employee, EmployeeAdmin) admin.site.register(Unit, UnitAdmin) admin.site.register(Room, RoomAdmin) Screenshot of the form The unit_name and room_no data have already been saved. There is ManyToMany relation between Unit and Room. Screenshot of Employee add form. This is what i want to do: When I select unit_name, I want the room_no field to come automatically according to the unit_name. -
Custom Authentication in Django Rest Framework
I have a django rest framework application with custom authentication scheme implemented. Now I want to allow external app call some methods of my application. There's an endpoint for external app to login /external-app-login which implemented like this: class ExternalAppLoginView(views.APIView): def post(self, request): if request.data.get('username') == EXTERNAL_APP_USER_NAME and request.data.get('password') == EXTERNAL_APP_PASSWORD: user = models.User.objects.get(username=username) login(request, user) return http.HttpResponse(status=200) return http.HttpResponse(status=401) Now I want to add authentication. I implemented it like this: class ExternalAppAuthentication(authentication.SessionAuthentication): def authenticate(self, request): return super().authenticate(request) But authentication fails all the time. What is the correct way to do it? I want to store login/password of external app in variables in application, not in database. -
This problem occured wile I was running my final solution in github . There is some minimal settings problem
I am working in github and while running it in final stage i get this error which I am not able to resolve . Origin checking failed - https://gagandeep141-congenial-xylophone-946j465ww4hj4g-8000.preview.app.github.dev does not match any trusted origins. I tried changing settings and expecting the solution -
How to install django-recaptcha in cpanel?
I'm tring to install django-recaptcha in cpanel but so error Unable to find from captcha.fields import CaptchaField Here is my code in django form.py from django import forms from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV2Checkbox class RequestForm(forms.Form): captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox()) views.py from django.views.generic import FormView # Create your views here. class HomePage(FormView, ): template_name = 'AppForm/homepage.html' form_class = RequestForm def post(self, request, **kwargs): if request.method != 'POST': return redirect('/error') else: form = RequestForm(request.POST) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret' : settings.RECAPTCHA_PRIVATE_KEY, 'response' : recaptcha_response } data = urllib.parse.urlencode(values).encode("utf-8") req = urllib.request.Request(url, data) response = urllib.request.urlopen(req) result = json.load(response) print(result) if result['success']: return redirect('/thankyou') else: return redirect('/error') else: return redirect('/error') setting.py INSTALLED_APPS = [ 'captcha', ... ] RECAPTCHA_PUBLIC_KEY = '6LdfgjhkgdsfhghjdfAAAPf1mAJmKucssbD5QMha09NT' RECAPTCHA_PRIVATE_KEY = '6Ldfgjhkg3kgAA83DFJwdkjhfkjdkshjkfFR1hXqmN8q' SILENCED_SYSTEM_CHECKS = ['captcha.recaptcha_test_key_error'] In Local system it run, but in cpanel unable to install django-recaptcha Unable to find from captcha.fields import CaptchaField -
ForeignKey form search via Text as opposed to Drop-Down - Django
I am working on a flight booking website on Django. In my models.py, I have two models; one called Airport and one called Flight. The Flight class has two variable's called 'Departure' and 'Destination' which inherit from from the Airport class via ForeignKey. Ultimatelly, I want the user to be able to select a departing airport and a destination airport. Now,I am limited to the drop-down option when trying to querry airports. Can someone please explain a way to go about editing my form to where a user can type in an Airport name and the stored values will appear based on the users search. (ex: A user enters "los " and "Los Angeles" appears and can be selected. Models.py from django.db import models class Airport(models.Model): city = models.CharField(max_length=50) code = models.CharField(max_length=3) def __str__(self): return f"{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="origin") destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="destination") length = models.IntegerField(null=False) def __str__(self): return f"{self.id} - {self.origin} to {self.destination}" Below, in my forms.py file; I have added a widget dict which has allowed me to now enter in a value to the form as opposed to having a drop down menu. However, it does not suggest results based on … -
DJANGO - How To Use Regex for Thesis Author Format?
I have one CharField for author/s but I want the input to follow certain format. For example: Cruz, R. (for only one author) Cruz, R. and Gray, A. (for two author) Cruz, R. and et. al. (for three or more author) Here is my code in forms.py to validate the format, but it doesn't seem to be working properly especially when I add this '|' sign for or condition: def clean_author(self): pattern = '[A-Za-z][,][A-Z]{1}[.] | [A-Za-z][,][A-Z]{1}[.][and][A-Za-z][,][A-Z]{1}[.] | [A-Za-z][,][A-Z]{1,2}[.][" et. al."]' get_author = self.cleaned_data['author'] if not re.search(pattern, get_author): raise ValidationError("Invalid author format has been detected") return get_author I'm new to regex so I don't really have that much knowledge on it. -
Why does manage.py runserver showing this instead of server link?
Started this project 2 days ago, yesterday I was trying to run instead it was showing this: (env.0.5) D:\Web\ecom\mosh>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\shuvo\appdata\local\programs\python\python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\shuvo\appdata\local\programs\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "c:\users\shuvo\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'tags' Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "D:\Web\ecom\mosh\env.0.5\lib\site-packages\django\core\management\base.py", line … -
django-tinymce convert url option do not work
TINYMCE_DEFAULT_CONFIG = { 'convert_urls' : False, 'relative_urls' : False, } Even with the above settings applied, tinymce still outputs files in the format ../../../../../../../static/images/example.png, not /static/images/example.png. Get the path. Changing convert_urls setting is not possible in django settings.py? -
Configure static files for django project live on ubuntu
I've finally got my project up and running after painful sleepless nights but I now can't get my images to show on my site. I managed to get my css to show but nothing else. Ill post as many screen shots and snippets as I can to see if anyone can help me. Info for what ive done so far: I've given my self permissions on static and static files folder with chmod commands and enabled it so I can use var/www/ roots. With the commands I've done and configurations I've set I can no longer collect static due to an error given: PermissionError: [Errno 13] Permission denied: '/staticfiles' Also if i open images that i upload to my site in a new window the extension shows as mysite.com/images/images/test4.jpg Current folder mapping in settings Current folder mapping in ubuntu /var/www/ Django Roots and URLS MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, '/images') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/staticfiles') CKEDITOR_UPLOAD_PATH = "uploads/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] sites-enabled settings server { listen 80; server_name ive put my ip here; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { root /var/www; } location / { include proxy_params; proxy_pass … -
libcurl link-time version (7.76.1) is older than compile-time version (7.86.0)
Whenever I start celery worker in my django project, it fails to start with the following error: "Unrecoverable error: ImportError('The curl client requires the pycurl library.') I have visited all the github issues and questions posted on stackoverflow but unable to pinpoint this issue. My pycurl installation is done successfully and if I run python -c 'import pycurl' && echo "Success". It returns me success but whenever I run celery worker it still gives me the pycurl error. I was expecting celery to run successfully but in return I get an import error. If I go to the kombu package which is installed and try to print traceback value then it outputs: pycurl: libcurl link-time version (7.76.1) is older than compile-time version (7.86.0) brew info openssl output is as follow: openssl@3 is keg-only, which means it was not symlinked into /usr/local, because macOS provides LibreSSL. If you need to have openssl@3 first in your PATH, run: echo 'export PATH="/usr/local/opt/openssl@3/bin:$PATH"' >> /Users/<>/.bash_profile For compilers to find openssl@3 you may need to set: export LDFLAGS="-L/usr/local/opt/openssl@3/lib" export CPPFLAGS="-I/usr/local/opt/openssl@3/include" For pkg-config to find openssl@3 you may need to set: export PKG_CONFIG_PATH="/usr/local/opt/openssl@3/lib/pkgconfig" brew info curl output is as follows: curl is keg-only, which means it … -
Simple User to User Rating function in Django
I am trying to add a field in my Django Project that will enable users to leave a review on another user's profile page. I understand that I need two ForeignKeys in my models.py, one for the user that will write the review and another for the user's profile where the review will be written on. I tried adding a Profile FK but I'm really not sure how to go about this or even what to include under the Profile class. This is what I tried so far but I am getting an error that says: ValueError at /profile/7/ Cannot assign "<User: username>": "Review.profile" must be a "Profile" instance I also need help with my views.py because as I play around the error message, I was able to finally post the review but it appears on the User's profile who wrote the review instead of the actual profile that I wanted to wrote it to. I am new to coding and tried really hard to read the django documentation about it but I can't really get past this one. models.py: class User(AbstractUser): name = models.CharField(max_length=200, null=True) email = models.EmailField(unique=True, default='') avatar = models.ImageField(null=True, default="defaultDp.jpg") location = models.CharField(max_length=200, null=True) class Profile(models.Model): … -
403 Forbidden CSRF Verification Failed React Django
Good day, i have been trying to set the csrftoken, so my login would be safe. I have followed the instructions of this stackoverflow question, but had no luck. I have done some experimenting by setting SESSION_COOKIE_SECURE to False and setting CSRF_COOKIE_SECURE to False. I've tried also tried different types of naming the X-CSRFToken in the headers to csrftoken and X-CSRFTOKEN but none of them worked. Any suggestions? views.py @ensure_csrf_cookie def login_view(request): if request.method == "POST": data = json.loads(request.body) # Attempt to sign user in username = data.get("username") password = data.get("password") settings.py SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE=True login.js function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); fetch('/api/login', { credentials:'include', method: 'POST', headers: { 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ username: username, password: password }) }) <form onSubmit={handleSubmit}> <CSRFToken/> </form> csrftoken.js import React from 'react'; function getCookie(name) { let cookieValue = null; … -
TemplateSyntaxError at /bag/ 'bag_tools' is not a registered tag library
I know this has been asked before but none of the suggested solutions have worked for me. I have a main project directory, in this is a file called template tags, which includes the file bag_tools.py and and an init.py file. The app 'bag' is included in installed apps in settings of the main project directory. The workspace has been restarted several times. All migrations have been made. Im stumped! Any suggestions?