Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I automatically add a filter to a MongoEngine query in Django?
I'm using MongoEngine with Django and I want to add a default filter on all queries that retrieve data, as well as some further logging. MongoEngine has signals, but does not appear to have any signal for pre-query. Am I missing something or can anyone recommend an elegant solution? -
Can't get Django-Simple-Captcha to work, posts even when using wrong captcha
I think this is a simple issue to solve, but I've been trying for a couple of hours now and I think that my View file is messed up. The captcha shows up on my page, but when i create a post and fill out the completely wrong captcha it get sent and updated anyway. My views-file: def discussions(request): posts = Post.objects.filter(created__lte=timezone.now()).order_by('-created') if request.method == 'POST': captcha = CaptchaTestModelForm(request.POST) if captcha.is_valid(): human = True else: captcha = CaptchaTestModelForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.created = timezone.now() post.save() return redirect('discussions') else: form = PostForm() captcha = CaptchaTestModelForm() -
Dynamically Build Q Filter in Django, with AND and OR Operators?
I have a database table of articles which includes a field link, which is the link to the article. I'd like to filter for articles in a given date range, that come from domains in a given list. I've got a string array like this: domain_names = [ 'domain_name_1', 'domain_name_2', 'domain_name_3', 'domain_name_4', ] ...and I have a filter like this which works: data = (myArticles.objects .filter(Q(creation_datetime__range=[from_date, to_date]) & (Q(link__contains=domain_names[0]) | Q(link__contains=domain_names[1]) | Q(link__contains=domain_names[2]) | Q(link__contains=domain_names[3]))) ) I'd like to dynamically build the filter, so that if an object is added to or removed from the domain_names list, the filter will dynamically update. I've tried this: q_object = Q() for name in domain_names: q_object.add(Q(link__contains=name), Q.OR) q_object = q_object.add(Q(creation_datetime__range=[from_date, to_date]), Q.AND) ...but I'm getting back all the objects in the date range, and the filter that's supposed to be filtering on domain_names isn't doing anything yet. What's the correct way to dynamically build a Q filter in this case? -
Django migrate from sqlite3 to mysql
I am trying to migrate my Django app from SQLite3 to MySql. I took following steps Configured a new empty database on MySql. I did not create any tables because I assumed that the tables will be created by the migrate command. Created a new user who has access to this database CREATE USER 'djangouser'@'%' IDENTIFIED WITH mysql_native_password BY 'password';GRANT ALL ON djangoappdb.* TO 'djangouser'@'%'; Stopped the server Dumped all the data to a file using python3 manage.py dumpdata > currData Deleted all the existing migrations reran python3 manage.py makemigrations. This step created a single new migration file Changed the setting.py file to use MySql and djangoappdb with correct username and password. ran python3 manage.py migrate command. I get following error ... File "/usr/local/lib/python3.8/dist-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.8/dist-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1146, "Table 'djangoappdb.djangoapp_customuser' doesn't exist") customuser is one of the models in the app. Am I supposed to create the tables manually? -
Detect Every Third Loop in a HTML Forloop - HTML - Django
I have a website and on one page there is repeating information from a for loop that is made to print. The problem is that every item in the forloop is about 10 lines of text. When I go to print, the 10 lines of text will sometimes break between pages. I need them to stay together no matter what and I have tried "page-break-inside: avoid;" but I can't get it to work. It is somewhat irrelevant however because I need to make sure every page only has three blocks on it because 4 already overdose the margins. My plan is to loop through the blocks just fine and detect every third loop and add extra spacing below it to get it to go to the next page. Question: How do I detect every third loop in my html forloop? {% for post in filter.qs %} {% if forloop.first %} <div style="position:relative; top: -12px; left: -2px; margin-bottom: 180px;"> <div style="position:absolute;left:21.79px;top:435.49px" class="cls_0030"><span class="cls_0030">{%if post.department%} {{post.department}}{%endif%}</span></div> <div style="position:absolute;left:248.82px;top:435.54px" class="cls_014"><span class="cls_014">Inspection #</span></div> <div style="position:absolute;left:355.58px;top:435.52px" class="cls_013"><span class="cls_013">{{ post.count_building }}</span></div> <div style="position:absolute;left:21.70px;top:453.54px" class="cls_014"><span class="cls_014">Inspection Date</span></div> <div style="position:absolute;left:96.52px;top:453.52px" class="cls_013"><span class="cls_013">{%if post.date%}{{post.date}}{%endif%}</span></div> <div style="position:absolute;left:248.82px;top:453.54px" class="cls_014"><span class="cls_014">Inspection Time</span></div> <div style="position:absolute;left:338.10px;top:453.49px" class="cls_008"><span class="cls_008">{%if post.time%}{{post.time}}{%endif%}</span></div> <div style="position:absolute;left:21.70px;top:471.54px" class="cls_014"><span class="cls_014">Floor(s)</span></div> <div … -
how use more than one routings file in django-channels?
I am making a project in which i use channels in two different apps.but how can i make two different routings files for each app import os from channels.routing import ProtocolTypeRouter,URLRouter from django.core.asgi import get_asgi_application from channels.http import AsgiHandler from channels.auth import AuthMiddlewareStack from consultation import routings as consultation_routings from chat import routings as chat_routings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sqh.settings._base') application = ProtocolTypeRouter({ "http":AsgiHandler(), "websocket":AuthMiddlewareStack( URLRouter( consultation_routings.websocket_urlpatterns, chat_routings.websocket_urlpatterns, ) ) }) when i add a second routings file address to URLRouter in asgi.py it raises following error : URLRouter( TypeError: __init__() takes 2 positional arguments but 3 were given -
How do I download a Django webpage into a PDF with all the css when user clicks "PDF" button? (Exactly how it looks, into a PDF)
I have tried using multiple technologies like weasyprint and reportlab but have not been able to make the webpage that the user is seeing into a pdf. I have read the documentation but maybe I am missing steps but I eventually want to take the exact page they are looking at and when the press the "PDF" button, it downloads the entire web page into a PDF with all the css and everything. The webpage does contain heatmap charts made with plotly, at times the webpage can have 2 charts or sometimes up to 20 charts. I currently just call the 'window.print()' function but it cuts off the charts and I was hoping that if I utilize weasyprint or a similar technology then I can have the charts be displayed correctly. Thank you in advance. -
Is it possible to define only a reference to a text in django templates, and change it later?
First of all, I am sorry for my English! If I have a multi-language app, in one button for registration I would do something like this: <button>{% trans 'Register now!' %}</button> Then I have to generate the dictionary for translations and then, a translator of my team will assign the value for "Register now". Right? #: templates/file.html:30 msgid "Register now!" msgstr "Regístrate ahora!" But what happens if the texts are not yet defined, or are going to change? Is it possible with a Django plugin, to just define a reference to a given text of a component in my HTML and then someone from my team will fill in the text and generate the translations? Something like: <button>{% text 'button_text_for_registration' %}</button> // Maybe this will change Rosetta adds an interface for translations, but it is not possible to change the default dictionary text. Is there a plugin that does this? Or what would be the best way to manage this dynamic content? -
Django model method not making changes to object
I have a method on my model to change an object from being published to unpublished. The redirect works alright but in my database, nothing happens. If the object is published it remains so with no changes to it when the button is clicked to unpublish the object(blog post article) This is the model and the method class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) published = models.BooleanField(default=False, null=True, blank=True) def unpublish(self): self.published == False self.save() My view def unpublish_post(request, slug): post = get_object_or_404(Post, slug=slug) post.unpublish return redirect('dashboard') My urls.py path('unpublish-post/<slug>/', unpublish_post, name='unpublish-post'), -
django shell - some querysets are empty in the shell but they shouldn't be
I am using the django shell to look at some querysets. I am able to retrieve all of my Student objects with .all() but if I then try to retrieve one object with .get() or filter on a field, I'm getting empty returns. The project seems to run ok on the browser (I'm still in the progress of writing all my tests but functionally it is working). I am able to successfully use get() or filter on a field with my Objectivemodel. Here is what I get with all(): >>> from gradebook.models import Student, Objective >>> s = Student.objects.all() >>> for i in s: ... print(i.student_first) ... John Sally Keith Terrance Henry Analise Ron >>> Now if I try to use get(): >>> qs = Student.objects.get(student_first='Analise') Traceback (most recent call last): gradebook.models.Student.DoesNotExist: Student matching query does not exist. Or filter on a field: >>> s.filter(student_first='Ron') <QuerySet []> >>> Student model class Student(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) student_first = models.CharField(max_length=30) student_last = models.CharField(max_length=30) nickname = models.CharField(max_length=31) fullname = models.CharField(max_length=60) attend = models.BooleanField(default=True) student_number = models.IntegerField() email = models.EmailField(max_length=50) def __str__(self): return self.fullname -
Why does my django app fail to deploy to heroku ("building wheel for psycopg2")?
While trying to deploy a django app to heroku I am running into an issue that I can not seem to fix, and I am getting increasingly desperate. When I enter the command git push heroku master it runs into the following error remote: Collecting sqlparse>=0.2.2 remote: Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) remote: Building wheels for collected packages: Pillow, psycopg2 remote: Building wheel for Pillow (setup.py): started remote: Building wheel for Pillow (setup.py): finished with status 'done' remote: Created wheel for Pillow: filename=Pillow-5.2.0-cp39-cp39-linux_x86_64.whl size=1316371 sha256=cb80053184568f78e761e74c93e38682de7c3000417f9d12e7b37971f12dfcd0 remote: Stored in directory: /tmp/pip-ephem-wheel-cache-4bhzio_g/wheels/2e/0c/21/df64563df0fe8750c4bff3e38b90f223df6c02aa5c5b570905 remote: Building wheel for psycopg2 (setup.py): started remote: Building wheel for psycopg2 (setup.py): finished with status 'error' remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-tajnjqcx/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-tajnjqcx/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-9ekv4vgu remote: cwd: /tmp/pip-install-tajnjqcx/psycopg2/ As far as I understand it, it tries to install the dependencies in my requirements.txt file. I tried to change psycopg2 to psycopg2-binary change the version number of psycopg2 remove it entirely all to no avail: It still tried to "build wheel" for it. I really have no idea what the error means and I am at a complete loss here. … -
Integrating Sagepay (Opayo) with Django - How to create a merchant session key
Longtime stackoverflow user first time asking a question. I am trying to integrate Opayo (SagePay) with Django and I am having problems generation the merchant session key (MSK). From sagepays docs they say to use the below curl request and that I should receive the key in the response curl https://pi-test.sagepay.com/api/v1/merchant-session-keys \ -H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=" \ -H "Content-type: application/json" \ -X POST \ -d '{ "vendorName": "sandbox" }' I have tried to implement this in my Django view with the following code but I receive a 422 response (Unprocessable Entity response). import requests def BasketView(request): headers = { "Authorization": "Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=", "Content-type": "application/json", } data = {"vendorName": "sandbox"} r = requests.post("https://pi-test.sagepay.com/api/v1/merchant-session-keys", headers=headers, params=data) print(r) Any ideas where I may be going wrong with this? Thanks -
LIke functoin view keep throwing DoesNotExist at /group/3/ after a second user in the group post when liked by another user
I am currently challenge with a like functionality on a group page for that I'm creating, the problem is that when a first user of the group post on the group page other users can comment and like at his post, but as soon as a second user of the same group post, then when the post get liked or commented on, it throws thess error DoesNotExist at /group/3/. i wonder why am getting this error, because when the first user posted it didn't throw that error, when his post got liked or commented on, but the error only shows up when a another user on the same group post and it got like or commented on. I would appreciate some help. Here is my like function view. def like(request, pk): user = request.user post = Post.objects.get(pk=pk) group = GroupEx.objects.get(group=pk) liked= False like = Like.objects.filter(username=user, post=post,group=group) if like: like.delete() else: liked = True Like.objects.create(username=user, post=post, group=group) resp = { 'liked':liked } response = json.dumps(resp) return redirect('group:main', pk=pk) return HttpResponse(response,content_type = "application/json") Here is my comment view. def comment(request, pk): context = {} user = request.user post = get_object_or_404(Post, pk=pk) group = get_object_or_404(GroupEx,pk=pk) if request.method == 'POST': form = NewCommentForm(request.POST) if … -
id null on django API with mongo and djongo
I need help. My API get me "id": null instead of the uuid given in mongoDB. Here's the results : Result in RestER Result in NoSqlManager And Here's my code : serializers.py from testapp.models import Test class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields=fields='__all__' models.py class Test(models.Model): testChar = models.CharField(max_length=255) testTwo = models.CharField(max_length=255) views.py from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse # Create your views here. from testapp.models import Test from testapp.serializers import TestSerializer @csrf_exempt def testApi(request,id=0): if request.method == 'GET': test = Test.objects.all() test_serializer = TestSerializer(test,many=True) return JsonResponse(test_serializer.data,safe=False) elif request.method == 'POST': test_data = JSONParser().parse(request) test_serializer = TestSerializer(data=test_data) if test_serializer.is_valid(): test_serializer.save() return JsonResponse("Added successfully", safe=False) return JsonResponse("Failed to Add",safe=False) elif request.method == 'PUT': test_data=JSONParser().parse(request) test=Test.objects.get(TestId=test_data['TestId']) test_serializer = TestSerializer(test,data=test_data) if test_serializer.is_valid(): test_serializer.save() return JsonResponse("Update successfully", safe=False) return JsonResponse("Failed to Update") elif request.method == 'DELETE': test=Test.objects.get(TestId=id) test.delete() return JsonResponse("Deleted successfully", safe=False) -
Django: how to solve several Foreign key relationship problem?
I'm currently learning Django and making electronic grade book. I am completely stuck after trying everything, but still cannot solve the problem. I will explain in detail and post all the relevant code below. I need to have two url pages "class_students" and "teacher_current". The first page is for the teacher to see the list of students of a certain class. The table on this page has "action" column. In every cell of this column there is View button, so that the teacher could be redirected to "teacher_current" page and see the list of current tasks, given to a certain student. On this page there is a "Mark" column, its cells may contain EITHER mark given to this student with link to another page to update or delete this mark OR "Add mark" link to add mark on another page. Here comes the problem: everything works correctly, except the thing that each mark is related to a Task class via Foreign key and NOT to a Student class. So every student of the same class has the same marks for the same tasks. But it certainly won't do. Here is all my relevant code: 1) views.py models.py urls.py: https://www.codepile.net/pile/qkLKxx6g 2) … -
Page not found (404) No post found matching the query
I am working with Django and I am just a beginner. I am following this tutorial to create a contact form. But I have this error when I want to go to this URL: http://127.0.0.1:8000/contact/. I have 3 apps in my project(Posts, Users and Contact): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Posts', 'Users', 'crispy_forms', 'Contact', And here is the urls.py in my project : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('' , include('Posts.urls')), path('',include('Contact.urls')), ] And it is urls.py in my Contact app: from django.urls import path from Contact import views app_name = "Contact" urlpatterns = [ path('contact/', views.context, name="contact"), ] And this is views.py in my Contact app: from django.shortcuts import render, redirect from .forms import ContactForm from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse def context(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Website Inquiry" body = { 'first_name' : form.cleaned_data['first_name'], 'last_name' : form.cleaned_data['last_name'], 'email' : form.cleaned_data['email_address'], 'message' : form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message,'admin@example.com', ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect("Posts:home") form = ContactForm() return render(request, "Posts/templates/contact/contact.html", {'form':form}) I have a templates folder in Posts app and … -
Django: CSRF cookie sometime missing while submitting form
After submit the form, I got csrf forbidden error. So, If I clear browser cookie, the problem is resolved. Suggest me what should I do? -
Heroku Django crashed: at=error code=H10 desc=“App crashed” method=GET path=“/”
I am trying to deploy my Django project on Heroku.But everytime, I have got same error. Heroku restart doesnot work for me. I cleared buildpack and added python buildpack. This has not work for me. I also tried different host like ALLOWED_HOSTS = ['*', '127.0.0.1', 'dailynotes.herokuapp.com']. In Procfile I tried different way like web: gunicorn ToDoApps.wsgi: --log-file - and web: gunicorn ToDoApps.wsgi:application --log-file - --log-level debug python manage.py collectstatic --noinput manage.py migrate This does not work for me. crashed file 2021-08-18T09:37:39.832259+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dailynotes.herokuapp.com request_id=81cc172e-247e-4aa9-8b39-fb9440cd67d2 fwd="103.14.72.227" dyno= connect= service= status=503 bytes= protocol=https 2021-08-18T09:37:40.734680+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=dailynotes.herokuapp.com request_id=8d2598b4-0521-4519-892a-467d2a2642ca fwd="103.14.72.227" dyno= connect= service= status=503 bytes= protocol=https logs --tail 2021-08-18T09:21:46.641887+00:00 app[web.1]: preload_app: False 2021-08-18T09:21:46.641888+00:00 app[web.1]: sendfile: None 2021-08-18T09:21:46.641888+00:00 app[web.1]: reuse_port: False 2021-08-18T09:21:46.641888+00:00 app[web.1]: chdir: /app 2021-08-18T09:21:46.641889+00:00 app[web.1]: daemon: False 2021-08-18T09:21:46.641889+00:00 app[web.1]: raw_env: [] 2021-08-18T09:21:46.641889+00:00 app[web.1]: pidfile: None 2021-08-18T09:21:46.641889+00:00 app[web.1]: worker_tmp_dir: None 2021-08-18T09:21:46.641890+00:00 app[web.1]: user: 9071 2021-08-18T09:21:46.641890+00:00 app[web.1]: group: 9071 2021-08-18T09:21:46.641890+00:00 app[web.1]: umask: 0 2021-08-18T09:21:46.641891+00:00 app[web.1]: initgroups: False 2021-08-18T09:21:46.641891+00:00 app[web.1]: tmp_upload_dir: None 2021-08-18T09:21:46.641909+00:00 app[web.1]: secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} 2021-08-18T09:21:46.641909+00:00 app[web.1]: forwarded_allow_ips: ['*'] 2021-08-18T09:21:46.641909+00:00 app[web.1]: accesslog: - 2021-08-18T09:21:46.641910+00:00 app[web.1]: disable_redirect_access_to_syslog: False 2021-08-18T09:21:46.641916+00:00 app[web.1]: access_log_format: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" … -
Django S3 : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I'm trying to use s3 to fetch images on my website. I'm trying to use get_object() to access to the image object. The part of the object that I want to return is the Body, which type is StreamingBody. I want to convert the StreamingBody into string to return it. Here is my code : def get_image_link(image): """Get image link""" key = "media/" + str(image) s3 = boto3.client('s3', config=Config(signature_version='s3v4', region_name=settings.AWS_S3_REGION_NAME)) obj = s3.get_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=key) return obj['Body'].read().decode('utf-8') obj['Body'].read() return bytes that I'm tring to decode in utf-8. When I run obj['Body'].read().decode('utf-8'), I get this error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Thank you by advance for your help -
Is there a way of having variable methods/functions in django?
I would like to be able to create functions to use them as "rules" or conditions. let's say i have a bunch of employees, but to calculate commissions to each one i would like to call a function that calculates the output. there are cases where i would reuse the function between employees but cases too where i would only have a function for a single employee. said function can change in time and must apply for all employees with that function. Example: if employee have more than 3 sales, give him/her 15% of beneficts from all sales: i would create a function like this: output = 0 orders = Order.objects.filter(employee = kwargs.get('employee_id')) if len(orders) < 3: return output for order in orders: output += (order.benefits * 0.15) return output Notes: Should be able to receive parameter in KWARGS as variables and others -
importing module into django/python and calling a function which also imports another module, Error
I have django application that i am trying to import a whole module into, i want to import this module which also calls other module but i get this error when i call a function that belongs to the imported module ModuleNotFoundError: No module named 'models' on the first line of the function is from models.regressor import SingleInputRegressor but if include the module or file name as from module_name.models.regressor import SingleInputRegressor the error goes away but there is such lines in the module that i cant do them manually its a machine learning module that am trying to import the whole module into django and just call a function from the model module that begging's the whole process. -
React seems to be requiring that Django Model field associated with the variable in React be declared to POST
I'm fairly new to programming so I am most likely missing something fairly basic but, I have lost a couple day on this issue and can't seem to find a solution. I am following a tutorial from the Great Adib (Source Code: https://github.com/GaziAdib/django_react_fullstack) and I am trying to hook up my React form with my Django backend. I am using axios to handle the API communication and have tested my API using Postman and the Django API UI and it seems to be working just fine, I can even GET data from my Django backend without issues but when I try to POST the data from my form I am running into issues, I keep getting RefrenceErrors on my Django fields that are associated with the according variables in my React code, that it is not defined, here is how I have my code set-up and the error that I am getting: import React, { useState } from 'react'; import { useHistory } from 'react-router'; import axios from 'axios'; [enter image description here][1]const Form = () => { let history = useHistory(); const [firstName, setFirstName] = useState("") const [lastInitial, setLastInitial] = useState("") const [dateVisited, setDateVisited] = useState("") const [foodRating, setFoodRating] … -
React Axios unable to POST to Django Rest Framework
I am trying to post data from react js to django rest api, but getting Method Not Allowed (POST) Settings.py CSRF_COOKIE_NAME = "XCSRF-TOKEN" CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = list(default_headers) + [ 'XCSRF-TOKEN', ] CSRF_TRUSTED_ORIGINS = [ "localhost:3000", "127.0.0.1:3000", ] Request with axios let token = localStorage.getItem("token"); let csrfCookie = Cookies.get('XCSRF-TOKEN'); let res = await axios.post(url + "/add/card/", /* url is working with postman and django */ data, /* data is a JavaScript Object */ { withCredentials: true, headers: { 'X-CSRFTOKEN': csrfCookie, 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Token ' + token } } ); So, I am sending this request headers Accept: application/json, text/plain Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Authorization: Token <token> Connection: keep-alive Content-Length: 186 Content-Type: application/x-www-form-urlencoded Cookie: XCSRF-TOKEN=<token>; sessionid=<token> Host: 127.0.0.1:8000 Origin: http://127.0.0.1:3000 Referer: http://127.0.0.1:3000/ sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="92", "Opera GX";v="78" sec-ch-ua-mobile: ?0 Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 OPR/78.0.4093.153 X-CSRFTOKEN: <token> But getting this response headeres Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://127.0.0.1:3000 Allow: GET, HEAD, OPTIONS Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Wed, 18 Aug 2021 16:42:26 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.8.3 Vary: Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY This unabled post only happens … -
Delete post in django
I know similar kind of question is asked before, but I was not able to get it. This is my first project as a Django beginner. In my Django blog app, I made a delete button but it is not working and I am finding for answers, trying different methods on the web but it did not help. I am trying to do is when admin open the post, then on clicking the delete button, it take the post-id and delete that post and redirect to home page, but it is not working as expected. So, lastly I came here. Any help will be appreciated. Thanks! This is my urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('post/<int:pk>', views.post, name='post'), path('about', views.about, name='about'), path('contact_us', views.contact_us, name='contact_us'), path('register', views.register, name='register'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('create_post', views.create_post, name='create_post'), path('delete_post', views.delete_post, name='delete_post') ] This is my views.py file: def delete_post(request, *args, **kwargs): pk = kwargs.get('pk') post = get_object_or_404(Post, pk=pk) if request.method == 'POST': post.delete() return redirect('/') return render(request, 'delete-post.html') This is delete post html form: <form action="{% url 'delete_post' post.id %}" method="post"> {% csrf_token %} <input type="submit" value="Delete post"> </form> Delete button: <a … -
/bin/sh: 1: apk: not found, while build image docker
I'm trying to create and run a djanog image with the docker to deploy it along with kubernetes, but when I run the image build command, it gives the error "/bin/sh: 1: apk: not found " Dockerfile: FROM python:3.8-slim LABEL maintainer="r.ofc@hotmail.com" ENV PROJECT_ROOT /app WORKDIR $PROJECT_ROOT RUN apk update \ && apk add mariadb-dev \ gcc\ python3-dev \ pango-dev \ cairo-dev \ libtool \ linux-headers \ musl-dev \ libffi-dev \ openssl-dev \ jpeg-dev \ zlib-dev RUN pip install --upgrade pip COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . CMD python manage.py runserver 0.0.0.0:8000 can someone help me?