Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django jQuery AJAX Autocomplete
I set an autocomplete field like bellow but its not working :( Is there any problem in it? import jQuery and jQuery UI: <script type="text/javascript" src="{% static 'js/jquery-1.12.4.min.js' %}"> </script> <script type="text/javascript" src="{% static 'js/jquery-ui.min.js' %}"> </script> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery-ui.css' %}"> In html template: <div class="ui-widget"> <label for="places">Places: </label> <input id="places"> </div> and : <script> $(function() { $("#places").autocomplete({ source: "/api/get_places/", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } </script> In url.py : url(r'^api/get_places/', views.get_places, name='get_places'), in views.py : def get_places(request): if request.is_ajax(): q = request.GET.get('term', '') places = Place.objects.filter(city__icontains=q) results = [] for pl in places: place_json = {} place_json = pl.city + "," + pl.state results.append(place_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) when i add print(places) in view, it works and returns correct fields from database based on the letter i entered in the textbox . so the problem is in the sending and receiving json data which it return! -
Django 'set' object is not reversible. Don't Know Why?
I'm creating a blog by using Django. And i got this error 'set' object is not reversible. Please let me know, why i encounter this error and How i can fix it? TypeError at /admin/ 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.0.2 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\USER\Anaconda3\lib\site-packages\django\urls\resolvers.py in _populate, line 416 Python Executable: C:\Users\USER\Anaconda3\python.exe Python Version: 3.6.0 Python Path: ['C:\\Users\\USER\\Desktop\\Django\\HarryBlog', 'C:\\Users\\USER\\Anaconda3\\python36.zip', 'C:\\Users\\USER\\Anaconda3\\DLLs', 'C:\\Users\\USER\\Anaconda3\\lib', 'C:\\Users\\USER\\Anaconda3', 'C:\\Users\\USER\\AppData\\Roaming\\Python\\Python36\\site-packages', 'C:\\Users\\USER\\Anaconda3\\lib\\site-packages', 'C:\\Users\\USER\\Anaconda3\\lib\\site-packages\\Sphinx-1.5.1-py3.6.egg', 'C:\\Users\\USER\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\USER\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\USER\\Anaconda3\\lib\\site-packages\\Pythonwin', 'C:\\Users\\USER\\Anaconda3\\lib\\site-packages\\setuptools-27.2.0-py3.6.egg'] Server time: Sun, 25 Feb 2018 08:31:27 +0000 This is my urls.py file: from django.conf.urls import url from django.contrib import admin from django.urls import path , include from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^about/$',views.about), url(r'^$', views.homepage), url(r'^Home/', include('Home.urls')), ] -
How to rate objects programmatically in Django Star Rating
I am using this library : django-star-rating to rate model objects by scores given by users. You can view the documentation here Problem that I face: How can I rate an object programmatically in view function rather than in the template. Also how can I integrate it with Django Rest framework? It uses a generic relation in the model schema. So far, I have used the field as Serializer Method field but the problem with that is that it is read only and the client cannot make patch request to update rating. Code so far: from star_ratings.models import Rating class ExampleModel(models.Model): rating = GenericRelation(Rating, related_query_name='example') from rest_framework import serializers class ExampleSerializer(serializers.HyperlinkedModelSerializer): rating_total = serializers.SerializerMethodField() rating_count = serializers.SerializerMethodField() class Meta: model = ExampleModel fields = '__all__' def get_rating_total(self, obj): if obj.rating.exists(): return obj.rating.first().total else: return 0 def get_rating_count(self, obj): if obj.rating.exists(): return obj.rating.first().count else: return 0 From drf docs : SerializerMethodField This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. Hence the field is read only and I can't rate it from … -
django with react using web pack
I have added react js in django using webpack loader WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles4/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } First time all things are OK. But when I change any code in react then don't change application with new code. Is it cache problem? -
Django blog deployment - server error 500
I have a simple blog project hosted on PythonAnywhere. When I go to my domain www.nomadpad.io I get "Server Error 500" From the error log below, it appears to be something to do with my editedimage field, which looks like this in my models.py : editedimage = ProcessedImageField(upload_to="images", blank=True, null=True, processors = [Transpose()], format="JPEG") This all works fine in my development environment, and I can run collectstatic on both versions. I can still access my live django-admin page, but when I try to upload an image, when I save the post, it returns again the Server Error 500. 2018-02-25 04:19:37,291: Internal Server Error: /#012Traceback (most recent call last):#012 File "/home/DMells123/.virtualenvs/nomadpadvenv/lib/python3.6/site-packages/django/template/base.py", line 882, in _resolve_lookup#012 current = current[bit]#012TypeError: 'ProcessedImageFieldFile' object is not subscriptable#012#012During handling of the above exception, another exception occurred:#012#012Traceback (most recent call last):#012 File "/home/DMells123/.virtualenvs/nomadpadvenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner#012 response = get_response(request)#012 File "/home/DMells123/.virtualenvs/nomadpadvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response#012 response = self.process_exception_by_middleware(e, request)#012 File "/home/DMells123/.virtualenvs/nomadpadvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response#012 response = wrapped_callback(request, *callback_args, callback_kwargs)#012 File "/home/DMells123/nomadpad/posts/views.py", line 24, in getAllPosts#012 return render(request, 'posts/getAllPosts.html', context)#012 File "/home/DMells123/.virtualenvs/nomadpadvenv/lib/python3.6/site-packages/django/shortcuts.py", line 30, in render#012 content = loader.render_to_string(template_name, context, request, using=using)#012 File "/home/DMells123/.virtualenvs/nomadpadvenv/lib/python3.6/site-packages/django/template/loader.py", line 68, in render_to_string#012 return template.render(context, request)#012 File "/home/DMells123/.virtualenvs/nomadpadvenv/lib/python3.6/site-packages/django/template/backends/django.py", line 66, in … -
Unable to send notification
I am using django notifications and I want to send a notification automatically before the expire date. Everything worked fine and notifications were being send until I add "if expired== datetime.date.today()" to views.py. How can I fix this and send notification at desired time? My django code: models.py from django.db import models from django.contrib.auth.models import User from datetime import datetime, timedelta import notifications # Create your models here. class Truck(models.Model): truck_id = models.CharField(max_length=10) insurance_id = models.CharField(max_length=10, null=True,blank=True) insurance_expiry = models.DateTimeField(null=True,blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False) days_left=3 def expire_date( self ): return self.insurance_expiry - timedelta( minutes= self.days_left) views.py from django.shortcuts import render from notifications.models import Notification from notifications import notify from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model import datetime from .models import Truck from celery.schedules import crontab from celery.task import periodic_task # Create your views here. @login_required def home(request): notifications = request.user.notifications.unread().order_by('-timestamp') return render(request, 'index.html', {'notifications': notifications}) @login_required @periodic_task(run_every=crontab(hour=06,minute=31)) def send_notification(request): recipient_username = request.POST.get('recipient_username', None) if recipient_username: recipients = User.objects.filter(username=recipient_username) else: recipients = User.objects.all() for recipient in recipients: trucks = Truck.objects.all() for truck in trucks: expired= truck.expire_date if expired==datetime.date.today(): # Notification.objects.create( verb="expired") notify.send( request.user, recipient=truck.user, verb='expiredd' # … -
Django - Deploying using Apache on a Windows server
I installed Apache on my windows server. I have a Flask application that I deployed using it and it works. However, I'm trying to deploy my Django app and nothing is working. WSGI.py import os import sys from django.core.wsgi import get_wsgi_application os.environ["DJANGO_SETTINGS_MODULE"] = "Project.settings" os.environ.setdefault("DJANGO_CONFIGURATIONS", "settings") sys.path.append("C:/Apache24/htdocs/Project") application = get_wsgi_application() settings.py DEBUG = False ALLOWED_HOSTS = [ "*" ] Virtual Host on Apache conf file: <VirtualHost *> ServerName ptylspol ErrorLog "C:\Apache24\logs\project_error.log" WSGIScriptAlias /Project C:\Apache24\htdocs\Project\Project\wsgi.py <Directory C:\Apache24\htdocs\Project> <Files wsgi.py> Require all granted </Files> </Directory> I haven't changed anything else. I don't know what else to do. Can someone give me any ideas or guidance? Thanks! -
is there any opensource support for build social network website with django >=2.0 and python3
I am new to Django and learning to develop social network web apps but I want to use django >= 2.0. I found 1.Vataxia 2.bootcamp 3. pinax but still no one support 100% django >= 2.0 and python3 -
Django populate from from model
Django 2.0.2 Python 3.6.3 Hi, I am still trying to learn Python by jumping head first into a django project. I have a "profile" model that extends the "user" model. I have a ModelForm for the profile. I have a create action that creates a new profile and saves it and the user info. That all works. I am trying to add the other CRUD actions and am starting with an "edit" method. I have read the "Creating forms from models" django doc. I see their idiom of (copied form the link above): >>> class ArticleForm(ModelForm): ... class Meta: ... model = Article ... fields = ['pub_date', 'headline', 'content', 'reporter'] # Creating a form to add an article. >>> form = ArticleForm() # Creating a form to change an existing article. >>> article = Article.objects.get(pk=1) >>> form = ArticleForm(instance=article) In my code I am trying: 1 def edit(request, pk): 2 try: 3 profile = Profile.objects.get(pk=pk) 4 5 if request.method == 'POST': 6 form = ProfileForm(request.POST, instance=profile) 7 else: 8 form = ProfileForm(instance=profile) 9 10 if form.is_valid(): 11 profile = form.save(commit=False) 12 profile.user = request.user 13 profile.save() 14 my_render = render(request, 'Members/index.html', { 15 'profile': profile 16 }) 17 else: 18 … -
Module Not FoundError Python Django
I am trying to map the base URL to my "Learning Logs's" home page. here is the following code I have in my main urls.py file: from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path(r' ', include('learning_logs.urls', namespace='learning_logs')), ] I save the file and look at the terminal to see if there are any issues and it spits out the following error: ModuleNotFoundError: No module named 'learning_logs.urls' I am no to python/django and following a book called the python crash course. not sure what I am doing wrong please help! -
Django Docker/Kubernetes Postgres data not appearing
I just tried switching from docker-compose to docker stacks/kubernetes. In compose I was able to specify where the postgres data volume was and the data persisted nicely. volumes: - ./postgres-data:/var/lib/postgresql/data I tried doing the same thing with the stack file and I can connect to the pod and use psql to see the schema but none of the data entered from docker-compose is there. Any ideas why this might be? Here's the stack.yml version: '3.3' services: django: image: image build: context: . dockerfile: docker/Dockerfile deploy: replicas: 5 environment: - DJANGO_SETTINGS_MODULE=config.settings.local - SECRET_KEY=password - NAME=postgres - USER=postgres - HOST=db - PASSWORD=password - PORT=5432 volumes: - .:/application command: ["gunicorn", "--bind 0.0.0.0:8000", "config.wsgi"] ports: - "8000:8000" links: - db db: image: mdillon/postgis:9.6-alpine volumes: - ./postgres-data:/var/lib/postgresql/data -
dict contains fields not in fieldnames
this is my function to make a csv file of a queryset def esport_to_csv(self, tweets): with open('tweets.csv', 'w') as new_file: fieldnames = ["tweet_id", "text" , "user_screen_name", "user_name", "user_verified", "created_at", "user_time_zone", "user_location", "favorite_count", "retweet_count", "user_followers_count", "user_friends_count"] csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='\t') csv_writer.writeheader() for tweet in tweets: line = [] line.append(tweet["tweet_id"]) line.append(tweet["text"]) line.append(tweet["user_screen_name"]) line.append(tweet["user_name"]) line.append(tweet["user_verified"]) line.append(tweet["created_at"]) line.append(tweet["user_time_zone"]) line.append(tweet["user_location"]) line.append(tweet["favorite_count"]) line.append(tweet["retweet_count"]) line.append(tweet["user_followers_count"]) line.append(tweet["user_friends_count"]) csv_writer.writerow(line) this is my server response ValueError: dict contains fields not in fieldnames: 967563194582515712, 'RT @KEEMSTAR: When you have your fathers car &amp; you tell everyone on the internet that your 15 year old ass bought it. t.co/bUhhrPw0…', 'TKBrotherTK', 'Team Kalvin🌏', False, '2018-02-25T06:23:36+05:30', 'Melbourne', 'Australia', 0, 0, None, None i have seen a solution online but i dont know how to apply it over here -
Dynamic search form using javascript for Django project
I am trying to create a search form using jquery for Django using following tasks to do: A user can upload file or input text into the text area or select option from the drop-down menu but these options will appear based on the selection of 1st drop-down menu. The user can clone this form number of times but not more than max options of 1st drop-down menu. The user can remove form < max options of the 1st drop-down menu. Once submit button will be pressed, it will check form validity then send information to Django. But problems are: Task 1 is working only on 1st form but not in cloned one. My Django views only get information about textarea and selected option but not the content of uploaded file which shows nothing in a file. views.py def fileupload(request): if request.method: print "Hello" try: print request.GET['cityname'] except MultiValueDictKeyError: pass try: print request.GET['listofcompany'] file = request.FILES['foofile'].read() print file except MultiValueDictKeyError: pass try: print request.GET['runprogram'] except MultiValueDictKeyError: pass var max_fields = 3; //maximum input boxes allowed var wrapper = $(".input_fields_wrap"); //Fields wrapper var addButton = $("#form-add"); //Add button ID var form = $('#main-form'); var x = 1; //initlal text box count … -
Django not passing data to the post method
I have been going over a Django tutorial and I have come across an issue where whenever I am trying to post a form to pass data from the webpage to the database it will not go to the method that it is supposed to go to in order for the action to be performed. Here is the code urls.py from django.urls import path, re_path from . import views app_name = 'music' urlpatterns = [ path('', views.index, name='index'), # /music/<album_id>/ re_path('(?P<album_id>[0-9]+)/', views.detail, name='detail'), # /music/<album_id>/favorite/ re_path('(?P<album_id>[0-9]+)/favorite/', views.favorite, name='favorite'), ] details.html <img src="{{ album.album_logo }}"/> <h1>{{ album.album_title }}</h1> <h3>{{ album.artist }}</h3> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'music:favorite' album.id %}" method="post"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ forloop.counter }}" name="song" value="song.id"/> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="https://i.imgur.com/b9b13Rd.png"/> {% endif %} </label><br> {% endfor %} <input type="submit" value="Favorite"> </form> views.py from django.shortcuts import render, get_object_or_404 from django.http import Http404 from .models import Album, Song import pdb; def index(request): all_albums = Album.objects.all() return render(request, 'music/index.html', { 'all_albums': all_albums }) def detail(request, album_id): album = get_object_or_404(Album, pk=album_id) return render(request, 'music/detail.html', {'album': album}) def favorite(request, … -
Django concurrent write issue within transaction.atomic()
class ChampionStats(models.Model): champ_id = models.IntegerField(primary_key=True) total_games = models.IntegerField(default=0) with transaction.atomic(): champ_stats, created = ChampionStats.objects.select_for_update().get_or_create(champ_id=champ_id) champ_stats.total_games += 1 champ_stats.save() I have multiple celery tasks running concurrently on the code above and sometimes occasionally I have multiple objects being returned. api.models.MultipleObjectsReturned: get() returned more than one ChampionStats -- it returned 2! To my understanding if I am running get_or_create in an atomic context then one task will create the table and set a lock on it, throwing an integrity error on all further creates on the same row, thus calling get() instead. -
can't locate what's causing RemovedInDjango110Warning
I got this in my log, after upgrading python from 2.7 to 3.5, there is no full stack trace, I'm not sure how to fix this. /root/.virtualenvs/python3/lib/python3.5/site-packages/django/template/loader.py:97: RemovedInDjango110Warning: render() must be called with a dict, not a RequestContext. return template.render(context, request) 2018-02-24 21:53:07,452 - WARNING - django - /root/.virtualenvs/python3/lib/python3.5/site-packages/django/template/loader.py:97: RemovedInDjango110Warning: render() must be called with a dict, not a RequestContext. return template.render(context, request) I did grep -rl --include \*.py 'Context(', shows nothing, without limiting on only python files, it will give me a bunch of JavaScript files (React). -
heroku myapp.herokuapp.com/admin/ showing Server Error (500)
the url https://myapp.herokuapp.com working fine but the url https://myapp.herokuapp.com/admin/ showing Server Error (500) i already created superuser and migrate it. why it showing error any idea. -
unused import statement in pycharm
I have a file called views.py, and in it there is this line: from django.shortcuts import render, which is marked as an unused import statement. I've ooked around and found the shortcuts.py file, but for some reason pycharm still marks my import statement as unused. How do I fix this? -
MultiValueDictKeyError with radio button in django
i keep on getting this error MultiValueDictKeyError at /show "'colors'" Request Method: POST Request URL: http://localhost:8000/show Django Version: 1.10 Exception Type: MultiValueDictKeyError Exception Value: "'colors'" **my Views.py** from django.shortcuts import render, HttpResponse, redirect def index(request): # change = { # change['texts']: request.session['text'], # change['reds']: request.session['red'], # change['blues']: request.session['blue'], # change['greens']: request.session['green'], # } # if request.session not in change: # request.session=request.session['lols'] return render(request,'buttons_app/index.html')#,change) def show(request): request.session['texts']= request.POST['text'], request.session['reds']= request.POST['colors'], return redirect("/") **my urls.py** from django.conf.urls import url from . import views urlpatterns=[ url(r'^$', views.index), url(r'^show',views.show), ] **my html** <body> <form action="/show" method="POST"> {% csrf_token %} Input text: <input type="text" name="text"> Red: <input type="radio" name="colors" value="red"> Blue: <input type="radio" name="colors" value="blue"> Green: <input type="radio" name="colors" value="green"> Big Font:<input type="checkbox" name="checkbox" value="bigfont"> submit :<input type="submit" name="submit" value="change the text"> </form> i cant get my request.POST to grab the radio button click. i even tried to open the dictionary of the radio button with request.POST['name:red'] im confused on how im suppose to grab the radio button and store it in another dictionary that has session so i later display the dictionary. I know that if i have a radio button it becomes a dictionary that is either the value or the name itself … -
Error adding more fields with django-autocomplete-light
I have a problem and I am using 2 libraries : django-autocomplete-light and django-dynamic-formset. The 2 are very good at doing their job. The first is used to do autocomplete and the second to make django formsets are dynamic. but when you want to join these 2 a problem occurs. Image of the problem when a new field is created, it is added in that way. Template: {% extends 'base/base.html' %} {% load static %} {% block titulo%} Registrar venta {%endblock%} {% block contenido %} <div class="col-md-12"> <form method="post">{% csrf_token %} <div class="col-md-4 form-group"> <label class="font-weight-bold" for="{{form.cliente.name}}">{{form.cliente.label}}</label> {{form.cliente}} </div> <h4 class="text-left">Detalle de venta: </h4> <div class="table-responsive-sm"> <table class="table" id="tablaDetalle"> {{ detalleformset.management_form }} <thead class="thead-dark"> <th>Producto</th> <th width="100px">Cantidad</th> <th width="115px">Prec.Unit.</th> <th width="115px">Subtotal</th> <th>Acción</th> </thead> <tbody> {% for form in detalleformset.forms %} <tr class="formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> <div class="row justify-content-md-end"> <div class="col-md-2"> <label class="font-weight-bold" for="{{form.total.name}}">{{form.total.label}}</label> {{form.total}} </div> </div> <div class="form-group"> <label class="font-weight-bold" for="{{form.descripcion.name}}">{{form.descripcion.label}}</label> … -
Download image by API
I always use request.get method, but now need to upload image on hosting by the api. I get this error: TypeError: must be str, not InMemoryUploadedFile. Im understand, what arises this error. How do upload an image in the code? data = request.FILES['avatar'] api = 'http://uploads.ru/api?upload=' + data upload_image = requests.post(api) respons = upload_image -
Updating model instance dynamically with django
I am stuck in this, i have this api that is made initially by a POST method then a PATHCH method gives it some previously nulled fields and closes this particular session. So far so good but the thing is that the poster and patcher of the API is a electronic device that given some particular circumstances fails to send the PATCH or POST as well, the thing is that there is not possible to be more than one session opened for any given instance, so what i need is when there comes a POST and the PATCH has not closed the current opened session the big idea is to force the update method for that instance and give the fields (nulled ones) the values of the POST that is trying to create a new session. Hope i 've had made myself clear. Here the code class MyModel(models.Model): session_initial_timestamp = models.DatetimeField() some_field = models.ForeignKey(SomeModel) field1_initial = models.IntegerField() field1_final = models.IntegerField() session_final_timestamp = models.DateTimeField()" So as i explained before the POST method gives the initial timestamp and field1_initial and of course the related field. The PATCH gives the final timestamp and final1_field. Thanks in Advance. -
Django models class relationships
In django models, I have 2 classes; Countries and Continents. Each country is linked to Continent with foreign key. class Continent(models.Model): countries = [get countries that are linked to this continent here] class Country(models.Model): continent = models.ForeignKey(Continent) How can I get the linked countries in the countries attribute? In shell I can get the countries using Country.objects.get() But it seems i cannot use class name Country in the attribute of another class. -
Cannot GET data via Django + ReactJS framework
I'm learning Django + ReactJS and I'm having trouble getting data from my Django model. I'm following step by step in this tutorial: http://geezhawk.github.io/using-react-with-django-rest-framework However, when I check the console in firefox I get the "Request failed with status code 500" message. The Django+React integration works fine, but for some reason it won't get the data. Any thoughts? The code in the site is as follows: Model: from django.db import models class Book(models.Model): title = models.CharField(max_length=200, unique=True) author = models.CharField(max_length=100) Serializer: from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title', 'author') views.py from rest_framework import generics from .models import Book from .serializers import BookSerializer class BookList(generics.ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializer index.html {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <title>Hello React</title> </head> <body> <div id="container"></div> {% render_bundle 'main' %} </body> </html> index.js var React = require('react') var ReactDOM = require('react-dom') var BooksList = React.createClass({ loadBooksFromServer: function(){ axios.get(this.props.url) .then(function (data) { this.setState({data: data}); }.bind(this) ) .catch(function (error) { console.log(error); }); }, getInitialState: function() { return {data: []}; }, componentDidMount: function() { this.loadBooksFromServer(); setInterval(this.loadBooksFromServer, this.props.pollInterval) }, render: function() { if (this.state.data) { console.log('DATA!') var bookNodes = this.state.data.map(function(book){ return <li> … -
serialize data to ArrayField(models.IntegerField(),default=list) field
I have the following field in postgres database :ArrayField(models.IntegerField(),default=list). When I send data from post request I get the following error: invalid literal for int() with base 10: '[176,68]' while the data sent is price:[176,68] Here is my serializer for price : class StringArrayField(ListField): """ String representation of an array field. """ def to_representation(self, obj): obj = super().to_representation( obj) # convert list to string return ",".join([(element) for element in obj]) def to_internal_value(self, data): return super().to_internal_value( data) class MySerializer(serializers.ModelSerializer): price = StringArrayField() class Meta: model = myModel fields =('price')