Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Test API Output
I want to test the output of some API urls. Currently my code tests the status_codes of these API urls. class TestApiStatusCode(TestCase): client = Client() def test_urls(self): response = self.client.get('/api/total-fund-aum') self.assertEqual(response.status_code,200) But how can I get the output of the api urls? -
Vue and Django Development Environment
I just started a new little project for learning purposes and I want to try out Vue js with Django (with DRF). I'm trying to use vue loader (webpack-simple template). The problem is that I don't know how to synchronize npm run dev and python manage.py runserver. I don't know how to access a template that is rendered by django in webpack-dev-server. I mean I have a template with django-template specific keywords like {% load static %} that is not handled by webpack-dev-server, obviously. I know I can build it everytime npm run build, but that's kinda annoying and boring to wait for it everytime I want to make a little change. In webpack, it's specified to run on a default index.html file, how can I make it work on the template that is actually rendered in 127.0.0.1:8000 with python manage.py runserver running? Is there an alternative? Thanks in advance for answers! -
RuntimeError: Model class __main__.category doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
i have seen many questions regarding this error but still i cant solve this error i have created an app called website and configured model.py import os import sys from django.db import models if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tango.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) class category(models.Model): name=models.CharField(max_length =128,unique=True) def __str__(self): return self.name class page(models.Model): category=models.ForiegnKey(category) title= models.CharField(max_length=128) url=models.URLField() views=models.IntegerField(default=0) def __str__(self): return self.title this is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ] and when i tried to run the command python manage.py migrate iam getting an error Traceback (most recent call last): File "manage.py", line 24, in <module> class category(models.Model): File "C:\Users\madhumani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class __main__.category doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. please … -
DRF Serializer handling generated field
I have a Django model that has two required fields - name and a slug. The slug could be passed in during the POST request or otherwise can be generated from name. I then have a model Serializer with both slug and name fields. If the slug is not passed in it throws an error that slug is a required field. However, I want to make it so that if slug is not passed in, I generate it from the name that is always passed in. Is there a way to do this gracefully in Serializer? -
How to set image from models in css django 1.11.x?
I try insert a image previously registred by user in css file. My model class Basics(models.Model): ... logo = models.ImageField('Logo') ... My context_processors # -*- conding:utf-8 -*- from .models import Basics def general(request): try: sitebasics = Basics.objects.get(pk=1) except: sitebasics = False context = { 'sitebasics': sitebasics, } return context My css file {% load thumbnail %} ... .header-full-title { float: left; overflow: hidden; padding-left: 75px; background-image: url("{{ sitebasics.logo|thumbnail_url:'logo_large' }}"); background-repeat: no-repeat; background-position: left center; } And the output inspecting the HTML is: .header-full-title { float: left; overflow: hidden; padding-left: 75px; background-image: url({{ sitebasics.logomarca|thumbnail_url:'logo_large' }}); background-repeat: no-repeat; background-position: left center; So when render it don't put the path of image, puts {{ sitebasics.logomarca|thumbnail_url:'logo_large' }} raw text from css. How I did to load a image in css file when render HTML? -
Django-datatable-view throwing error after decorating url
I am using django-datable-view for rendering data from django models. Everything works fine before decorating the url, after i added login_required to the url, it threw weird error. According to the doc, it states that i can add login_required to the url. Below is my code from django_datatables_view.base_datatable_view import BaseDatatableView class OrderListJson(BaseDatatableView): # The model we're going to show model = MyModel # define the columns that will be returned columns = ['number', 'user', 'state', 'created', 'modified'] # define column names that will be used in sorting # order is important and should be same as order of columns # displayed by datatables. For non sortable columns use empty # value like '' order_columns = ['number', 'user', 'state', '', ''] # set max limit of records returned, this is used to protect our site if someone tries to attack our site # and make it return huge amount of data max_display_length = 500 def render_column(self, row, column): # We want to render user as a custom column if column == 'user': return '{0} {1}'.format(row.customer_firstname, row.customer_lastname) else: return super(OrderListJson, self).render_column(row, column) def filter_queryset(self, qs): # use parameters passed in GET request to filter queryset # simple example: search = self.request.GET.get(u'search[value]', None) … -
How to create django model for PostGIS enabled postgres with PK ogc_fid?
I'm reposting this from DBA Stack Exchange, just in case someone can help me here since I only got 7 views there (knowing that includes me). 1.) What is the difference between ogc_fid and fid? I figured that ogc_fid is the default pk created by ogr2ogr to PostGIS. So I thought that it would normally function as an fid would once queried as an object. I copied this in Django Model as : ogc_fid = models.AutoField(primary_key = True) I applied makemigrations and this presents the error : You are trying to add a non-nullable field 'ogc_fid' to route without a default; we can't do that (the database needs something to populate existing rows). To resolve this, I deleted the line ogc_fid = models.AutoField(primary_key = True) from the Django Model and it passed the makemigrations and migrate part. 2.) Querying the objects in Postgres/PostGIS I started testing the objects by querying it in Django Views: routes = Route.objects.all() print(routes) A programming error would occur: column network_route.id does not exist Seems to make sense since my table indeed doesn't have the id field but instead the ogc_fid field that I deleted from the Django Model, which again I assumed that it will … -
How to use django-phonenumber_field in forms.py?
I was trying to take phone number from user as part of his profile updating. I recently found out from stackoverflow that there's a library django-phonenumber_field with which I can easily take input the phone number. So I used it in the model.py like this phone = PhoneNumberField(blank=True). As it is mentioned in the django-phonenumber_field github repository here that As with CharField's, it is discouraged to use null=True. So I didn't use that too. Then I tried to use that phone field in forms.py. Initially I was using this before came to know about phone field: phone = forms.IntegerField(widget=forms.TextInput(attrs={'class': 'form-control'}), required=True) When I am changing it to phone = PhoneNumberField() and I'm migrating, it raised field error. . I coudln't find any forms.PhoneNumberField(). So when I'm keeping the field to be the Integerfield and running the server, I tried to get the input from user I get this error: NOT NULL constraint failed: auth_profile.phone Then I changed phone = PhoneNumberField(blank=True) to phone = PhoneNumberField(null=True, blank=True). which is discouraged. After that, though I didn't get any error but it doesn't matter what user type in the phone-field it always sets null in the database. Probably because I used Integerfield I kept … -
Django UpdateView not saving whether new user or existing user using ModelForm
I am writing an UpdateView UpdateAccountView for the User model, updating through a ModelForm MyUserCreationForm which is already the ModelForm used for creating new users. The problem is that whenever I click Submit to save the changes in the template, it rerenders the template. For instance, if I didn't change any fields, it gives me error of "Username is already taken" which I will show you in the MyUserCreationForm to check for unique usernames, or just rerenders the template for new entries on the fields, without actually saving any changes to the model. Here is my MyUserCreationForm class MyUserCreationForm(UserCreationForm): class Meta: model = User #extended from auth.models.User fields = ("first_name", "last_name", "username", "email", "gender", "profile_photo") # some other code to style the ModelForm template def clean_username(self): username = self.cleaned_data['username'] if not re.search(r'^[\w.-]+$', username): raise forms.ValidationError('Username can only contain alphanumeric characters, dots, hyphens ,and underscores') try: User.objects.get(username=username) except ObjectDoesNotExist: return username raise forms.ValidationError('Username is already taken.') and here is the view class UpdateAccountView class UpdateAccountView(UpdateView): form_class = MyUserCreationForm model = User template_name = 'auth/account-edit.html' success_url = '/' def get_object(self, queryset=None): return self.request.user However, if I directly update the Model by using model and fields in the UpdateView, it works fine. But … -
Django Allow user to change its picture
i made a edit user page that user can change the model (with onetonefield) everything works, but ImageField doesnt work whenever i click submit after i put some files on imagefield , user's imagefield is still empty i cant understand why this is happening because other fields are okay with it here's my code models.py def user_path(instance, filename): from random import choice arr =[choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') for _ in range(8)] pid = ''.join(arr) extension = filename.split('.')[-1] return 'hs/%s/%s.%s' % (instance.owner.username, pid, extension) views.py def edit_profile(request): content = {} profile = request.user.get_username() if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user.userprofile) form2 = EditUserForm (request.POST, instance=request.user) content['form'] = form content['form2'] = form2 if form.is_valid() and form2.is_valid(): new_user = form.save() new_user2 = form2.save() return redirect('/moc/change-profile') else: if form.is_valid() and form2.is_valid(): content['form.errors'] = form.errors content['form2.errors'] = form2.errors messages.warning(request, 'wrong') return redirect('/moc/profile/edit/') else: form = EditProfileForm(instance=request.user) form2 = EditUserForm(instance=request.user) content['form']= form content['form2'] = form2 return render(request, 'moc/editprofile.html', content) forms.py class EditProfileForm(forms.ModelForm): class Meta: model = userProfile fields = ('nick','profileimage',) def __init__(self, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') class EditUserForm(forms.ModelForm): class Meta: model = User fields = ('email',) def __init__(self, *args, **kwargs): super(EditUserForm, self).__init__(*args, **kwargs) f = … -
Django Template not loading variables from views
I created a template in Django, and initialized a very simple HTML code just to test it out with some variables loaded from the views.py file. The HTML file is loaded, but the variables are not. The weird thing is that when I inspect the elements I see this: enter image description here Here are my codes: views.py: from django.http import HttpResponse from django.template import loader from .models import Structure def index(request): all_structures = Structure.objects.all() template = loader.get_template('Structures/index.html') context = { 'all_structures': all_structures, } return HttpResponse(template.render(context, request)) def detail(request, structure_id): return HttpResponse("<h2>Details for Structure id " + str(structure_id) + "</h2>") index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <ul> {% for structure in all_structures %} <li><a href="/structures/{{ structures.id }}/">{{ structures.name }}</a></li> {% endfor %} </ul> </body> </html> -
Django: Can't pre-select from option menu Upon POST
This has been taking over 7 hours with no success. By now I have no idea why. I have two forms, this screenshot should give a pretty good indication of the flow I'm looking for. So basically, a user either selects one of the existing items from the dropdown menu of BottleForm (marked in the screenshot as "1"), or he elects to click the Add button, which opens a modal of another form BrandForm (marked in the screenshot as "2"), which should let him fill a new brand name. What I want is that when a new brand-name is submitted in the BrandForm and the page is reloaded, that brand is already pre-selected in the dropdown menu. I've read countless of threads but none of the suggested answers regarding setting initial on the field work. Why is it not working? views.py (add_brand is the submit name for the BrandForm): elif 'add_brand' in request.POST: context['form2'] = BrandForm(request.POST) context['form'] = BottleForm(initial={'brand': 'name'}) the_biz = Business.objects.filter(owner=user.id).first() if context['form2'].is_valid(): print("brand for valid!") brand = context['form2'].save(commit=False) brand.business = the_biz brand.save() return render(request, template_name="index.pug", context=context) bottle_form.pug: //- Create New Brand Modal div.modal.fade.create-new-brand(tabindex="-1" role="dialog") div.modal-dialog.modal-sm(role="document") div.modal-content div.modal-header H3 Enter the Brand's name here: div.modal-body form.form-horizontal(method="post" action=".") | … -
Python: Why 2 calls of the same function don't run in parallel?
I'm trying to call the same function with different parameters in parallel using multiprocessing module. Here is example of my code: from django.apps import AppConfig class CurrencyRatesConfig(AppConfig): name = 'currency_rates' def ready(self): import time from multiprocessing import Process import currency_rates.ws_get_rates p1 = Process(currency_rates.ws_get_rates.get_rates('1m', 'tBTCUSD', 'BTC2USD')) p1.start() p2 = Process(currency_rates.ws_get_rates.get_rates('1m', 'tIOTUSD', 'IOT2USD')) p2.start() p1.join() p2.join() But it doesn't work. I see just p1's execution result. Could somebody describe what is wrong? Thanks. -
Unable to save to database from Django ModelForm
There are no errors but the form doesn't save to database. Otherwise, its possible to add data from django admin. The urls and redirects also work well, i can be able to open the form, edit/put data and hit submit, but the database does not reflect. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class RPAS(models.Model): user = models.OneToOneField(User) manufacturer = models.CharField(max_length = 100, default = '') model_name = models.CharField(max_length = 100, default = '') serial_no = models.CharField(max_length = 50, default='') reg_mark = models.CharField(max_length = 50, default='') def __str__(self): return self.user.rpas.manufacturer # RPAS.profile = property(lambda u: RPAS.objects.get_or_create(user=u)[0]) def edit_rpas_profile(sender, **kwargs): if kwargs['created']: user_profile = RPAS(user=kwargs['instance']) post_save.connect(edit_rpas_profile, sender=User) views.py from .forms import RPASForm from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied def edit_rpas(request): if request.user.is_authenticated(): if request.method == "POST": form = RPASForm(request.POST,instance=request.user) if form.is_valid(): form.save(commit=False) return redirect ('/account/rpas/') else: form = RPASForm(instance=request.user) args = {'form': form} return render(request, "accounts/edit_rpas.html", args) else: raise PermissionDenied forms.py from django import forms from django.contrib.auth.models import User from django.forms import ModelForm from accounts.models import RPAS class RPASForm(ModelForm): class Meta: model = RPAS fields = ( 'manufacturer', 'model_name', 'serial_no' ) template <form action="." method="POST" class="padding"> {% csrf_token %} {{ form.as_p }} <input … -
Include function not rendering properly
I have a simple question I guess, I am using the include function in order to insert an HTML into another HTML page the problem is that my URL does not work anymore in that configuration ; HTML : {% extends 'base.html' %} {% load staticfiles %} {% block body %} <div class="container"> <div class="jumbotron"> <h3>Welcome to your Employee panel</h3> <h4>You can start your survey right away</h4> </div> </div> {% include "survey/list.html" %} {% endblock %} HTML to include: {% load i18n %} {% block body %} <div id="intro" class="container-fluid"> <div class="jumbotron"> <h3>{% trans "Welcome to the Django Survey app"%}</h3> </div> <div class="col-md-offset-1"> <div class="content"> <h4>You've have one survey that is waiting for you</h4> </div> <div class="survey-listing"> <ul> {% for survey in surveys %} <li><a href="{{ survey.get_absolute_url }}">{% trans "Take the Survey"%} {{survey.name}}</a></li> {% endfor %} </ul> </div> </div> </div> {% endblock %} When including the survey list is not rendering ;( -
python script run by cron not logging output
I have a python script that is scheduled to run by cron. I can see the cron job is running this script when looking in the syslog grep CRON /var/log/syslog. But then when I open the file am logging the output I don't see any entries. Crontab: */1 * * * * root run-one $PY $RASROOT/manage.py runscript listen_for_updates >> /var/log/updates.log 2>&1 python script: def run(): while True: print('Waiting for updates...') Note: on running the script manually on the server it is logging, and I see output in the file. -
2 models in 1 view and 1 template in Django?
So i have 2 models, class Post(models.Model): topic = models.CharField(max_length=200) description = models.TextField() created_by = models.ForeignKey(User, related_name='posts') created_on = models.DateTimeField() def __str__(self): return self.topic class Comment(models.Model): commented_by = models.ForeignKey(User, related_name='comments') commented_on = models.ForeignKey(Post, related_name='comments') commented_text = models.CharField(max_length=500) commented_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.commented_text and i want to display post and comment on single template. So, i created this view: def post_desc(request, pk): post = get_object_or_404(Post, pk=pk) comment_list = Comment.objects.all() return render(request, 'post_desc.html', {'post': post, 'comment_list':comment_list}) and try to display them in template: {% if post.created_on %} {{ post.created_on }} {% endif %} <h1>{{ post.topic }}</h1> <p>{{ post.description }}</p> <h4>Comments</h4> {% if comment_list.commented_on == post.topic %} {{ comment_list.commented_by }}{{ comment_list.commented_text }} {% endif %} But it is only displaying post and not comment section. What i did wrong here? -
Abort older request when newer one comes
My question may sound a bit strange, but what I want to do is to stop computing some response for the current request (the endpoint I have is quite "heavy" and takes a couple of seconds to finish) as soon as the user sends another updated request to the same endpoint. For example, the user may play with filtering checkboxes, so I am always interested in the most recent request (previous ones can be safely aborted). Is this behavior possible to implement in Django? Thanks. -
firstof usage with list variables
I have seen that list data types do not hold their structure after using firstof with as. For example: {% firstof some_list some_string as value %} If some_list is a valid list above, it gets assigned to value. But if I do something like {% if pk in value %}, it fails, even when it succeeds with {% if pk in some_list %}. When I print both of them: {{some_list}} {{value}} they give the same output but I think list is probably not stored as list after using firstof with as. Thoughts? -
Django get city, country using latitude and longitude
I am using django-cities and geopy. I am trying to get city name, id and country name, id based on given latitude and longitude. Normally this is how you can get city and country using geopy. from geopy.geocoders import Nominatim geolocator = Nominatim(timeout=3) geolocator.reverse('52.5094982,13.3765983') loc = location.raw loc_dict = location.raw print(loc_dict['address']) and this is the output: {'suburb': 'Tiergarten', 'country_code': 'de', 'country': 'Deutschland', 'postcode': '10117', 'attraction': 'Potsdamer Platz', 'road': 'Potsdamer Platz', 'city': 'Berlin', 'city_district': 'Mitte', 'state': 'Berlin'} In django this is how i'm trying to get them: This is where i'm adding the coordinates. urls.py url(r'^(?P<page_slug>(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?))/$', views.Coordinates.as_view(), name='coordinates') views.py class Coordinates(APIView): def get_object(self): geolocator = Nominatim(timeout=3) location = geolocator.reverse(self.kwargs['page_slug']) loc_dict = location.raw return loc_dict def get(self, request, page_slug): data = dict() loc_dict = self.get_object() data['country'] = loc_dict['address']['country'] if 'city' in loc_dict['address']: data['city'] = loc_dict['address']['city'] data['city_id'] = City.objects.get(name=loc_dict['address']['city']).id elif 'state' in loc_dict['address']: data['city'] = loc_dict['address']['state'] data['city_id'] = City.objects.get(name=loc_dict['address']['state']).id else: data['city'] = None data['country_id'] = Country.objects.get(name=loc_dict['address']['country']).id return Response(data) This should be the output: {"city":"Berlin", "city_id":"2" ,"country":"Deutschland", "country_id":"3"} Normally it should work, my problem is that geopy returns country: Deutschland whereas in django-cities it's Germany. And this happens to cities aswell, geopy gives me București and django-cities Bucharest. How can i get city name … -
Django UnboundLocalError at /x/ when surfing to localhost:8000/x
I am new to Django, I just created a model with few classes, and created views and urls and everything works just fine up until I try to extract the id of an object to use it in the url. Here are my codes: urls.py: from django.conf.urls import url from . import views urlpatterns = [ # / structures/ url(r'^$', views.index, name='index'), # / structures/712 url(r'^(?P<structure_id>[0-9]+)/$', views.detail, name='detail'), ] views.py: from django.http import HttpResponse from .models import Structure def index(request): all_structures = Structure.objects.all() html = '' for Structure in all_structures: url = '/structures/' + str(Structure.id) + '/' html += '<a href="' + url + '">' + Structure.name + '</a><br>' return HttpResponse(html) def detail(request, structure_id): return HttpResponse("<h2>Details for Structure id " + str(structure_id) + "</h2>") models.py: from django.db import models class Structure(models.Model): name = models.CharField(max_length=120) path = models.CharField(max_length=200) def __str__(self): return self.name class Type(models.Model): typename = models.CharField(max_length=50) def __str__(self): return self.typename class Record(models.Model): structure = models.ForeignKey(Structure, on_delete=models.CASCADE) #each structure has many records, each per line name = models.CharField(max_length=200) type = models.ForeignKey(Type) pos = models.IntegerField() long = models.IntegerField() def __str__(self): return self.name And here is the error I a having: I am not seeing any wrong referencing or any issue with my … -
python-social-auth Facebook and LinkedIn user's email is empty
I am developing a Django web app using python-social-auth. I have this in my Django settings: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xxx' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xxx' SOCIAL_AUTH_FACEBOOK_KEY = 'xxx' SOCIAL_AUTH_FACEBOOK_SECRET = 'xxx' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email',] SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'xxx' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'xxx' SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress'] Now Google sets user's email just fine in auth.user model in database, but LinkedIn and Facebook won't even send the user's email. What do I do? -
Bad performance in Django / Apache
I have written this view that is supposed to be fast and simple, but in reality it takes way too much time and basically hogs my server's CPUs. It's written in django-rest-framework and basically does the following: look up DB object from query parameters update some fields in db object save object find any detail records for the object return json-encoded detail records The view is written as part of APIView.post() handler. Profiling the function itself offers the following: fetch takes 2 - 5 ms update takes 1 ms fetch details takes 3 - 7 ms apache itself reports some 30-40 ms MORE than the profiled function itself (if function reports total time 10ms, apache (access.log) will report some 40ms. The added time seems to be there for all queries. netdata (looking at postgres page) says that all fetches are done from RAM. I have a 2 CPU machine serving the entire app. The 2 CPUs are loaded for the entire Apache-reported time, meaning that average function serving time is 40 ms, I get 100% load at 50 queries per second. Obviously, my target is MUCH more than 50 queries per second. As the core function takes only ~10ms, I … -
load Local infile csv to mysql db fails
I trying to import my csv file into database. but it fails. # -*- coding: utf-8 -*- import MySQLdb class Database: def __init__(self): self.host = 'localhost' self.user = 'root' self.port = 3306 self.password = 'root' self.db = 'test' self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db, self.port, local_infile = 1) self.cursor = self.connection.cursor() def insert_csv_test(self): query = "LOAD DATA LOCAL INFILE ‘/Users/ankr/Desktop/output’ INTO TABLE details FIELDS TERMINATED BY ‘,’ LINES TERMINATED BY ‘\n’" self.cursor.execute(query) self.connection.commit() self.connection.close() print("Done") def close_connection(self): self.connection.close() database = Database() database.__init__() database.insert_csv_test() database.close_connection() It fails. Seeing this below. Traceback (most recent call last): File "test.py", line 30, in database.insert_csv_test() File "test.py", line 20, in insert_csv_test self.cursor.execute(query) File "/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.12-intel.egg/MySQLdb/cursors.py", line 202, in execute self.errorhandler(self, exc, value) File "/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.12-intel.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\xe2\x80\x98/Users/ankr/Desktop/output\xe2\x80\x99 INTO TABLE details FIELDS TERMINATED BY \xe2\x80\x98,\xe2\x80\x99 LI' at line 1") Any Help would be appreciated. -
Creating a record with foreign key Django Rest Framework
New to DRF 3.7.1 and I'm hitting a problem trying to create an object containing a foreign key using POST. The scenario is I have a student - school model (one school has many students) - example below: class School(models.Model): school_id = models.CharField(primary_key=True,max_length=10) school_name = models.CharField(max_length=100) school_address = models.CharField(max_length=255) # other fields omitted class Student(models.Model): student_name = models.CharField(max_length=100) # other fields omitted school = models.ForeignKey('School') The serializer looks like: class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = ('school_id','school_name','school_address') class StudentSerializer(serializers.ModelSerializer): school = SchoolSerializer() class Meta: model = Student fields = ('student_name','school') Assuming a school exists (school_id='ABC') I'm trying to post this JSON to create a student: { "student_name": "John Doe", "school_id": "ABC" } but am getting the error: AssertionError at /mytest/ The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer myapp.serializers.StudentSerializer, or set read_only=True on nested serializer fields. Not sure how to fix this - what should I reference for the school foreign key? Thanks in advance