Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PasswordResetView takes 1 positional argument but 2 were given
def password_recover(request): print("password_recover") return password_reset(request, subject_template_name='registration/password_reset_subject.txt') So I had that piece of code, that was working on django 1.8.While migrating to django 2.2, i changed that piece of code too the one below def password_recover(request): print("password_recover") return PasswordResetView(request, subject_template_name='registration/password_reset_subject.txt') I am getting error takes 1 positional argument but 2 were given -
django rest framework add write only field for unit conversion
I am trying to write an API allowing users to read a length in km but write it in miles. The model stores the information in kilometers. The idea is to achieve something like this: class AreaSizeSerializer(serializers.ModelSerializer): class Meta: model = AreaSize fields = ['width', 'height'] # This function should perform the unit conversion def write_width(self, miles): self.width = miles * 1.609344 ... So when the user performs a POST request containing the size in miles it gets converted to kilometers and stored in the database. Could somebody please explain how to do this? -
TypeError: Field 'id' expected a number but got DeferredAttribute object at 0x000002B6ADE878D0
I am using a queryset in Django- whenever I run the server, it gives an error. TypeError: Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x000002B6ADE878D0 It is something about the queryset of my form that causes the error. I don't know whether its an issue with my models.py or my forms.py I tried looking up this DeferredAttribute object on Google, but I didn't really see any answer that works for me. forms.py: from .models import Task, Categories from django import forms from django.forms import ModelForm from django.db.models import Q class TaskForm(ModelForm): task_title = forms.CharField(max_length=100) task_description = forms.CharField(widget=forms.Textarea) due_date = forms.DateTimeField() is_completed = forms.BooleanField() #categories = forms.ModelChoiceField(empty_label="---None---") class Meta: model = Task fields = ['task_title', 'task_description', 'due_date', 'is_completed', 'categories', 'parent'] def __init__(self, user, *args, **kwargs): # Get all the categories from the database for that specific user super(TaskForm, self).__init__(*args, **kwargs) # It is something about this line that causes the error self.fields['categories'].queryset = Categories.objects.filter(Q(user_id__isnull=True) | Q(user_id=user.id)) models.py: from django.db import models from django.db.models import Q from users.models import CustomUser from django.urls import reverse from django.contrib.auth import get_user_model class Categories(models.Model): category_type = models.CharField(max_length=50) user = models.ForeignKey(CustomUser, null = True, on_delete=models.CASCADE) def __str__(self): return '%s ' % (self.category_type) def get_absolute_url(self): … -
I have problems with statistical files in django. CSS background
Good morning, I can't upload a background image that is in one of my css files. See that in the image below my css is set correctly in my HTML file. enter image description here The css file is in the 'static' folder inside the SASS folder as the image below enter image description here The next image shows the css file where my background is. enter image description here Finally, this is the css file where my background image is, enter image description here To understand better. This CSS file folder is not being called directly from my HTML. All CSS files from the SASS folder are being called by the STYLE.CSS file from the CSS folder. This theme he came from the themeforest, so I have such a hard time rendering this file. I'm sorry English, I hope you can understand. -
Django comment's reply system
i have comment section in django blog's like this screenshot one, but how do i reply to each desire comment. i have comment section in django blog's like this screenshot one, but how do i reply to each desire comment. appreciate to your help...:) thank you so much views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" context_object_name = 'post' form = CommentForm() def get_object(self): obj = super().get_object() if self.request.user.is_authenticated: PostView.objects.get_or_create( user=self.request.user, post=obj) return obj def get_context_data(self, **kwargs): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] context = super().get_context_data(**kwargs) context['most_recent'] = most_recent context['page_request_var'] = "page" context['category_count'] = category_count context['form'] = self.form return context def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): post = self.get_object() form.instance.user = request.user form.instance.post = post form.save() return redirect(reverse("post-detail", kwargs={ 'pk': post.pk })) models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() post = models.ForeignKey('Post',related_name='comments', default=False, on_delete=models.CASCADE) def __str__(self): return self.user.username @property def get_comments(self): return self.comments.all().order_by('-timestamp') -
Django: How to create an admin 'list of Calculations' in admin, for example BMI, Body Surface, Age
I want to design the possibility to make a large number of calculations in a Django Project. The data are provided by patients, such as weight, length, Date of birth. I would like to create in Django admin a list with calculations for each parameter. That way I can easily adjust and expand with Body Surface Area, Ideal Bodyweight, and make calculations for kids, women, and men, for kg/com and pd/inch, etc. Could anybody give me an example of how to do this? I would like python used for the calculations in the admin listed calculations. Thanks, Hans -
How to change bool value of is_actual (DRF)
I have two fields in Post model - def next_month(): now = timezone.now() return now + relativedelta(months=+1) created = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(default=next_month, blank=True, editable=False) So, I want to add field is_actual = models.BooleanField(). If end_time > now(), value equal True. I understand, that I'm need to use some function, when function runs at 00:00 every day, for checking date and change is_actual value. But I don't know how to do that. Can you help me, please? -
scp command gives 'posix_spawn: No such file or directory' error in windows
Im trying to scp my django app (its in the desktop) to my server using linode. I'm using Windows 10 version 1903. BTW, im using OpenSSH. When i type this command: scp -r excelsite ****@**.**.**.***:~/ It gave out this error... CreateProcessW failed error:2 posix_spawn: No such file or directory Any help if very much appreciated! -
Django CMS icon in menu
I am trying to show my uploaded icon on navigation but i guess, i am going through a wrong way. this is my model that extended class IconExtension(PageExtension): image = models.ImageField(upload_to='icons') extension_pool.register(IconExtension) and this is my cms_toolbars.py file @toolbar_pool.register class IconExtensionToolbar(ExtensionToolbar): # defines the model for the current toolbar model = IconExtension def populate(self): # setup the extension toolbar with permissions and sanity checks current_page_menu = self._setup_extension_toolbar() # if it's all ok if current_page_menu: # retrieves the instance of the current extension (if any) and the toolbar item URL page_extension, url = self.get_page_extension_admin() if url: # adds a toolbar item in position 0 (at the top of the menu) current_page_menu.add_modal_item(_('Page Icon'), url=url, disabled=not self.toolbar.edit_mode_active, position=0) and this is my menu.html file {% load menu_tags %} {% for child in children %} <li class="child{% if child.selected %} selected{% endif %}{% if child.ancestor %} ancestor{% endif %}{% if child.sibling %} sibling{% endif %}{% if child.descendant %} descendant{% endif %}"> <a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}">{{ child.get_menu_title }} <img src="{{ child.image.url }}"> </a> {% if child.children %} <ul> {% show_menu from_level to_level extra_inactive extra_active template "" "" child %} </ul> {% endif %} </li> {% endfor %} I am not getting why it is not … -
Django - Showing A Form & It's Existing Model Data On The Same Page
Hi all, I was wondering if it would be possible to show the data in my already existing model at the same time as using a form on the same template. (I'm trying to make a chat / blog system.) My problem is that I need to reference a local variable before the user posts a new message using the form and Django is giving me the "local variable 'rsgroupchat' referenced before assignment" error. Any help would be highly appreciated as otherwise I will have to make a separate view and template to do this (of which is not exactly suitable). Below is the view I am working with: @login_required def groupView(request): serverdata = server.objects.all() chatmessage = rsgroupchat.objects.all().order_by('-dateandtime') if request.method == 'POST': form = newchatmessage(request.POST) if form.is_valid(): forserver = form.cleaned_data.get('forserver') content = form.cleaned_data.get('content') rsgroupchat = form.save(commit=False) rsgroupchat.user = request.user rsgroupchat.save() return redirect('../rsgroups') else: form = newchatmessage() return render(request,'rs-groups-dash.html', {'form':form, 'serverdata':serverdata, 'chatmessage':chatmessage}) And here is my form / chat message: class newchatmessage(forms.ModelForm): class Meta: model = rsgroupchat exclude = ['user'] fields = ('forserver', 'content', 'user',) -
Not saving output from edit profile
I would like users to be able to click on edit profile, redirected to a form allowing them to edit certain details in their profile and then saving said details when they click submit. The problem I am having now is that when users submit their form, none of the information seems to be saved Here is the code i have on forms.py class TeacherSignUpForm(UserCreationForm): email = forms.EmailField(max_length=100) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) linkedin = forms.URLField(max_length=200) class Meta(UserCreationForm.Meta): model = User fields = ('email', 'username', 'first_name', 'last_name') def save(self, commit=True): self.instance.is_teacher = True user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() mentor = Mentor.objects.create( user=user, linkedin=self.cleaned_data['linkedin'] ) return user # edit mentor profile class MentorProfileForm(forms.Form): first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) email = forms.EmailField(max_length=150) Views(teachers.py): class TeacherSignUpView(CreateView): model = User form_class = TeacherSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'teacher' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() # user.set_password(form.cl) login(self.request, user) return redirect('teachers:app-instructor-dashboard') #edit mentor profile def edit_user(request): user = request.user form = MentorProfileForm(initial={'first_name':user.first_name,'last_name':user.last_name,'email':user.email}) if request.method == 'POST': if form.is_valid(): user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.email = request.POST['email'] user.save() return HttpResponseRedirect('%s'%(reverse('profile'))) else: form = MentorProfileForm() return render(request, 'classroom/teachers/app-instructor-profile.html', {'form':form}) … -
django pagination after search form "POST" from database , not work correctly
i have problem with pagination after form search "POST" , when i click to next page , no result appears , because the function in view.py include "if request.method == 'POST':" , and here is my codes: models.py file: from django.db import models class acc_start(models.Model): username = models.CharField(max_length=50, blank=True, null=True) ip = models.CharField(max_length=50, blank=True, null=True) Acct_type = models.CharField(max_length=50, blank=True, null=True) Session_Id = models.CharField(max_length=50, blank=True, null=True) Timestamp = models.DateTimeField() Tunnel_Client = models.CharField(max_length=50, blank=True, null=True) NAT_IP_Address = models.CharField(max_length=50, blank=True, null=True) Start_Port = models.CharField(max_length=50, blank=True, null=True) End_Port = models.CharField(max_length=50, blank=True, null=True) post_date = models.DateTimeField() procedure_check_start = models.IntegerField() class Meta: db_table = "acc_start" ========================== forms.py file : from django import forms from .models import acc_start class AccStartSearchCform(forms.ModelForm): class Meta: model = acc_start fields = ['username', 'ip', 'Session_Id', 'NAT_IP_Address', 'Start_Port', 'End_Port'] ============================== views.py file : from django.shortcuts import render, render_to_response from .models import acc_start from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from .forms import AccStartSearchCform def f_requist_accounting_start(request): form = AccStartSearchCform(request.POST or None) context = { "form": form, 'nbar': 'accounting_start' } if request.method == 'POST': queryset = acc_start.objects.all().filter( username__icontains=form['username'].value(), ip__icontains=form['ip'].value(), Session_Id__icontains=form['Session_Id'].value(), NAT_IP_Address__icontains=form['NAT_IP_Address'].value(), Start_Port__icontains=form['Start_Port'].value(), End_Port__icontains=form['End_Port'].value() ) page = request.GET.get('page', 1) paginator = Paginator(queryset, 14) try: queryset = paginator.page(page) except PageNotAnInteger: queryset = paginator.page(1) except EmptyPage: queryset = paginator.page(paginator.num_pages) … -
How do I create different outputs from the same model form in django template?
I have the following model form: Model: class Inspection(models.Model): InspectionID = models.AutoField(primary_key=True, unique=True) GroupID = models.ForeignKey('PartGroup', on_delete=models.CASCADE, null=True) class InspectionReport(models.Model): ReportID = models.AutoField(primary_key=True, unique=True) InspectionID = models.ForeignKey('Inspection', on_delete=models.CASCADE, null=True) Date = models.DateField(auto_now=False, auto_now_add=False, null=True) Comment = models.CharField(max_length=255, blank=True) Signature = models.CharField(max_length=255, blank=True) Form: class InspectionReportForm(forms.ModelForm): class Meta: model = InspectionReport fields = ('Date', 'Comment', 'Signature') labels = {"Date": "Date (YYYY-MM-DD)"} I want to implement this in a template with a Pass, Fail, and Check button. Pass and Fail would have an autocompleted Comment saying pass or fail. And Check would prompt the user for a comment and have a further submit button. I know how to have a form with a basic submit button that posts the form data but I want to be able to have different buttons for the same form with different results. Here's what I have so far... a basic form with one submit button: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Create</button> -
Adding Custom Action to Django Rest Framework user/me endpoint
this is my first time asking something here. Please, bare in mind that in case I'm missing something. If so, I will do my best to provide the answer to whatever is needed. Alright, so, I'm starting with Django Rest Framework and I've been following a course but there is something that is not entirely clear for me. I'm trying to add a custom function to a /user/me endpoint. In this function, I'd like to provide the user id [self.user.id] and trigger a function to, i.e., deploy AWS infra. The issue is not with the code for AWS infra, but with triggering this by accessing a custom url. The contents for my views.py is: class ManageUserView(generics.RetrieveUpdateAPIView): """Manage the authenticated user""" serializer_class = UserSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get_object(self): """Retrieve and return authentication user""" return self.request.user From my urls.py is: from django.urls import path from user import views app_name = 'user' urlpatterns = [ path('', views.CreateUserView.as_view(), name='create'), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views.ManageUserView.as_view(), name='me') ] I've tried adding the following line into my views.py file: @action(methods=['POST'], detail=True, url_path='create-aws-infra') But when I try to go to /user/me/create-aws-infra, I cannot access it. I'm not sure if I have to import the … -
Django 2.2 : Is there any way to remove app name from admin urls?
I am using Django Built-in Admin panel, is there any way to remove app name from urls? If I want to access User listing, it redirects me to 27.0.0.1:8000/admin/auth/user/ can I make it 27.0.0.1:8000/admin/user/ without the app name auth? Thanks, -
Not able to update models ManyToMany relationship django. getting an error saying the models field has not been defined
i'm just confused or tired on this one. when this code runs it doesn't always remove or add, and when it does it will not update the like count. As i see the code, when the user is found in the liked value it should remove the user and decrease the likes and visa versa, it does not seem to do that. I also only seem to be able to have 1 like across all pictures, so i would have to remove one like and add to another, again this seems to all happen randomly. def liked_pic(request): pdb.set_trace() if request.method == 'POST': pic = Pictures.objects.get(id=request.POST.get('pic_id')) user = UserModel.objects.get(email=request.user) liked = Pictures.objects.filter(likes=user).exists() print(pic.likes, liked) if liked: pdb.set_trace() pic.likes.remove(user) pdb.set_trace() pic.save() if not liked: pdb.set_trace() pic.likes.add(user) pic.save() picturecount = Pictures.objects.filter(likes).count() data = {'json_pic_id': pic.id,'likes': picturecount, 'user':liked} return JsonResponse(data) return HttpResponseRedirect('home') pdb trace----------------- System check identified no issues (0 silenced). January 06, 2020 - 09:50:49 Django version 3.0, using settings Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. **accounts.UserModel.None False** (Removed computer path information) **-> pic.likes.add(user)** (Pdb) continue [06/Jan/2020 09:51:05] "POST /liked/ HTTP/1.1" 200 44 [06/Jan/2020 09:51:23] "GET /home/ HTTP/1.1" 200 3141 [06/Jan/2020 09:51:23] "GET /media/static/dataset/00000016.png HTTP/1.1" 200 184935 **accounts.UserModel.None True** … -
Insert pandas data frame into Postgres
I have a pandas data frame which I want to insert it into my Postgres database in my Django project. The data frame has 5 columns and the Database table has 6 columns and moreover, the data frame columns and DB columns order are not the same. So, before merging both, do I have to make sure that the order of the columns is the same in both the data frame and DB table? and how pls suggest how do I handle the missing column -
Determine if redirect will produce a 404 status code in view prior to redirecting
I have a system in which the majority of functionality is dependent upon a session cookie being set by the user. Naturally with this, I allow easy changing of this session (a Property) so the user can view new information seamlessly as they are going throughout the application. For example, a user is viewing Units in the system, when they select a new Property the Units for the newly selected Property are shown. Simple enough. However, there is an instance where a user is viewing a Unit and they change a Property. Obviously the Unit they are viewing is no longer found so the page 404's. What I want is to know that the redirect will 404 so I can redirect them to the homepage instead. How can I do this? Every way I can think to check (i.e. resolve or HttpRespsonse) does not show an error. from urllib.parse import urlparse import requests from django.contrib import messages from django.http import HttpResponse from django.shortcuts import redirect, get_object_or_404 from django.urls import reverse, resolve, Resolver404 from apps.properties.models import Property def set_property_session(request, property_id): redirect_url = request.META.get('HTTP_REFERER') # to check if it resolves, we must gather the path from the url path_to_check = urlparse(redirect_url).path try: … -
Getting a 'settings.DATABASES is improperly configured. Please supply the NAME value' error
I am using Django to connect to an on-premise database. Earlier, the database was hosted on Azure. The connection string I used within Django settings earlier was as follows- for sql database of Azure DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DatabaseName', #notrealname 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'sql-django-uat.database.windows.net', #notreal 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'MARS_Connection': 'True', } After the database migration, this string doesnt work. I keep getting 'Login timeout expired'. But substituting 'NAME' with "DATABASE' works. Example given below- DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'DATABASE': 'DatabaseName', #notrealname 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'sql-django-uat.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'MARS_Connection': 'True', } My webapp gets to the login page. But after I log in, I get the error- 'ImproperlyConfigured at /login/ settings.DATABASES is improperly configured. Please supply the NAME value.' Can someone tell me how to solve this? Thanks so much in advance. -
How to add information to a checkbox in django-admin
In my Django admin (change_form) I have several checkboxes. I want to let the users know what is going to be happened when they select a checkbox. See picture below. I have searched alot but couldn’t find anything? I don't know where to search!! Form! -
Django template with get_absolute_url() using args isn't working
Having trouble using get_absolute_url() with args to work in my template (perhaps I'm doing this incorrectly on the template side) I keep getting an error that says person_id is not defined I've got a simple model that looks like this: class Course(models.Model): year = models.ForeignKey(Year, on_delete=models.PROTECT) name = models.CharField(max_length=50) short_name = models.CharField(max_length=50) created = models.DateTimeField(auto_now=False, auto_now_add=True) last_updated = models.DateTimeField(auto_now=True, auto_now_add=False) It has get_absolute_url that looks like this: def get_absolute_url(self): """Return absolute url for Course.""" return reverse( "view_course", args=[ person_id, location_id, str(self.id) ] ) and I've got my URL which looks like this: path( "<person_id>/locations/<location_id>/course/<pk>/", views.CourseDetailView.as_view(), name="view_course", ), In my template I've tried a few different ways to get this to display, currently it looks like this: {% for section in sections %} <a id="course{{section.course.id}}" href="{{person.id}}/locations/{{location.id}}/course/{{ section.course.get_absolute_url }}" class="card-link location-course-link">{{ location.person }}</a>{{section.course.short_name}} {% endfor %} I have also tried: href="{{ section.course.get_absolute_url }}" Also tried: href="{{ section.course.get_absolute_url person.id location.id }}" While all the data is correct (the url comes out to 1/locations/3/course/5/ as expected in the template - it still gives that error when clicked on. -
django crispy forms render(0 got an unexpected keyword argument argument 'renderer'
Error during template rendering In template /home/bsd/.local/lib/python3.6/site-packages/crispy_forms/templates/bootstrap4/field.html, error at line 42 render() got an unexpected keyword argument 'renderer' 32 {% crispy_field field 'class' 'form-check-input' %} 33 {% endif %} 34 <label for="{{ field.id_for_label }}" class="{%if use_custom_control%}custom-control-label{% else %}form-check-label{% endif %}{% if field.field.required %} requiredField{% endif %}"> 35 {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} 36 </label> 37 {% include 'bootstrap4/layout/help_text_and_errors.html' %} 38 {% elif field|is_file and not field|is_clearable_file and use_custom_control %} 39 {% include 'bootstrap4/layout/field_file.html' %} 40 {% else %} 41 <div class="{{ field_class }}"> 42 {% crispy_field field %} 43 {% include 'bootstrap4/layout/help_text_and_errors.html' %} 44 </div> 45 {% endif %} 46 {% endif %} 47 </{% if tag %}{{ tag }}{% else %}div{% endif %}> 48 {% if field|is_checkbox %} 49 {% if label_class %} 50 </div> 51 {% endif %} 52 </div> I have this two lines in my login.html tempalte {% load crispy_forms_tags %} {% crispy captchaform %} Its crashing when I add the second line, no idea why.It was working on django 1.8, but now moving to django 2.2 its giving me this error. -
Django Reportlab 'list' object has no attribute 'getKeepWithNext'
I am using Django and Reportlab to generate our schools Substition plan from a Database as a table on a pdf. every class should have it's own table. I already created a view and setup django and Reportlab this is my code so far: views.py def some_view(request): elems = [] buffer = io.BytesIO() pdf = SimpleDocTemplate( buffer, pagesize=landscape(A4), ) substitution = Substitution.objects.all().values('klasse').distinct() i = 0 while len(substitution) > i: x = Substitution.objects.filter(klasse=substitution[i]['klasse']) i = i + 1 static_data = [['Datum', 'Tag', 'Pos', 'Lehrer', 'Fach', 'Raum', 'Klasse', 'Vertreter', 'Info', 'Art'], ] elems.append(static_data) for s in x: data = [ [s.date, s.date, s.period, s.absent_teacher, s.subject, s.room_name, s.klasse, s.substituting_teacher, s.substitution_message, s.substitution_kind], ] table = Table(data) elems.append(table) if len(substitution) <= i: pdf.build(elems) buffer.seek(0) return FileResponse(buffer, as_attachment=False, filename='hello.pdf') when I add static_data = [['Datum', 'Tag', 'Pos', 'Lehrer', 'Fach', 'Raum', 'Klasse', 'Vertreter', 'Info', 'Art'], ] elems.append(static_data) I get this error: AttributeError 'list' object has no attribute 'getKeepWithNext' when I remove it it works fine! I serached on the Internet for a similar error but couldn't find anything... Dose anybody know how to fix error ? -
how to access the multiple urls each time when i call in django?
I am new to django. in my code i have written the multiple views. When i call each url it is showing as below. Using the URLconf defined in new_2020.urls, Django tried these URL patterns, in this order: 1.admin/ 2.app_1/ function_based_view/ [name='function_based_view'] 3.app_1/ function_based_view_1/ [name='function_based_view_1'] 4.app_1/ templates/ [name='templates'] 5.url_1/ 6.templates but i want to output urls like below. app_1/ function_based_view/ url_1/ templates/ project level code snippet: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('app_1/',include('polls.urls')), path('url_1/',include('polls.urls')), path('templates',include('polls.urls')), ] application level code snippet: from django.urls import path from . import views urlpatterns = [ path('function_based_view/', views.function_based_view, name='function_based_view'), path('function_based_view_1/', views.function_based_view_1, name='function_based_view_1'), path('templates/', views.templates, name='templates'), ] -
CSRF token not set in Django with Python Request
I'm trying to send a POST request to a Django view from an ordinary Python script using Python-Request. The django view is not @login_required, so the only thing i need to send, other than my JSON data, is a CSRF token, here is what i tried: token = session.get('http://127.0.0.1:8000/myview/view') data = json.dumps({'test': 'value'}) session.post('http://127.0.0.1:8000/myview/myview', data={ 'csrfmiddlewaretoken': token, 'data': data}) The django view should just receive the Request and print it to my console: def myview(request): if request.method == 'POST': data = request.POST.get('data') print(json.loads(data)) print('received.') response = HttpResponse(get_token(request)) return response The problem with my current code is that my console will throw a log: WARNING - Forbidden (CSRF token missing or incorrect.). I cannot use @csrf_exempt, since i need this to be as safe as possible. Any advice? Thanks in advance!