Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelForm set instance file input change text
I have the following code: advertisement = Advertisement.objects.get(id=advertisementid) form = AdvertisementForm(request.POST or None, request.FILES or None, instance=advertisement) I'd like to change the text Currently, Change which is initially set by Django in my HTML-View where a image or file can be chosen. Thanks for your help. -
Heroku + Django, can't make migration to postgres
I'm trying to put a django based app on Heroku with Docker. I'm using one container for postgres and another one for my app locally. In production, I only push my app and use heroku postgres add-on. Locally it works fine. But when I try to upload it to Heroku, my app seems able to connect to postgres database, but can't find any tables. I have no idea where the problem is, except maybe migrate fail because of some restricted authorisation (but I didn't see any error outputs through the Heroku logs): here my docker-compose: web: build: . command: bash -c "python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db And here the postgres conf: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) Here is my problem: 1) I can't connect directly to the heroku dyno because this is a lot of painful configuration and I didn't succeed (the documentation is a little blurry about how to achieve this) 2) I have no idea if the postgres is actually linked. All i did is put db_from_env = dj_database_url.config(conn_max_age=500) as … -
Django url patterns, redirect from root to other url
This should be an easy enough problem to solve for you guys: I just started working with Django, and I'm doing some routing. This is my urls.py in the root of the project: urlpatterns = [ path('admin/', admin.site.urls), path('', include('dashboard.urls')), ] This is the routing in my dashboard app: urlpatterns = [ path('dashboard', views.index, name='index'), path('', views.index, name='index'), ] Now let's say I want my users to be redirected to /dashboard if they go to the root of the website. So I would use '' as a route in the urls.py in the root, and then have everyone sent to /dashboard from the urls.py in the dashboard app. But when I do this I get the following warning: ?: (urls.W002) Your URL pattern '/dashboard' [name='index'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. So I tried to use '/' instead of '', but since a trailing / is automatically removed from an url, the url wouldn't match the pattern. Should I ignore/mute this warning or is there another way to go about it? -
Access Data from Angular JS http.POST with Django Python HTML to Views.py
I am new to Python with django. I need to process the data from Angular js http.post in Views.py. My data got posted but i am unable to use/process the data in views.py. Plz help. i like to get data in list or dict. `enter code here` <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> <html lang="en"> {% load staticfiles %} <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> </head> <form action="/your-name/" method="POST"> {% csrf_token %} <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" value="{{ current_name }}"> {% csrf_token %} {{name.customer_gid}} {{name.customer_name}} <input type="submit" value="OK"> </form> <body> <a href="{% url 'stock' %}">Stock </a> <div ng-app="Appemployee" ng-controller="CustomerController"> {% csrf_token %} <p> Name : <input type="text" ng-model="name"> </p> {% verbatim %} U Typed : {{name}} <div> <input type="text" name="txt_post" value="" ng-model="txt_db_post" > <input type="submit" value="Post To DB" ng-click="POST_script_DB()"> </div> {% endverbatim %} </div> <script> var myApp = angular.module('Appemployee', []).config(function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }); myApp.controller('CustomerController', ['$scope','testService', function($scope,testService) { $scope.POST_script_DB = function() { var posteddata = testService.getcusomter($scope.txt_db_post); posteddata.then(function (result){ alert(result.data); }),function(){ alert('no data'); }; <!--alert($scope.txt_db_post)--> }; }]); myApp.service("testService", function ($http) { this.getcusomter = function (e) { var response = $http.post("/stock_post/",{parms:{"stock_post":e}}); alert(response) return response; } }); </script> </body> </html> The above html and service will post data to views … -
Django_permissions, how to template my menu item based on the permissions? in the view.py
I want to display menu item based on my given permissions, for example users who are not a Project manager thex dont see item project in the menu and so on.. I have a separated Client dashboard from admin dashboard which is not so good and pro. Here my code: views.py class UsersListView(PermissionRequiredMixin, LoginRequiredMixin, ListView): login_url = 'accounts/login/' permission_required = 'can_view_user' template_name = "user_list.html" model = User def dispatch(self, request, *args, **kwargs): if check_permission_BM_or_AM(request): if request.user.is_authenticated(): return super(UsersListView, self).dispatch(request, *args, **kwargs) return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) permission.py def check_permission_BM_or_AM(request): customer= Customer.objects.get(auth_user_id=request.user.id) marolle = MaRolle.objects.filter(ma=customer.id) rollen = Rollen.objects.get(id=1) rollens = Rollen.objects.get(id=4) for ma in marolle: if str(ma.rolle) == rollen.rolle or str(ma.rolle) == rollens.rolle: return True menuitem.html <ul><li class="dropdown-submenu "> {% if perms.user %} <a tabindex="-1" href="/administrator/de/projekt/"><span class="fa fa-fw fa-book "></span> Projekte</a> {% endif %}</li></ul> how to use the template to get my class view to work based on the given permission_required = 'can_view_user'permission? -
delete date range from DateTime field in Django
I have the following function that takes a csv file, reads the unique dates, and then deletes them. def delete_dates(self, lines): try: #read csv file file = csv.DictReader(lines.splitlines(), delimiter=',') #holds the dates that will be deleted from the DB dates = [] for row in file: #append every date in the file dates.append(self.get_date_only(row['date/time'])) #print unique dates in dates list print set(dates) #prints MAX AND MIN print max(set(dates)) print min(set(dates)) #if there are dates delete all objects from that date with the same country and company if set(dates) > 0: for date in set(dates): try: objects_to_delete = Payments.objects.filter( date_time=date ).filter( Account=self.company ).filter( Country=self.country ).delete() except Exception as e: print (e) except Exception as e: print (e) return False return True It seems like it is looking for objects with the same date and 0:00 for the time. I would like the same logic as: delete from Table where Account = 'account' and Country = 'country' and date_time between min(set(dates)) and max(set(dates)) This way all data from the dates in dates list are deleted. -
django - authenthicate - missing required potential argument 'self'
I have a custom auth backend and I am trying to connect users with it. This is the backend import logging from .models import Users class OwnAuthBackend(object): def authenticate(self, email, password): try: user = Users.objects.get(email=email) if user.check_password(password): return user else: return None except Users.DoesNotExist: logging.getLogger("error_logger").error("user with login %s does not exists " % login) return None except Exception as e: logging.getLogger("error_logger").error(repr(e)) return None def get_user(self, user_id): try: user = Users.objects.get(sys_id=user_id) if user.is_active: return user return None except Users.DoesNotExist: logging.getLogger("error_logger").error("user with %(user_id)d not found") return None And this is in the view.py email = form.cleaned_data['email_field'] password = form.cleaned_data['password'] user = OwnAuthBackend.authenticate(email=email, password=password) if user is not None: messages.success(request, 'You logged in successfully!') return redirect('index') else: messages.warning(request, 'Credentials were wrong. Failed to log in!') return redirect('index') message.error(request, 'Something went wrong while logging you in..') return redirect('index') The import: from main.backends import OwnAuthBackend Error is in the title I really have no idea what self I have to make, tried placing the request there but that didn't work. According to: users.is_authenticated - custom user model, the user is logged in if I use user = OwnAuthBackend.authenticate(request, email=email, password=password) But the problem is, if I go to control panel, the user isn't logged in … -
Issue with Django Paginator
I'm trying to use Django Paginator according to my CBV process but I don't overcome to display pages with my array. My class looks like : class IdentityIndividuResearchingView(LoginRequiredMixin, ListView) : template_name = 'Identity_Individu_Recherche.html' model = Individu context_object_name = 'queryset' def get_object(self) : queryset = Individu.objects.order_by("-id") return queryset def get_context_data(self, **kwargs) : context_data = super(IdentityIndividuResearchingView, self).get_context_data(**kwargs) person_France = Individu.objects.filter(Pays='FR') context_data['person_France'] = person_France if 'recherche' in self.request.GET: query_lastname_ID = self.request.GET.get('q1ID') query_firstname_ID = self.request.GET.get('q1bisID') query_naissance_ID = self.request.GET.get('q1terID') sort_params = {} lib.Individu_Recherche.set_if_not_none(sort_params, 'Nom__icontains', query_lastname_ID) lib.Individu_Recherche.set_if_not_none(sort_params, 'Prenom__icontains', query_firstname_ID) lib.Individu_Recherche.set_if_not_none(sort_params, 'VilleNaissance__icontains', query_naissance_ID) query_ID_list = Individu.objects.filter(**sort_params) context_data['query_ID_list'] = query_ID_list paginator = Paginator(query_ID_list, 3) page = self.request.GET.get('page', 1) try: query_ID_list = paginator.page(page) except PageNotAnInteger: query_ID_list = paginator.page(1) except EmptyPage: query_ID_list = paginator.page(paginator.num_pages) And my template looks like this : <table class="tableform" style="width:85%"> <tbody> <tr> <th>ID</th> <th>État</th> <th>N° Identification</th> <th>Civilité</th> <th>Nom</th> <th>Prénom</th> <th>Date de Naissance</th> <th>Ville de Naissance</th> <th>Pays de Naissance</th> <th>Institution</th> </tr> {% for item in query_ID_list %} <tr> <td>{{ item.id}}</td> <td>{{ item.Etat}}</td> <td>{{ item.NumeroIdentification}}</td> <td>{{ item.Civilite }}</td> <td>{{ item.Nom }}</td> <td>{{ item.Prenom }}</td> <td>{{ item.DateNaissance }}</td> <td>{{ item.VilleNaissance }}</td> <td>{{ item.PaysNaissance }}</td> <td>{{ item.InformationsInstitution }}</td> </tr> {% endfor %} </tbody> </table> {% if query_ID_list.has_previous %} <a href="?page={{ query_ID_list.previous_page_number }}&q1ID={{ request.GET.q1ID }}">Page précédente</a> {% endif %} <span class="current"> … -
Django rest api post data from browser
I am a newbie in Django so forgive if the question is silly but I didn't find the answer of it. I am making an API which goes GET and POST request of in the products table. views.py rom rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . models import products from . serializers import productSerializer from django.db.models import Q class productList(APIView): def get(self, request): product_list = products.objects.all() serializer = productSerializer(product_list, many=True) query = self.request.GET.get("item_id") if query: product_list = product_list.filter( Q(item_id=query)).distinct() serializer = productSerializer(product_list, many=True) return Response(serializer.data) def post(self): serializer = productSerializer(self.request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py from django.contrib import admin from django.urls import path from webshop import views urlpatterns = [ path('admin/', admin.site.urls), path('products', views.productList.as_view()), ] models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class products(models.Model): item_id = models.CharField(max_length=20) item_name = models.CharField(max_length=255) item_price = models.FloatField(validators = [MinValueValidator(0.0)]) def __str__(self): return self.item_name I can use the get request in the browser easily with the following urls in the browser and the get the required JSON data. # Get all the products http://localhost:8000/products # Get the product with id=2 http://localhost:8000/products?id=2 Now I want to do the POST request using … -
Wagtail OpenCV with Python3
Looking at this page http://docs.wagtail.io/en/v1.13.1/advanced_topics/images/feature_detection.html What would be the equivalent to sudo apt-get install python-opencv python-numpy for python3 I've found python3-numpy but can't seem to find a version of opencv for python3, I've ended removing that from our Dockerfile and installing opencv-python==3.4.0.12 in our requirements file. This seems to work but is this a non standard way to handle this or is this ok? Thanks Joss -
Django - Using signals to make changes to other models
say I have two models like so... class Product(models.Model): ... overall_rating = models.IntegerField() ... class Review(models.Model): ... product = models.ForeignKey(Product, related_name='review', on_delete=models.CASCADE) rating = models.IntegerField() ... I want to use the ratings from all of the child Review objects to build an average overall_rating for the parent Product. Question: I'm wondering how I may be able to achieve something like this using Django signals? I am a bit of a newbie to this part of Django; have never really understood the signals part before. This overall_rating value needs to be stored in the database instead of calculated using a method since I plan on ordering the Product objects based on their overall_rating which is done on a DB level. The method may look something like this if I were to implement it (just for reference): def overall_rating(self): review_count=self.review.count() if review_count >= 1: ratings=self.review.all().values_list('rating',flat=True) rating_sum = 0 for i in ratings: rating_sum += int(i) return rating_sum / review_count else: return 0 Thank you -
How to use django admin to automatically select the model ??
For example, there are 3 models, task, car, driver. task has two foreign keys, car and driver. Car OneToOneField driver. After the task select the car, how to automatically correspond to the driver, in the admin interface?? thank you all -
Filtering results using Javascript and Django model not working
I have a model for events which are in different cities. When on the site you choose a city that you're in. What I want to do is that you only ever see available events of the city you're in. My problem is that in rendering the html results I seem to have a problem regarding the views and interaction between javascript in getting the city and the django models and having the results filter. When I try to get the city stated within the view using 'GET' I keep getting an error regarding global variables not being declared that is I use this following construction: def IndexPage(request): def GetCitySession(request): if request.method == "GET": global cityName cityName = request.session['city-name'] cityId = request.session['city-id'] context = { "cityName": cityName, "cityId": cityId } return JsonResponse(cityName) venues = ProfileVenue.objects.all().filter() oc_list = [] for venue in venues: if Occurrence.objects.filter(date__gte=timezone.now()).filter(event__location=venue).exists() and venue.city.name==cityName: or I get 'Key error' error with exception value 'city-name' if I use this construction: if Occurrence.objects.filter(date__gte=timezone.now()).filter(event__location=venue).exists() and venue.city.name==request.session['city-name']: So how would one go about making sure it filters correctly? I've looked around and I haven't yet found something suitable to my needs. Javascript that sets city values /* Ciudades */ if(localStorage.getItem("cities") == null){ … -
Creating django model with foreignkey field
Suppose I have the following models: class Room(models.Model): title = models.CharField(max_length=255) room_log = models.ForeignKey("Log", on_delete=models.CASCADE, blank=True, null=True) ... class Log(): fs = FileSystemStorage(location=LOG_PATH) name = models.CharField(max_length=255) log = models.FileField(storage=fs, blank=True, null=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not os.path.exists(LOG_PATH): os.makedirs(LOG_PATH) self.log.save(self.name + '.log', ContentFile('start of log!')) return super(Log, self).save(force_insert, force_update, using, update_fields) else: if not os.path.isfile(LOG_PATH + self.name + ".log"): self.log.save(self.name + '.log', ContentFile("start of log!")) else: pass return super(Log, self).save(force_insert, force_update, using, update_fields) I want for each Room model I create to have assigned a new Log model with the same name of the room. I've tried editing the save() function of the Room model like this: def save(self, *args, **kwargs): if not self.pk: Log.objects.create(name=self.title) return super(Room, self).save(*args, **kwargs) But it just returns the error UNIQUE constraint failed: chat_log.id when creating a new Room model (The creation of Log model works great). How would I do that? -
pyrqlite/rqlite Insert statement has no effect
My python insert statement seems to have no effect on my rqlite database. I tried to change the insert statement several times with no success, I also read the DOC 3 times now and couldn't find any solution. Python doesn't catch any exceptions neither, so I have no idea what the error could be. I started the first node like so: ./rqlited -http-addr 192.168.88.106:4001 -raft-addr 192.168.88.106:4002 ~/node and the second to join: ./rqlited -http-addr 192.168.88.12:4001 -raft-addr 192.168.88.12:4002 -join http://192.168.88.106:4001 ~/node when I then execute my script: with connection.cursor() as cursor: cursor.execute("INSERT INTO t_card(uuid, prim, active, id_person) VALUES(?, ?, ?, ?)", (nfc, 1, 1, pk)) connection.commit() no entry is made to the db the connection I establish like so: import pyrqlite.dbapi2 as dbapi2 IP = environ['IPTM'] connection = dbapi2.connect( host=IP, port=4001, ) the IPTM I set in bash, and it defenitely reads it in python export IPTM=192.168.88.106 any help is highly appreciated! -
How do I host my Django app on a intranet?
I have successfully developed a Django app. The requirement is to deploy the app over an on-premise server. The application is accessible on the intranet using the development environment. Is any web server is preferred to deploy this application locally (or) Should I leave the terminal running the server as it is so that the users can access the application as they are already doing it? Any suggestions appreciated. PS: I am using Unix server. -
POSTing foreign keys to Django Rest Framework, using Postman
So I've made a simple REST API for the company I work for. This is a side project, so I'm still learning a lot. So far it works nicely for GET requests. The problem I'm facing now is trying to do POST requests (Using Postman for now, the idea is to connect the API straight to a sensor that broadcasts JSON data and upload all that data to our DB through the API). The way we have set up the models, there are several ForeignKey relationships in our DB (we are using PostgreSQL if that makes a difference). I'm trying to POST one of our most basic bits of information, but arguably the most important which is measurement data. The model for a data point has a ForeignKey to a parameter, and a sensor. A parameter would be a model that has a parameter name, type, position, and a sensor would be another model that itself has a ForeignKey to a Chamber (another model that also includes it's own ForeignKeys, to Customers), and another ForeignKey to SensorType. In short, for relationships, data relates to parameter, and sensor (which relates to SensorType, and to Chamber which itself relates to Customer which … -
Django How can I render Images through a for loop
I uploaded images with admin, but cannot render them in the template. I've been looking at other questions but nothing is working. What am I missing? Settings.py STATIC_URL = '/static/' STATIC_DIRS = { os.path.join(BASE_DIR, "static"), } MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Models.py class Function(models.Model): name = models.CharField(max_length=50) fimage = models.ImageField(upload_to="images") def __unicode__(self): return "name{},id{}".format(self.name, self.id) HTML {% for function in functions %} <a href="function_page/{{function.id}}"> <img id=function_menu_pic src="{{MEDIA_URL}}{{function.fimage.url}}"></a> {% endfor %} -
Django-filter and Django-tables2 Using a foreign attribute
I've read through previous questions, and tried reading up in the docs but I've had no real luck with this. I'm using Django-tables2 in conjunction with Django-filter to display and filter data of students. Question 1: Table ordering One of the columns in the table (current standing) is populated using an accessor to a model manager in the student model, as follows: models.py class Student(models.Model): #a bunch of fields def get_current_standing(self): current_standing = AcademicStanding.objects.get(year=self.enrol_term, student=self).standing return current_standing tables.py class StudentTable(tables.Table): current_standing = tables.Column(accessor='get_current_standing') class Meta: model = Student fields = ["last_name", "first_name", "campus_id", "current_standing"] The table populates and displays correctly, but sorting by generates an error. I can adjust the Column as follows: current_standing = tables.Column(accessor='get_current_standing', order_by='academicstanding.standing') But because the relationship is 1:N I get multiple results, where (as shown by the manager in the students model), I only want the academic standing for a student for that particular year of enrolment. This method also doesn't group the entries according to the standing. Question 2: Django-filter I now wish to be able to filter by current_standing, too. filters.py class StudentFilter(django_filters.FilterSet): qset = AcademicStanding.objects.order_by('standing').values_list('standing', flat=True).distinct() l = [(t, t) for t in qset] current_standing = django_filters.ChoiceFilter(choices=l) class Meta: model = Student … -
Filter a table based on other two tables Django OMR
I have a table with fields email and department_name, another table named Department with a dept_name and a user table. Department table have a manytomany relation to user table. I need to filter first table with departments having user with email columns. Is there anyway to do this in a single query. My query may look like TempUser.objects.filter(email__in=Department.objects.filter(dept_name="department name from first table").users.value_list('email', flat=True) -
Function's url staying after a new render
I have just started learning Django after completing the tutorial on their website and I am trying to get my Django website's form to render a template with a dictionary describing the "login_error" variable after a login attempt has failed. This works fine but the URL still contains the view functions name and I don't want this. Redirecting the page to itself works fine but then I cannot define the "login_error" variable. The URL to start the views login function: path('login_user', views.login_user, name='login_user'), If the login fails I am re-rendering the page like so: return render(request, 'sign_in/sign-in.html', { 'login_error': "We couldn't find an account with that email and/or password." }) Here is what I am using to navigate to this function: <form class="sign_in" method="post" action="{% url 'sign-in:login_user' %}"> Here are some images to help explain what's happening: I submit a bad login: This is the part of the URL stays after the render: Any advice, links or resources to direct me in the way of a solution would be highly appreciated as I have been searching for hours now and still can't find anything related to this issue, thanks! -
django: trying to organize clean_data functions, and validators. Where does each thing go?
I am trying to find the way to organize code snippets the right way but I am getting mixed up with all this: I have the models.py where I have declared (show part of the fields) this class Posts(models.Model): image = models.ImageField(upload_to=user_directory_path, null=True, blank = True) Then I want to sanitize that field just in case someone wants to be funny in the form page. So I went to forms.py and created a custom method to clean it class PostsForm(ModelForm): class Meta: model = Posts fields = ['image' , 'otherfields'] def clean_image(self): image = self.cleaned_data['image'] Ok that cleans it, but I need more, like making sure they dont upload a file too large. So I thought I could create a directory in templates/validators and create a file like validators.py where I write my validation functions and then I can import that function. So. validators.py from django.core.exceptions import ValidationError def file_size(value): limit = 2 * 100 * 100 if value.size > limit: raise ValidationError('File too large. Should be less than 200 Kbs') so when I am in the forms.py I wanted to import that file validators.py like this from myaapp.validators import file_size but it tells me that it doesn't know what … -
Django Migration is not apply new migrations
I tried to make new migrations but show me error. I am using django1.9 and python 2.7 .Is any solution for this so i can create new migration.How can I do the migration? django.db.utils.IntegrityError: could not create unique index "appointments_userappointments_advance_c37857a7_uniq" DETAIL: Key (advance, status)=(5000, 3) is duplicated. Here is my model: class UserAppointments(models.Model): """ Represent an Appointment entity """ STATUS = ( ("1", 'Scheduled'), ("2", 'Active'), ("3", 'Completed'), ("4", 'Cancelled') ) customer = models.ForeignKey(Customer, null=True, blank=True) staff_user = models.ForeignKey(StaffUser, null=True, blank=True, related_name='staff_user') service = models.ForeignKey(Service, null=True, blank=True) advance = models.IntegerField(default=0, null=True, blank=True) date_time = models.DateTimeField(auto_now_add=True) creation_date = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(StaffUser, null=True, blank=True, related_name='created_by') update_date = models.DateTimeField(auto_now=True, null=True, blank=True) updated_by = models.ForeignKey(StaffUser, null=True, blank=True, related_name='updated_by') status = models.CharField(max_length=1, default=1, choices=STATUS) class Meta: verbose_name_plural = 'Appointments' ordering = ['date_time'] def __unicode__(self): return self.date_time.strftime("%Y-%m-%d %H:%M:%S") and my migration file: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('appointments', '0009_auto_20180114_1838'), ] operations = [ migrations.AlterModelOptions( name='userappointments', options={'ordering': ['advance'], 'verbose_name_plural': 'Appointments'}, ), migrations.AlterUniqueTogether( name='userappointments', unique_together=set([('advance', 'status')]), ), ] -
Django ManyToManyField Storing None objects
I am trying to create an audit app in which a model contains all the questions, answers in form of choices and comments class AuditQuestion(models.Model): NOT_INITIATED = 'NI' IN_PROCESS = 'IP' COMPELETED = 'C' STATUS = ( (NOT_INITIATED, 'Not Initiated'), (IN_PROCESS, 'In Process'), (COMPELETED, 'Completed'), ) type_of_room = models.ForeignKey(TypeOfRoom, null=True, blank=True) question = models.CharField(max_length=512) status = models.CharField(max_length=2, choices=STATUS, default=NOT_INITIATED) comments = models.TextField(null=True, blank=True) def __str__(self): return self.question Another model contains project status which contains details of the project such as location, project_name, user and floor no of the building class ProjectStatus(models.Model): floor_no = models.IntegerField(null=True) project_details = models.ForeignKey(ProjectDetails, null=True) question = models.ManyToManyField(AuditQuestion, null=True) def __str__(self): return str(self.floor_no) The logic goes like this... a new project is created using ProjectDetails model, and a project status is generated for every floor of the building. and each floor is to be audited against the questions present in AuditQuestion model and status and comments are to be registered. I used ManyToMany relation so that project status model can have multiple questions and their status and comments. But, when i try to save question it doesn't happen my view.py function is below: @login_required def save_question(request): project_status_id = request.POST.get('project_status_id') question_id = request.POST.get('question_id') status = request.POST.get('status') comments = … -
Request CSRF + Access-Control-Allow-Headers
Im developing an application with two core. Client Side with ReactJs and a Server Side made with Django. The Client will makes a lot of GET/POST request to the server. To prevent CSRF problem, every Ajax Request has CSRF-TOKEN. beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", window.csrftoken); } [...] } This is a piece of the Django/Python view view example of the server: response = HttpResponse(json.dumps(software_settings), content_type="application/json" ) response['Access-Control-Allow-Origin'] = "*"; response['Access-Control-Allow-Headers'] = "X-Requested-With, X-Prototype-Version, X-CSRF-Token"; response['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS"; I have two big problems: FIRST: On online solutions, window.csrftoken variables is usually taken from cookie. I sincerely don't know how to create it. Im using unversal-cookie to read and write cookie with React, but I missing the correct data flow between the two applications. The default values is "null" so the first call has null as CRFT Token; SECOND: I have a problem with response. As see above, I've tried to put a lot of configurations entry fro Access-Control. This is a piece of request headers: Access-Control-Request-Headers:x-csrftoken Access-Control-Request-Method:POST Connection:keep-alive Host:localhost:8000 Origin:http://localhost:3000 This is the error I get: Failed to load http://localhost:8000/get_software_settings/: Request header field X-CSRFToken is not allowed by Access-Control-Allow-Headers in preflight response. I …