Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Writing a custom manager for my model class with an existing obj instance
I am reading on how to write a custom manager for my model however it seems like I have a few questions. The reason I would like to add a custom manager to my class is because I would like to introduce a method called "customUpdate" which would basically check if the members in a dict are members of this class. This is what my code looks like so far.Then Ill post in some questions that I have class modelEmployer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) location = models.PointField(srid=4326,max_length=40, blank=True, null=True) objects = GeoManager() # models.GeoManager() Now this is what my manager class would like this is a rough sketch: class customEmployerManager(models.Manager): def customUpdate(dataDict): # Check if the fields in this data are present in this model for key in dataDict: empInst = How do I get instance of class which filter returned ? if not hasattr(empInst, key): # This property is not present dataDict.pop(key) empInst.update(**dataDict) #Will this work ? Update only works with queryset Now here are my questions 1- From the tutorials that I read I need to add customEmployerManager to my main model class as an object member like this objects = customEmployerManager() however I am currently … -
Django Admin authentication credentials not provided - HTTP 401
My Django app is not recognizing the credentials in the admin panel for some models. I can login, view part of the models, but for some others I see the following error message: {"detail":"Authentication credentials were not provided."} Interesting: there are models I can see but when I click on "Add" to add an entry, I see the error message. Among others, I am using the following libraries: Django==2.0.9 django-cors-headers==2.4.0 django-extensions==2.1.3 django-storages==1.7.1 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 In my settings.py I have the following: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'django_extensions', 'storages', 'rest_framework', 'authentication.apps.AuthenticationConfig', 'directory.apps.DirectoryConfig', 'metacontent.apps.MetacontentConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] and also: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( #'rest_framework.permissions.IsAuthenticated', #removed for open docs access ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100, 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '1000/hour', 'user': '6000/hour', }, } When the request is NOT working, the headers of the response are the following: HTTP/1.1 401 Unauthorized Date: Fri, 02 Nov 2018 21:50:27 GMT Server: Apache/2.4.34 (Amazon) mod_wsgi/3.5 Python/3.6.5 Allow: GET, HEAD, OPTIONS Vary: Origin X-Frame-Options: SAMEORIGIN WWW-Authenticate: JWT realm="api" Content-Length: 58 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: application/json … -
Writing a custom update method for a model in django
I would like to write a custom update method for my model. Basically I would like to make sure that the fields that being passed to this method are fields that are present in this model. I came up with something like this def update(self,dict): #Check if the fields in this data are present in this model for key in data: if not hasattr(self, key): #This property is not present data.pop(key) self.update(data) However when I do something like this modelMyobject.objects.filter(xxxxx).update(**dict) This method never gets called. Any suggestions on what I could do to fix this ? -
How to incorporate saleor into existing django website?
I have some limited experience creating django websites, and I am getting more comfortable with it. I am currently working on the most complicated site I have done, which requires eCommerce functionality (shopping cart, order tracking, etc). Saleor seemed like an amazing fit as not only does it provide all the functionality I need and is compatible with my existing site, it includes a lot of functionality I would have liked to have but didn't think was possible until at a much later date. My problem is that when I followed the instructions to download and install saleor, it seems to be a distinct django website/project. I'm used to installing django apps via pip and adding to INSTALLED_APPS, but saleor doesn't seem to be added like that. Given that it is a completely distinct site that I have to run on a separate port from my main site (at least while using the development server with manage.py), how can I integrate it into my existing project? -
{% debug %} django template tag not working
Hello people of the world!!! Little issue here, I´m trying to print some pictures, and use the inbuilt debug django template tag {% debug %}, but the result is that is printing some awkward lines. There is a print - screen of the Thanks people!!! -
Request of dictionary keeps coming in as Str, how can I get it to pass through as a dictionary?
Hi I made an http POST and it keeps receiving as a string. I am trying to get it as a dictionary so I can pull each key, value. I have my $http.post('/route/', data).success({console.log("succes")}} My data: var data ={} data['company'] = user.user.company_name data['farmer'] = user.farmer data['number'] = "+14087729399" Then from my views: def initiate_sms(request): user_data = request.body print user_data And would print as: {"company":"AkshaYagna","farmer":"Child.farm 06","number":"+14087729399"} Declaring that the whole thing is a string. I feel like I am missing something here. -
location__dwithin does not work - probably because range specified is not in degrees
I am trying to use location__dwithin however it gives an output of Unable to get repr for <class 'django.db.models.query.QuerySet'> This is my model class modelEmployee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200, unique=False, blank=False, null=True) location = models.PointField(srid=4326,max_length=40, blank=True,null=True) objects = GeoManager() This is the code that I am using transformedLocation = loggedInEmployer.location.transform(32148, clone=True) qset = modelEmployee.objects.filter(location__dwithin=(transformedLocation, D(mi=200))) however during debugging after running the filter command qset results in Unable to get repr for <class 'django.db.models.query.QuerySet'> I believe this is because 200 is not in degrees. My question is what are my options here to make this work ? Will I need to convert 200 miles to degrees ? -
Avoid N+1 problem fetching users and permissions in Django
I need to fetch a list of users and a list of permissions (guardian object permissions) each user has. The problem is that every way I am trying to do this runs into the N+1 problem. Whether I simply loop over the user list and get permissions from the set for user in User.objects.all(): data = UserSerializer(user).data data['permissions'] = PermissionSerializer(user.userobjectpermission_set, many=True) Or if I use prefetch_related() for user in User.objects.prefetch_related('userobjectpermission_set'): data = UserAndPermSerializer(user).data It ends up fetching the user list first and then running a separate permission query for every single user. I can write a raw SQL statement and serialize it myself, but I would rather use the serializers I already have and so I would like to have the users and permissions as model instances. Any way to accomplish what I need using the ORM? Django is version 1.11 LTS and I cannot upgrade to 2.x any time soon. -
Django fail to connect to postgres database in gitlab ci
I have the following .gitlab-ci.yml : image: python:3.6 stages: - lint - test services: - postgres:10.1-alpine cache: paths: - /root/.local/share/virtualenvs/ before_script: - python -V - pip install pipenv - pipenv install --dev lint: stage: lint script: - pipenv run pylint --output-format=text --load-plugins pylint_django project/ | tee pylint.txt - score=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' pylint.txt) - echo "Pylint score was $score" - pipenv run anybadge --value=$score --file=pylint.svg pylint artifacts: paths: - pylint.svg test: stage: test script: - pipenv run python manage.py test And I am connecting to the database like this : # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'db', # set in docker-compose.yml 'PORT': 5432 # default postgres port } } For now, I just have this tests in users/tests.py : from .models import CustomUser from django.test import TestCase class LogInTest(TestCase): def setUp(self): self.credentials = { 'username': 'testuser', 'password': 'secret'} CustomUser.objects.create_user(**self.credentials) def testLogin(self): # send login data response = self.client.post('/users/login/', self.credentials, follow=True) # should be logged in now self.assertTrue(response.context['user'].is_authenticated) Which fails with the following error : psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known In development, I use the following docker-compose.yml … -
Django - Force a user to reset initial password
I am implementing a functionality where a user is forced to change a password (i.e. if the admin creates an initial password, the user is required to change it on the next login). I am using the Django Contrib Auth package. For this, I have a extended the user profile by a boolean parameter force_password_change: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) force_password_change = models.BooleanField(default=True) In my view, I am extending the standard LoginView: class MyLoginView(LoginView): def form_valid(self, form): # form is valid (= correct password), now check if user requires to set own password if form.get_user().profile.force_password_change: return HttpResponseRedirect('password_change') else: auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) The system renders a 404 page not found error after I click the login button: The current path, accounts/login/, didn't match any of these. I noticed that when I add auth_login(self.request, form.get_user()) just before the HttpResponseRedirect('password_change') it works fine. But this also means that the user is (incorrectly) authenticated. urls.py: path('', myapp.MyLoginView.as_view(), name='login'), path('password_change/', myapp.MyPasswordChangeView.as_view(), name='password_change'), Why is this the case and why is the 404 error refering to accounts/login/? -
Django- user foreign key
I have been doing a project where I added user (custom user model) as a foreign key(field name, added_by) to another model(say, post). Now I want to filter from post table by a specific user and/or logged in user. How do I do that? I tried the following, content= post.object.filter(added_by=request.user.username) -
Django TastyPie GenericForeignKeyField error
I have the following Django models and TastyPie resources: Models: calendar/models.py: class CalendarEntry(models.Model): content_type = models.ForeignKey(ContentType, verbose_name='content type') object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') event/models.py: class Event(ProtectedModel): event = generic.GenericRelation('mypkg.calendar.CalendarEntry') Resources: calendar/pie.py: class CalendarEntryResource(ModelResource): content_object = GenericForeignKeyField({ Event: EventResource, }, 'content_object', null=False, blank=False) event/pie.py: class EventResource(ModelResource): event = fields.ManyToManyField( 'mypkg.calendar.pie.CalendarEntryResource', 'event', related_name='content_object', full=False ) If I visit /calendar/api/v1/calendar-entry/ the returned objects include the URI for the 'content_object' (i.e. the event). However, if I visit /event/api/v1/event/ I get an error: "The model '<Event: Title>' has an empty attribute 'event' and doesn't allow a null value." I've followed the documentation and references I've found as best as I can, but I can't seem to get this working. Any suggestions appreciated. -
Django: Migrating mysql to postgres with pgloader stalls
I'm in the process of migrating my Django db from mysql to postgres. I've been following along with the guide found here, but have run into a wall when moving the data over from the old db to the new. I'm using a script to do this: LOAD DATABASE FROM mysql://mysql_username:mysql_password@localhost/mysql_dbname INTO postgresql:///myproject WITH truncate, data only, disable triggers, preserve index names, include no drop, reset sequences ALTER SCHEMA 'mysql_dbname' RENAME TO 'public' ; I run the script with pgloader and it goes for a while and stops. Output below: [...] 2018-11-02T19:59:30.832000Z NOTICE COPY public.auth_group 2018-11-02T19:59:30.832000Z NOTICE COPY public.auth_group_permissions 2018-11-02T19:59:30.832000Z NOTICE COPY public.auth_permission 2018-11-02T19:59:30.832000Z NOTICE COPY public.auth_user 2018-11-02T19:59:30.832000Z NOTICE COPY public.auth_user_groups 2018-11-02T19:59:30.832000Z NOTICE COPY public.auth_user_user_permissions 2018-11-02T19:59:30.832000Z NOTICE COPY public.django_admin_log 2018-11-02T19:59:30.832000Z NOTICE COPY public.django_content_type 2018-11-02T19:59:30.833000Z NOTICE COPY public.django_migrations 2018-11-02T19:59:30.833000Z NOTICE COPY public.django_session 2018-11-02T19:59:30.833000Z NOTICE COPY public.scoutapp_field 2018-11-02T19:59:30.833000Z NOTICE COPY public.scoutapp_labelledata 2018-11-02T19:59:30.833000Z NOTICE COPY public.scoutapp_labellefieldorder 2018-11-02T19:59:30.833000Z NOTICE COPY public.scoutapp_leafsamplefields 2018-11-02T19:59:30.833000Z NOTICE COPY public.scoutapp_leafsamples 2018-11-02T19:59:30.833000Z NOTICE COPY public.scoutapp_leafsufficiency 2018-11-02T19:59:30.833000Z NOTICE COPY public.scoutapp_rustmitefields 2018-11-02T19:59:30.833000Z NOTICE COPY public.scoutapp_rustmites 2018-11-02T19:59:30.833000Z NOTICE COPY public.scoutapp_scoutingareas 2018-11-02T19:59:30.834000Z NOTICE COPY public.scoutapp_sensorlocations 2018-11-02T19:59:30.834000Z NOTICE COPY public.scoutapp_soilmoisturedata 2018-11-02T19:59:30.834000Z NOTICE COPY public.scoutapp_spraytrials debugger invoked on a CL-POSTGRES::PROTOCOL-ERROR in thread #<THREAD "lparallel" RUNNING {1006AC6013}>: PostgreSQL protocol error: Unexpected message received: Z debugger invoked on … -
How to read image from database(sqlite Django) not local file?
OpenCV => 3.4, Operating System / Platform => Ubuntu18.4, Compiler => Pycharm2018, Django => 2.1.2 Model from django.db import models class Image(models.Model): name = models.CharField(max_length=500) imagefile = models.FileField(upload_to='images/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.imagefile) Read Image from .models import Image import cv2 lastimage = Image.objects.last() imagefile = lastimage.imagefile image = cv2.imread(imagefile) cv2.imshow('image',image) Error Get this error Exception Type: TypeError Exception Value: bad argument type for built-in operation -
How to solve CORS problem of my Django API?
I cannot solve CORS problem in my Django API. When I make a call to this API, I get error: Access to fetch at 'http://localhost:8000/' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. To enable CORS, I did pip install django-cors-headers and added the following code to settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'localhost:80', 'localhost:8000', '127.0.0.1:8000' ] I should say that I run my project on Docker. This is docker-compose.yml: version: '2' services: django-docker: build: context: . dockerfile: Dockerfile.django container_name: my.django image: my-django ports: - 8000:8000 webapp-docker: build: context: . dockerfile: Dockerfile.webapp container_name: my.webapp image: my-web ports: - 80:80 -
Send celery task message to rabbitmq
I usually use celery with Django and run shared tasks in Django. But for specific case, I want to add task queue to rabbitmq manually without running Django or celerybeat. Is there any simple python script or shell cmd to do that? -
M2m-relation object in django admin test client post
Hei, I'm unit testing django admin page for models with m2m-relations. I have a custom clean function in my models, thus I need some test cases for the admin page. The problem is that I don't know how to create the payload dictionary for test client post with ManyToManyField. models.py: class Statistics(models.Model): short_name = models.CharField(default=u"", max_length=200) full_name = models.CharField(default=u"", max_length=200) id = models.AutoField(primary_key=True) class Query(models.Model): url = models.CharField(default=u"", max_length=200) query = models.TextField(default=u"") id = models.AutoField(primary_key=True) title_fi = models.CharField(default=u"", max_length=500) statistics = models.ManyToManyField(Statistics, related_name='queries') def clean(self): print("Query clean: ",self.__dict__) try: json_query = json.loads(self.query.replace("\'", "\"")) except Exception: raise ValidationError(u'Väärin muodostettu query') if not get_data(self.url, json_query): raise ValidationError(u'Väärin muodostettu query tai query ei palauttanut lukua') tests.py: response = self.client.post('/admin/key_values/query/add/', {'url': url, 'query': str(query),'title_fi':'fi'}, follow=True) This doesn't pass because statistics-field cannot be undefined. (If I put 'blank=True' there, my above test will pass, but that's something I don't want to do !). How can I include at least one statistices-object into my test case ? -
Django FloatField and DecimalField creation return different than object in database
I've just realise that in Django2, the object at the creation (using xxx.objects.create or xxx.save) return an object that is a little bit different than the object which is really in database (MODEL.objects.get(the object created)). You can see it using DecimalField or FloatField: class Product(Model): price = FloatField() then running the shell (python manage.py shell): from *project*.models import Product a = Product.objects.create(price=30) # or "a = Product(price=30); a.save()" b = Product.objects.get(price=30) a == b # True a.price == b.price # True str(a.price) == str(b.price) # False : "30" == "30.0" Is this a bug from django ? Because when you create an object using the xxx.objects.create method, you expect it to return the same object (at least the same copy) than what you get when you search this object in the database. I found the source code of the create method: def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj Many thanks ! -
Django insert data on signup
I have a users app in a Django project (2.1). After an user signup (both front end and when added in the admin dashboard ideally), I'd like to insert data in one other table. I know how to insert data, but I don't find how to do it right after a successfull signup. # users/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username',] admin.site.register(CustomUser, CustomUserAdmin) # users/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email') # users/models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): # add additional fields in here credit = models.IntegerField(default=200) # editable=False def __str__(self): return self.email # users/urls.py from django.urls import path from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), ] # users/views.py from django.urls import reverse_lazy from django.views import generic from .forms import CustomUserCreationForm class SignUp(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' And … -
request.POST not being picked up in django
I am using apiary to send API calls via POST. The method being sent is POST and it's sending the corret POST DATA, but django is not picking it up in the request.POST dict: # this is printing request.method, request.body [remote IP:43306] POST b'{\\n "email": "tomas@gmail.com",\\n "password": "hellopassword"\\n}' # this is printing request.POST [pid 4974:tid 140607472903936] [remote 54.81.191.72:43306] 333 POST <QueryDict: {}> Why can't django properly parse the POST data here? -
Configuring Django Production Settings and Content Security Policy
I'm trying to configure my site to pass the tests at: https://observatory.mozilla.org https://csp-evaluator.withgoogle.com/ I've been looking at this blog post. My Django settings in production are as follows: # Content Security Policy CSP_DEFAULT_SRC = ("'none'", ) CSP_STYLE_SRC = ("'self'", "fonts.googleapis.com", "'sha256-/3kWSXHts8LrwfemLzY9W0tOv5I4eLIhrf0pT8cU0WI='") CSP_SCRIPT_SRC = ("'self'", ) CSP_IMG_SRC = ("'self'",) CSP_FONT_SRC = ("'self'", "fonts.gstatic.com") CSP_CONNECT_SRC = ("'self'", ) CSP_OBJECT_SRC = ("'none'", ) CSP_BASE_URI = ("'none'", ) CSP_FRAME_ANCESTORS = ("'self'", 'https://example.com/', 'https://example.com/') CSP_FORM_ACTION = ("'self'", ) CSP_INCLUDE_NONCE_IN = ('script-src',) CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True X_FRAME_OPTIONS = 'DENY' SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True Yet, when I run the aforementioned tests I fail even though I have the above setup. Moreover, in Chrome dev tools I receive no errors, which is great. Anyone have advice on this please? Thanks -
One View Dynamic Template
I've got modules that if enabled/disabled would require a different arrangement of tables and iframes on the frontend webpage. In order to do this I set up a function to check which modules are enabled/disabled and assigned a number to each 'set' and will be created separate templates for each "set1.html", "set2.html", "set3.html", etc... I'd like to utilize one single view where I can pass the set number from from function I created but I can't seem to figure out how. def homeset(request): return render(request, 'app/set1.html', {}) Looking to figure out some way to make the "1" the return of the function I created to determine which set# to load as template and would prefer to not have to create a view for every single template needed. -
Django MPTT - filter objects including their parents
I'm trying to figure out how to get QuerySet or TreeQuerySet of objects including their ancestors. I have a model Location - it can be Venezia,Italy,Croatia,Europe.. etc... Now I want to filter locations and I want this filtered QuerySet to include all their ancestors. So for example: Location.objects.filter(name__in=['Venezia','Zagreb']) would return QuerySet of Venezia,Italy,Zagreb,Croatia,Europe instead of Venezia,Zagreb I can do that using for loop but I'm curious if it's possible to do that using Django ORM. -
Django urls - don't allow direct opening when using {% include %}
In django 2.0.2 template I include datatable (from https://datatables.net/) using {% include 'ExchangesList.html' %} Everything is working fine. But when I open /exchanges/exchanges_list_json/ in browser there is data used for table visible. urls.py urlpatterns = [ #url(r'^$', ExchangesList.as_view(), name="exchanges"), url(r'^exchanges_list_json/$', ExchangesListJson.as_view(), name="exchanges_list_json"),] exchanges_list.js $(document).ready(function() { var table = $('#exchanges_table').DataTable( { "ajax": EXCHANGES_LIST_JSON_URL, ... views.py class ExchangesList(TemplateView): template_name = 'ExchangesList.html' class ExchangesListJson(BaseDatatableView): model = Exchanges columns = [ 'exchange_sort_id', 'exchange_name', 'exchange_country', 'exchange_url', 'exchange_trade_volume_24h_btc', 'exchange_last_updated', ] order_columns = columns def filter_queryset(self, qs): qs = Exchanges.objects.all() sSearch = self.request.GET.get('sSearch', None) if sSearch: qs = qs.filter(Q(exchange_name__istartswith=sSearch) | Q(exchange_description__istartswith=sSearch) | Q(exchange_id__istartswith=sSearch)) return qs def prepare_results(self, qs): qs = Exchanges.objects.all() json_data = [] for item in qs: json_data.append({ 'exchange_sort_id': escape(item.exchange_sort_id), 'exchange_name': escape(item.exchange_name), # escape HTML for security reasons 'exchange_country': escape(item.exchange_country), 'exchange_url': escape(item.exchange_url), 'exchange_trade_volume_24h_btc': escape(item.exchange_trade_volume_24h_btc), 'exchange_last_updated': item.exchange_last_updated.strftime("%H:%M:%S "), }) #print(json_data) #print('len qs ' , len(qs)) return json_data How can I block direct opening exchanges_list_json.html keeping possibility to include? Thank you for any help! -
How to send POST request to Django API from ReactJS web app?
I created a very simple Django API. It returns a fixed numeric value (just for testing purpose): views.py from django.http import HttpResponse def index(request): return HttpResponse(0) I also have a simple front-end developed using React JS. To develop the backend and front-end, I was using these two tutorials: ReactJS: https://mherman.org/blog/dockerizing-a-react-app/ Django Python API: https://semaphoreci.com/community/tutorials/dockerizing-a-python-django-web-application Now I want to send a POST request to Django API from ReactJS and pass name and email parameters. How can I do it? This is my App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { fullname: "", emailaddress: "" }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { const target = event.target; const value = target.type === "checkbox" ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } handleSubmit(event) { event.preventDefault(); console.log(this.state); } render() { return ( <div className="App"> <header> <div className="container"> <nav className="navbar"> <div className="navbar-brand"> <span className="navbar-item">Forms in React</span> </div> </nav> </div> </header> <div className="container"> <div className="columns"> <div className="column is-9"> <form className="form" onSubmit={this.handleSubmit}> <div className="field"> <label className="label">Name</label> <div className="control"> <input className="input" type="text" name="fullname" value={this.state.fullname} onChange={this.handleChange} /> </div> </div> <div className="field"> <label className="label">Email</label> <div className="control"> …