Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Node.js and Django sharing a Postgresql database
I've built an application in Node.js and it's using a postgresql database. It's a mobile application for Android, which allows users to upload an image to the application using their mobile phone. We have another application that uses Django, and a model in python that uses OCR to extract text from images, and stores them in a table. I want to use the python code to run on the images that have been uploaded by the user using the mobile app, and process the image text and store it against the user record in the database. My problem is that the Node.js database doesn't use auth_user as the main table for users and I am unable to connect django to the existing postgresql db, because the tables are not standard django models. Any advice? The mobile app is how we collect images and pdfs, but python is the code that uses OCR and an ML library to process this - and we want to display them back to the user through the mobile app. Thanks p.s.: The database is hosted on Google Cloud, where all the images are stored too. -
TemplateDoesNotExist at / but filesystem loader says it does | happening in an extends tag
I am using Django 1.5.1 with Python 2.6.6. The error that I am getting is TemplateDoesNotExist at / when using the template extends {% extends "t_base_menu.html" %} The template that holds the extends is in the project/home/templates/home/index.html. The loader setting are (SITE_ROOT is correct): TEMPLATE_DIRS = ( join(SITE_ROOT, 'templates'), ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) In the error page the Template-loader postmortem says it exists, using django.template.loaders.filesystem.Loader: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /project/templates/t_base_menu.html (File exists) I have noticed that it is working if I move the t_base_menu.html to the project/home/templates folder. What am I missing? -
Form object not iterable in Django
I want to assign the input of a form to a function in my view but I keep getting this error. Please help do I fix it. Error receiver = list(ToolsForm.declared_fields['receiver_mail']) TypeError: 'CharField' object is not iterable -
Django returns image data as None
My utils.py: import base64, uuid from django.core.files.base import ContentFile def get_report_image(data): f , str_image = data.split(';base64,') print(f) print(str_image) decoded_img = base64.b64decode(str_image) img_name = str(uuid.uuid4())[:10] + '.png' data = ContentFile(decoded_img, name=img_name) return data When I try to get a report, I get the 500 server error: Internal Server Error: /reports/save/ Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38\ go\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\1\AppData\Local\Programs\Python\Python38\ go\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, * File "C:\Users\1\PycharmProjects\StasProject\sales_proje line 13, in create_report_view img = get_report_image(image) File "C:\Users\1\PycharmProjects\StasProject\sales_proje line 5, in get_report_image f , str_image = img.split(';base64,') AttributeError: 'NoneType' object has no attribute 'split' Although, in the browser console I can find 23 kbs of the data that goes as data:image/png;base64, and a bunch of characters. I'm trying to get the latter. Why does it not see the data? I have views.py as this: from django.shortcuts import render from profiles.models import Profile from django.http import JsonResponse from .utils import get_report_image from .models import Report def create_report_view(request): if request.is_ajax(): name = request.POST.get('name') remarks = request.POST.get('remarks') image = request.POST.get('image') img = get_report_image(image) Report.object.create(name=name, remarks=remarks, image=img, author=author) author = Profile.objects.get(user=request.user) return JsonResponse({'msg': 'send'}) return JsonResponse({}) -
How to run django orm query without using field name?
So i have one json data that contain field name of model as json key with value. i want to run orm query and define field name on run time. Ex: json_data = {"postgres_id":"10"} query = AcronymSecurityControlMaster.objects.get(postgres_id=10) json_data = {"age":"10"} query = AcronymSecurityControlMaster.objects.get(age=10) -
DRF is not re-evaluating queryset as expected gotcha
This is a question about whether DRF is working as it should or whether it could be improved to account for this use case. I have a simple API that returns a custom queryset like this: class WorldRankingViewset(viewsets.ReadOnlyModelViewSet): queryset = Ranking.objects.world_ranking() Where the custom queryset is: class RankingQuerySet(models.QuerySet): def world_rankings(self, rank_type="World"): # get most recent update update = RankingUpdate.objects.issued().filter(rank_type=rank_type, date__lte=TODAY).order_by("-asat", "-date").first() # if there is one, get all the player rankings for that update if update: return self.filter(update=update, player_id__gt=0, points__gt=0) else: return self.none() In the generics.py code of DRF, the get_queryset function has this code: def get_queryset(self): .... queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset Given the comment "Ensure queryset is re-evaluated on each request" I was expecting it to do that. However, when I run my API test, the following sequence happens. Evaluation queryset Run setUpTestData() to populated data for test Make call to api without re-evaluating queryset Return no data If I put a custom get_queryset code into the api then it all works as I would expect and returns test data: class WorldRankingViewset(viewsets.ReadOnlyModelViewSet): queryset = Ranking.objects.none() def get_queryset(self): return Ranking.objects.world_rankings() Run setUpTestData() to populated data … -
django.core.exceptions.FieldError: Unknown field(s) (PhoneNumber, City, Email, KYCDocument, Image, Speciality) specified for Doctor
I am trying to make a form using modelsform, it was working fine but, suddenly I don't know what suddenly happens and it started giving me this error django.core.exceptions.FieldError: Unknown field(s) (PhoneNumber, City, Email, KYCDocument, Image, Speciality) specified for Doctor I have checked this error online and tried some solutions but nothing workout form me . here is forms.py file from django import forms from .models import Doctor class Doctorslist(forms.ModelForm): class Meta: model = Doctor fields = ('name','PhoneNumber','Email','City','Speciality','Image','KYCDocument') here is models.py file from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Doctor(models.Model): name = models.CharField(max_length=20) phone_number = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField(max_length = 100) city = models.CharField(max_length=100) speciality = models.CharField(max_length=50) doc_image = models.ImageField(upload_to = 'blog_images', verbose_name = "Image") kycdocument = models.ImageField(upload_to = 'blog_images', verbose_name = "kycImage") -
create page like html with some header and footer
i want to create some html page with div shape like some ms word pages, with some header and footer for every pages, this is not that hard with some dive with fixed height and width but i want to use table on them as the tables grew and become bigger than page height another page with same footer and header created. i can use of server side languages with template like Django or javascripts is allowed too -
Django generate one-time password for admin site
So I want to generate a one-time password, "everytime" there a new login to admin site (let say I set timeout for 30 minutes or so), and send that password via email or else. Thankyou:) -
Django erroneously triggers the post_save signal on instance delete
I'm trying to send an email notification when an Article instance is created or modified. I use signals and send_mail. Everything works great while I just create and modify articles. But, if I delete an Article, I've got a notification that it was updated! This is incorrect behavior. What can be a reason (and solution)? models.py from django.core.mail import send_mail from django.db.models.signals import post_save from django.dispatch import receiver # ... class Article(TimeStampedModel): title = models.CharField(_('Title'), max_length=255, db_index=True) slug = AutoSlugField(_('Slug'), unique_with=['year', 'month'], populate_from="title", db_index=True) picture = models.ImageField(verbose_name=_('Image'), upload_to = upload_to) category = models.ForeignKey('Category', blank=True, null=True, on_delete=models.SET_NULL, db_index=True, related_name='articles') author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) annotation = models.TextField(_('Brief annotation'), blank=True) # Brief annotation (1 paragraph) date = models.DateTimeField(_('Date'), default=timezone.now, db_index=True) modified = models.DateTimeField(_('Modified'), db_index=True, auto_now=True) year = models.PositiveIntegerField(_('Year'), db_index=True, blank=True) month = models.CharField(_('Month'), db_index=True, max_length=2, blank=True) is_published = models.BooleanField(_('Is published'), default=False) def delete(self, *args, **kwargs): # Remove the media files of the article together with their folder from django.core.files.storage import default_storage if self.picture: with contextlib.suppress(FileNotFoundError): default_storage.delete( self.picture_thumbnail.path ) self.picture.delete() path = os.path.join(settings.MEDIA_ROOT, settings.CKEDITOR_UPLOAD_PATH, 'news', str(self.year), str(self.month), str(self.slug)) if os.path.isdir(path): shutil.rmtree(path) # Remove folder super().delete(*args, **kwargs) def __str__(self): # Потом допилить, чтобы год и месяц тоже выводился return self.title # There can be … -
Function() got multiple values for argument 'pk'
My program currently needs to print reports for each database entry in the settings model. It reads the pk of the model and uses that to check the items of the settings entry. However I get a trialBalanceMonthly() got multiple values for argument 'TBMreports_pk' error when I click on the button that is supposed to print the report. Here is my code : reportsHome.html: {% for x in model %} <a href="#" class='list-group-item active'>{{ x.Complex }} Reports</a> <div> <hr> <a href="{% url 'trialBalanceMonthly' TBMreports_pk=x.pk %}" type="button" class="btn btn-outline-primary btn-sm" >{{ x.Complex }} Trial Balance Monthly</a> <a href="{% url 'trialBalanceYearly' TBYreports_pk=x.pk %}" type="button" class="btn btn-outline-primary btn-sm" >{{ x.Complex }} Trial Balance YTD</a> <br> <a href="{% url 'incomeStatementMonthly' ISMreports_pk=x.pk %}" type="button" class="btn btn-outline-primary btn-sm" >{{ x.Complex }} Income Statement Monthly</a> <a href="{% url 'incomeStatementYearly' ISYreports_pk=x.pk %}" type="button" class="btn btn-outline-primary btn-sm" >{{ x.Complex }} Income Statement YTD</a> <hr> </div> <br> {% endfor %} Views.py (I have removed some of the code that generates the variables to make this a more reproducible question) --This is what each of the reports views functions look like def trialBalanceMonthly(TBMreports_pk): pkForm = get_object_or_404(SettingsClass, pk=TBMreports_pk) complexName = pkForm.Complex ### Printing Trial Balance PDF response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; … -
How to fix 504 error caused by Docker image update
I have Django project. It works with nginx, uwsgi and google cloud run. This project is using docker which python:3.9 image. I have got this error since 17,Aug. 2021-10-13 17:22:29.654 JSTGET504717 B899.9 sGoogleStackdriverMonitoring-UptimeChecks(https://cloud.google.com/monitoring) https://xxxx/ The request has been terminated because it has reached the maximum request timeout. To change this limit, see https://cloud.google.com/run/docs/configuring/request-timeout and also this error occur on all my pages. However when I open my pages myself, I can see my pages. It means I can't see this 504 error by myself. I added a line in admin.py at 17, Aug. I didn't think this line is no related with this error. Because this change is only effect in admin page. However I needed confirm what is cause this error. So I had rollback my code before the error. Now I'm still can't fix this error. Builded docker image is different size before after error. And Vulnerability has decreased. I think this is caused by some small change on python image. In this case, how can I solve this problem? What I did I changed docker image to python:3.8 and python:3.9.6-buster. I couldn't fix the error. -
I want to improve performance of my api endpoint(DJANGO)
I'm using Django rest to request data of customers from an endpoint suppose the endpoint is '/customers/list' and my Query set is to get all customers queryset = Customers.objects.all() I am expecting to get so many customers which will affect the performance of the application that will consume this endpoint. I am not willing to return the result set paginated so how can i improve the response time in case of too many records are processed. -
How can i solve the heroku deployment application error?
When you run py manage.py runserver, everything works without error. There was a need to test on the heroku server. When uploading to heroku, Application error occurs. An error appears in the heroku logs: 2021-10-13T07:44:14.143374+00:00 heroku[web.1]: Starting process with command `daphne Quiz.asgi:application --port 22236 --bind 0.0.0.0 -v2` 2021-10-13T07:44:16.405529+00:00 app[web.1]: Traceback (most recent call last): 2021-10-13T07:44:16.405551+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2021-10-13T07:44:16.405640+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2021-10-13T07:44:16.405651+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 170, in entrypoint 2021-10-13T07:44:16.405777+00:00 app[web.1]: cls().run(sys.argv[1:]) 2021-10-13T07:44:16.405779+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 232, in run 2021-10-13T07:44:16.405911+00:00 app[web.1]: application = import_by_path(args.application) 2021-10-13T07:44:16.405911+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/utils.py", lin e 12, in import_by_path 2021-10-13T07:44:16.405982+00:00 app[web.1]: target = importlib.import_module(module_path) 2021-10-13T07:44:16.405992+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, i n import_module 2021-10-13T07:44:16.406091+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-10-13T07:44:16.406101+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-10-13T07:44:16.406200+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-10-13T07:44:16.406262+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-10-13T07:44:16.406325+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-10-13T07:44:16.406387+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 855, in exec_module 2021-10-13T07:44:16.406469+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_remove d 2021-10-13T07:44:16.406527+00:00 app[web.1]: File "/app/./Quiz/asgi.py", line 9, in <module> 2021-10-13T07:44:16.406642+00:00 app[web.1]: from quiz_app.routing import ws_urlpatterns 2021-10-13T07:44:16.406642+00:00 app[web.1]: File "/app/./quiz_app/routing.py", line 3, in <module> 2021-10-13T07:44:16.406724+00:00 app[web.1]: from .consumers import … -
Django permissions using too much the database
We started investigation on our database as it is the less scalable component in our infrastructure. I checked the table pg_stat_statements of our Postgresql database with the following query: SELECT userid, calls, total_time, rows, 100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0) AS hit_percent, query FROM pg_stat_statements ORDER BY total_time DESC LIMIT 5; Everytime, the same query is first in the list: 16386 | 21564 | 4077324.749363 | 1423094 | 99.9960264252721535 | SELECT DISTINCT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" LEFT OUTER JOIN "auth_user_groups" ON ("auth_user"."id" = "auth_user_groups"."user_id") LEFT OUTER JOIN "auth_group" ON ("auth_user_groups"."group_id" = "auth_group"."id") LEFT OUTER JOIN "auth_group_permissions" ON ("auth_group"."id" = "auth_group_permissions"."group_id") LEFT OUTER JOIN "auth_user_user_permissions" ON ("auth_user"."id" = "auth_user_user_permissions"."user_id") WHERE ("auth_group_permissions"."permission_id" = $1 OR "auth_user_user_permissions"."permission_id" = $2) This sounds like a permission check and as I understand, it is cached at request level. I wonder if someone did a package to cache them into memcached for instance, or found a solution to reduce the amount of requests done to check those permissions? I checked all indices and they seem correct. The request is a bit slow mostly because we have a lot of permissions but still, the amount of calls … -
django multiplechoice field wont get saved
I have a simple form which has a checkbox for the users to choose some choices from.therefore, I created a model called InterestedField and connected my main model to it with manytomany method. this my main model: class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) isCompleted = models.BooleanField(default=False) interested_field = models.ManyToManyField(InterestedField) and this the InterestedField itself: class InterestedField(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) simple enough. then, I created this form like this: class InterestedFieldChoiceForm(forms.Form): InterestedFieldChoice = forms.ChoiceField() and these are my views and html template code: class PersonalView(View): template_name = 'reg/personal.html' def get(self, request, *args, **kwargs): context = {} interested_field = InterestedField.objects.all() context['interested_field'] = interested_field return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): user = request.user form = InterestedFieldChoiceForm() if form.is_valid(): interested_field = request.POST.getlist('InterestedFieldChoice') user.personalInfo.interested_field = interested_field[0] user.personalInfo.save() user.personalInfo.isCompleted = True user.personalInfo.save() user.save() return render(request, 'reg/done.html', context={'info_type': 'اطلاعات فردی'}) my html: <form id="personal-form" method="POST" action="{% url 'personal' %}" autocomplete="off" class="ant-form ant-form-horizontal"> <div class="ant-descriptions"> <div class="ant-descriptions-view"> {% for field in interested_field %} <label class="ant-col ant-col-md-6 ant-col-xs-8 ant-checkbox-wrapper {% if field in user.personalInfo.interested_field.all %} ant-checkbox-wrapper-checked {%endif%}" style="margin-left: 0; float: right;"> <span class="ant-checkbox {% if field in user.personalInfo.interested_field.all %} ant-checkbox-checked {%endif%}"> <input type="checkbox" name="InterestedFieldChoice" class="ant-checkbox-input" value="{{field.id}}"> <span class="ant-checkbox-inner"></span> </span> <span>{{field.title}}</span> … -
wsgi.url_scheme http in docker using nginx
I am using Apache on CentOS. On this server I have a Django project with docker. There are two containers in docker (nginx and python). In the Apache I have .conf that have proxy to nginx container that is exposed on port 803. SSL is set in the Apache conf as well. ProxyPreserveHost On RequestHeader set X-Forwarded-Proto "https" RequestHeader set X-Scheme "https" ProxyPass / http://127.0.0.1:803/ ProxyPassReverse / http://127.0.0.1:803/ On the docker I have app.conf for nginx that looks like this: upstream project { server project-python:5000; } server { listen 80; server_name _; error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; client_max_body_size 64M; location / { gzip_static on; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Scheme "https"; proxy_set_header X-Forwarded-Proto "https"; proxy_set_header X-Forwarded-Protocol "ssl"; proxy_set_header X-Forwarded-Ssl=on; proxy_set_header Host $host; proxy_pass http://project; proxy_redirect off; } } In the Dockerfile Python is exposed on port 5000 and in the docker-compose.prod.yml file for production the python is started with gunicorn with this command: gunicorn tmssms.wsgi:application --preload --bind 0.0.0.0:5000 So I have two issues. In the Django when I dump request.META I got wsgi.url_scheme that is http. The second one is that I don't even understand how nginx is communicating with gunicorn because when I set app.conf to be just … -
get data from somewhere and use boolean field
i try to write a view for getting data from somewhere that is not my database,and if this data was true mine be true and if was false mine be false too!!1any one have any idea?for example take data from another web site that you can by something,if main website let you buy,my site button be green if was close my site button be red,by the way i use Django -
Docker container not running - Docker-compose
I am trying to run a django-react app in docker containers and trying to deploy it on digital ocean. Here is my docker-compose script version: "3.9" services: web: image: "${WEB_IMAGE}" container_name: website command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/mediafiles ports: - 8000:8000 env_file: .env nginx: image: "${NGINX_IMAGE}" container_name: nginx volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/mediafiles ports: - 80:80 depends_on: - web tensorflow-servings: image: "${TENSORFLOW_IMAGE}" container_name: tensorflow_serving ports: - 8501:8501 depends_on: - web volumes: static_volume: media_volume: Here you see nginx and web are listed, but not web. I get 502 Bad Gateway - nginx/1.21.3 error -
Gettings errors during password validation in Django serializers?
my serializer class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['username', 'password'] #overwrite validate method to add some complexity to the password def validate(self, data): #here data is a ordered dict if not data: return Response("please enter name and password") password = data.get('password', '') print(password) user = CustomUser(**data) print(self.instance) messages = {} my_password_validators = [UserAttributeSimilarityValidator, MinimumLengthValidator, CommonPasswordValidator, NumericPasswordValidator] try: password_validation.validate_password(password, password_validators=my_password_validators) # the exception raised here is different than serializers.ValidationError except exceptions.ValidationError as e: print("here") print(e) messages['password'] = list(e.messages) # If some error then return those error if messages: raise serializers.ValidationError(messages) return super(RegistrationSerializer, self).validate(data) my error object of type 'NoneType' has no len() Password is coming alright but it is giving no length attribute, also i want to know how the username to be given to this method so that it can check password similarity with the username -
API Integration in Python
I'm doing project on COVID live tracking website, so in my project when selected particular state, type(vaccinated, cases, tests) and from selected date range i.e., from date range to date range so according to date and type mentioned the website needs to give output in form of graph. For live data I've the following API links https://data.covid19india.org/csv/latest/states.csv http://data.covid19india.org/csv/latest/cowin_vaccine_data_statewise.csv I've never done this before so I'm just confused how to start and do the project. When I asked some of friends I came to know it can be done by API integration with Python. Can anyone please help me how to start and do project in efficient way (if some links or resources provided would be great). I know my question is silly but I'm helpless how to do project. Please help me -
How to show if there are duplicates in enumerate
I have a list of stats that I keep for every team in the NFL. Every week I have a function that goes through the whole league and using enumerate, ranks teams in each stat category and then saves to a db. My question is... if multiple teams have the same value how do I give them the same rank? For example if the Patriots and Giants each average 30points a game and thats the best in the league, how do I make them both rank 1 and the next team start at 3? Below I have how I currently rank the teams now I appreciate any help or tips you can offer. for team in TeamName.objects.filter(league__name='NFL'): for count, value in enumerate(NFLTeamStats.objects.all().values( 'name', 'avg_points').order_by( '-avg_points'), start=1): if value['name'] == team.pk: avg_points_rank = count -
Models not getting registered to admin in Django?
I was just starting to make a quiz app in django when i encountered this problem. The problem is that that my models are not getting registered in the admin page. I have tried a lot of methods but nothing seemed to work. Can someone help me with this? models.py from django.db import models # Create your models here. class Quiz(models.Model): name = models.CharField(max_length=300) description = models.TextField() class Questions(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.TextField() op1 = models.CharField(max_length=200) op2 = models.CharField(max_length=200) op3 = models.CharField(max_length=200) op4 = models.CharField(max_length=200) admin.py from django.contrib import admin from .models import Quiz, Questions # Register your models here. admin.site.register(Quiz) admin.site.register(Questions) -
Csrftoken is not defined
I'm using the following code as recommended by the documentation: function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $("#formTabla").submit(function(event){ event.preventDefault(); var formData = new FormData(this); $.ajax({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } url : "{% url 'submit' %}", type: "POST", processData: false, contentType: false, data: { "checkboxes": formData, "datos": todosDatos }, success: function (respuesta){ } }); }); I'm getting the error "Uncaught ReferenceError: csrftoken is not defined". I understand why this happens, but I have no idea how to solve it. How and where am I supposed to define crsftoken? -
Added functionality in views.py does not work online but working in localhost. I want to add contact page
It resulted FileNotFoundError [Errno 2] No such file or directory. When I accessed the contact page in the browser like this https://sample.one/orders/contact/ (sample.one is not the true domain name) Below is my code, could someone tell me how to solve this or possible cause of the problem. Thanks a lot. Below is the code. #settings.py import os from pathlib import Path from decouple import config SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = ['sample.one', 'www.sample.one'] ROOT_URLCONF = f'{config("PROJECT_NAME")}.urls' WSGI_APPLICATION = f'{config("PROJECT_NAME")}.wsgi.application' ASGI_APPLICATION = f'{config("PROJECT_NAME")}.routing.application' PREPEND_WWW = True # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Application definition INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'category', 'accounts', 'orders', 'django.contrib.humanize', 'currencies', 'django_filters', 'storages', ] 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', ] 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', 'category.context_processors.menu_links', 'carts.context_processors.counter', 'currencies.context_processors.currencies', 'carts.context_processors.country_cur', ], }, }, ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } #tell that we are using custom user usermodels AUTH_USER_MODEL = 'accounts.Account' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { …