Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What does a parameter without equal in a django models.Field means?
I was reviewing a django repo in git hub and find this way of fields declaration from django.utils.translation import ugettext_lazy as _ class Usuario(AbstractBaseUser, PermissionsMixin): usuario = models.CharField(_('Usuario'), max_length=60, unique=True) is_staff = models.BooleanField(_('staff status'), default=False) I don't understand for what is the _('Usuario') and _('staff status') parameters. Could someone explain me this? Thanks -
Unable to save django form after added queryset filter in __init__ method
I've filtered a field queryset from my django form and now suddenly in html page when i hit submit it doesn't save anymore but if i comment the method, I can save again. Any help is much appreciated below is my code model : class Model_A(models.Model): project_name = models.CharField(max_length=50, unique=True) project_manager = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='project_manager', null=True, blank=True) def __str__(self): return self.project_name form.py : class EditProjectForm(forms.ModelForm): prefix = 'edit_form' class Meta: model = Model_A fields = '__all__' #Save failed after adding this method def __init__(self, user, *args, **kwargs): super(EditProjectForm, self).__init__(*args, **kwargs) self.fields['project_manager'].queryset = Employee.objects.filter(department__in=[18, 19, 20]).exclude(employment_status=6) view.py : def project_setting(request, project_id): form = EditProjectForm(request.POST or None, request.FILES or None, instance=selected_project, prefix='settings') if form.is_valid(): inst = form.save(commit=False) inst.save() form.save_m2m() return HttpResponseRedirect('/projects/{}/setting'.format(project_id)) context = { 'form': form, } return render(request, '/projects/setting.html', context=context) -
only show the root nodes in django treebeard
I have a category in following form Home Bedroom Office Here Home and Office are only the root node. I wanted to show them in a grid but also the Bedroom is displayed. The code I tried is the following <div class="container"> <div class="row category-header"> {% category_tree depth=2 as tree_categories %} {% if tree_categories %} {% for tree_category, info in tree_categories %} <div class="col-sm-12 col-md-6"> {% if info.has_children %} <li class="dropdown-submenu"> <a tabindex="-1" href=""> <img src="media/{{ tree_category.image }}" class="img-responsive" alt={{ tree_category.name }}> {{ tree_category.name }} </a> <ul class="dropdown-menu"> {% else %} <li> <a tabindex="-1" href=""> <img src="media/{{ tree_category.image }}" class="img-responsive" alt={{ tree_category.name }}> {{ tree_category.name }} </a> </li> {% endif %} {% for close in info.num_to_close %} </ul> </li> {% endfor %} </div> {% endfor %} {% endif %} </div> </div> How do i show only the Home and Office in 2 column? The way i am trying is a hacky -
Return NoneType on queryset django REST framework
Problem : I am getting an error like this : Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/rest_framework/viewsets.py" in view 87. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch 474. response = self.handle_exception(exc) File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in handle_exception 434. self.raise_uncaught_exception(exc) File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch 471. response = handler(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/rest_framework/mixins.py" in list 42. page = self.paginate_queryset(queryset) File "/usr/local/lib/python2.7/dist-packages/rest_framework/generics.py" in paginate_queryset 172. return self.paginator.paginate_queryset(queryset, self.request, view=self) File "/usr/local/lib/python2.7/dist-packages/rest_framework/pagination.py" in paginate_queryset 311. self.count = _get_count(queryset) File "/usr/local/lib/python2.7/dist-packages/rest_framework/pagination.py" in _get_count 54. return len(queryset) Exception Type: TypeError at /api/userprofiles/ Exception Value: object of type 'NoneType' has no len() What I am trying to do : I just want people to get their own profile, when they connect to the api, so instead of applying UserProfile.objects.all , I thought it would be better if I used UserProfile.objects.get(user=request.user). But as you can well see it isn't working, perhaps because pagination has some problem cause it is trying to get len() but the object it's getting is NoneType although I printed the queryset just after it's … -
Trying to query based on choice field django
I've been stuck on this all day. I've got a model, Load, within that model it has a choice field with different "statuses". I am trying to implement some tabbed views in my template. So basically each tab will be responsible for displaying a certain status. I believe that I should be using a queryset within my view get_context_data but I'm just not really understanding how to accomplish this. I've tried a ton of different ways in the view, so i'll just paste the latest attempt. These query's will be static once they are done so my best thought was to use a model managers for each query, but I couldn't get multiple model managers to work on one model. Here's an example of one. Any help would be appreciated. Thank you class BookedManager(models.Manager): def get_queryset(self): return super(BookedManager, self).get_queryset().filter(load_status='Booked') Models.py class Load(models.Model): load_number = models.IntegerField() agent = models.ForeignKey(User, limit_choices_to={'groups__name': 'Agent'},related_name='Agent', on_delete=models.CASCADE, null=True) customer = models.ForeignKey(User, limit_choices_to={'groups__name': 'Customer'},related_name='Customer', on_delete=models.CASCADE) carrier = models.ForeignKey(Carrier, on_delete=models.CASCADE, blank=True, null=True) pickup_date = models.DateField() delivery_date = models.DateField() shipper = models.ForeignKey(Location, related_name='shipper', on_delete=models.CASCADE, blank=True) consignee = models.ForeignKey(Location, related_name='consignee', on_delete=models.CASCADE, blank=True) po_number = models.CharField(max_length=255) pu_number = models.CharField(max_length=255) pieces = models.IntegerField() description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) PREBOOK = 'Waiting … -
Having a django model that can only contain a specified number of rows
I want to create a Django Group model whose members are in a Django Person Model...The Person instance can only occur in a specific number of groups...and a group can only accommodate a specific number of person instances -
How to do Django Database routing for two database in same app?
I am new to django, facing challenge of using two different database in my same App I have done something like this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'projectDb', 'USER': 'piyush', 'PASSWORD': 'piyush@123', 'HOST': 'localhost', 'PORT': '5432', }, 'vendor': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'vendorDb', 'USER': 'piyush', 'PASSWORD': 'piyush@123', 'HOST': 'some_rds_end_point', 'PORT': '5432', } } For both the Database I need read and write access , I have refer DjangoDoc but still confused, how to write DATABASE_ROUTERS for this. Please help me. -
Exception in worker process while running heroku open
I am trying to deploy my django app on heroku, after running git push heroku master , when i do heroku open , it gives Application error. heroku logs command shows : [2018-01-21 05:25:17 +0000] [10] [ERROR] Exception in worker process 2018-01-21T05:25:17.928006+00:00 app[web.1]: Traceback (most recent call last): 2018-01-21T05:25:17.928007+00:00 app[web.1]: File "/app/.heroku/python /lib/python2.7/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2018-01-21T05:25:17.928009+00:00 app[web.1]: worker.init_process() 2018-01-21T05:25:17.928010+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process 2018-01-21T05:25:17.928011+00:00 app[web.1]: self.load_wsgi() 2018-01-21T05:25:17.928012+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2018-01-21T05:25:17.928013+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-01-21T05:25:17.928014+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2018-01-21T05:25:17.928015+00:00 app[web.1]: self.callable = self.load() 2018-01-21T05:25:17.928016+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2018-01-21T05:25:17.928016+00:00 app[web.1]: return self.load_wsgiapp() 2018-01-21T05:25:17.928018+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2018-01-21T05:25:17.928018+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-01-21T05:25:17.928019+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/util.py", line 352, in import_app 2018-01-21T05:25:17.928020+00:00 app[web.1]: __import__(module) 2018-01-21T05:25:17.928021+00:00 app[web.1]: File "/app/mysite/wsgi.py", line 16, in <module> 2018-01-21T05:25:17.928023+00:00 app[web.1]: application = get_wsgi_application() 2018-01-21T05:25:17.928023+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2018-01-21T05:25:17.928024+00:00 app[web.1]: django.setup(set_prefix=False) 2018-01-21T05:25:17.928025+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/__init__.py", line 27, in setup 2018-01-21T05:25:17.928026+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2018-01-21T05:25:17.928027+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate 2018-01-21T05:25:17.928028+00:00 app[web.1]: app_config = AppConfig.create(entry) 2018-01-21T05:25:17.928029+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/apps/config.py", line 94, in create 2018-01-21T05:25:17.928030+00:00 app[web.1]: module = import_module(entry) 2018-01-21T05:25:17.928031+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in … -
supervisord prints logs only when stopped server
so this is what I print in python with flushing: import sys print "getting detailed" sys.stdout.flush() then i check the logs file and it is empty, so then I stop the server: supervisorctl stop my-project and the logs file is filled with messages from the print above, so the question is how to make it print to the log file without stopping the server? -
Django Formset Redirect with pk/id
I'm trying to pass in the parent id of a formset into a view, but it doesn't seem to work for me for some reason. I do this in other apps without issue but this particular one returns "None" as a pk. The only difference being my formset model doesn't usually contain a foreignkey relationship. If I render the parent by itself, I can pass the pk just fine. Please help :) Exception Value: Reverse for 'company-detail' with keyword arguments '{'pk': None}' not found. 1 pattern(s) tried: ['customers/(?P[0-9a-z-]+)/detail/$'] ''' forms.py ''' class CompanyCreateForm(forms.ModelForm): class Meta: model = CompanyModel fields = [ 'name', 'website', 'rate', ] widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': ''}), 'website': forms.URLInput(attrs={ 'class': 'form-control', 'placeholder': ''}), 'rate': forms.NumberInput(attrs={ 'class': 'form-control', 'placeholder': ''}), } SitesFormSet = inlineformset_factory( CompanyModel, SiteModel, fields=('street1', 'street2', 'city', 'state', 'zipcode', 'country', 'phone', 'distance', ), widgets={ 'street1': forms.TextInput(attrs={ 'class': 'form-control' }), 'street2': forms.TextInput(attrs={ 'class': 'form-control' }), 'city': forms.TextInput(attrs={ 'class': 'form-control' }), 'state': forms.TextInput(attrs={ 'class': 'form-control' }), 'zipcode': forms.NumberInput(attrs={ 'class': 'form-control' }), 'country': forms.TextInput(attrs={ 'class': 'form-control' }), 'phone': forms.TextInput(attrs={ 'class': 'form-control' }), 'distance': forms.NumberInput(attrs={ 'class': 'form-control' }) }, extra=1 ) ''' views.py ''' def companycreateview(request): if request.method == 'POST': companyform = CompanyCreateForm(request.POST) if companyform.is_valid(): company … -
django core 'dict' object is not callable
Django 2.0.1 python 3.6.3 Hi I have an address form which is a kind of extended user model form. The form asks for name, birth-date, address and phone info. I do some form validation on the form fields, for example the birth-date entered must be at least 18 years ago. I also overwrite the form's clean method to verify the US address via the USPS address api. After the address info is verified the validated/normalized address values returned from the USPS are put into the cleaned_data dict and are returned. After the cleaned_data return, Django eventually calls _get_response() in django/core/handlers/base.py. There is a section ... if response is None: wrapped_callback = self.make_view_atomic(callback) try: response = wrapped_callback(request, *callback_args, **callback_kwargs) except Exception as e: response = self.process_exception_by_middleware(e, request) that throws the error: TypeError at / 'dict' object is not callable What does that mean in this context? -
Django groups and permissions in API level (with django-rest-framework)
Consider the following scenario; I have a bunch of Users and API classes. I need to restrict access to each API by checking the requested user's group permissions and allow the user to do group permitted stuff. Suppose I have a user user_xx, he belongs to group group_xx and has permissions activity | activity | Can add activity. When user_xx tries to access MyActivityAPI through HTTP-DELETE method the view class should restrict the access.Can do I achieve this feature? If possible, How?What I'd triedCreated some groups & assigned permissions to them and added users to their corresponding groups. I tried to access one of the restricted api, but it allows me to access (expected behaviour : restrict the user from the api). -
Formatting json data in python with djano
I'm having trouble formatting json data and displaying certain fields in python. What I'm looking to do is only display the name and the price on a webpage via djano. I've tried many different way but the only code that works right now is showing all the data not just the name and price. the data is as follows: { "totalCount_str": "10134", "items": [ { "adjustedPrice": 306988.09, "averagePrice": 306292.67, "type": { "id_str": "32772", "href": "https://crest-tq.eveonline.com/inventory/types/32772/", "id": 32772, "name": "Medium Ancillary Shield Booster" } }, { "..." } ], "pageCount": 1, "pageCount_str": "1", "totalCount": 10134 } item.py import requests from bs4 import BeautifulSoup Collects the item price chart page = requests.get('api.eveonline.com/xxxxx') Creates a BS4 object soup = BeautifulSoup(page.text, 'html.parser') item_name = soup.find(name_='') item_price = soup.find(averagePrice='') print(name) print(price) -
Nested and Integrated Crispy Layouts
TLDR Question: How do you make one crispy form with an ¿integrated?(not sure if this is considered inline) layout with multiple models(some related, some not). I am trying to understand several things in Django: forms, formsets, nested forms, and crispy, and I've been at it for a while, and feel I am close, just need someone to help connect the dots. I'm not sure how to accomplish it without crispy, so I started down this path thinking crispy was the solution. Please correct if I am wrong, thanks :) I would like one form (as in HTML form, not necessarily Django Form), that has a primary model with lots of fields, but with secondary/tertiary models in the middle of the primary fields. I am somewhat near the layout, but can't seem to get the secondary/tertiary models to render in the middle of the layout, let alone compile (at the bottom) without crispy/django erroring. Here is what I am trying to attain Files For reference models.py #Black in the picture class Truck(models.Model): name = models.CharField(…) … #Blue in the picture class QuickInspection(models.Model): odometer = models.IntegerField(…) … (created_at, user_cookie#who did it, …) truck = models.ForeignKey(Truck) ----- #These two are unrelated to the … -
I wanna hand over arguments to URL
I wanna hand over arguments to URL.I wrote in urls.py app_name = 'app' urlpatterns = [ url(r'^(?P<id>[0-9a-zA-Z]{10})/user_data$', views.UserViewSet.get_user_data, name='get_user_data'), ] in views.py class UserViewSet(): def get_user_data(request, **id): I wanna make a url is connected registed id & regist_time &group like https://localhost:8000/app/user_data?regist_time=2018-01-01T02:00:00&group=A .I searched Django tutorial but I cannot understand I should write URL or views to connect regist_time &group.I saw news.views.month_archive(request, year='2005', month='03') in url but in my case regist_time &group is changed each user.regist_time &group's data is in **id like ison style.So I do not know how to write it.What should I write it? -
Django 'manage.py test' failing to migrate models to test database
I am having trouble running unit tests with Django. According to the Django docs: https://docs.djangoproject.com/en/2.0/topics/testing/advanced/#using-different-testing-frameworks The default Django testing behavior involves: Performing global pre-test setup. Looking for tests in any file below the current directory whose name matches the pattern test*.py. Creating the test databases. Running migrate to install models and initial data into the test databases. Running the system checks. Running the tests that were found. Destroying the test databases. Performing global post-test teardown. Anytime I try to run ./manage.py test The Django gets as far as step 3, creating the test database, then throws an error django.db.utils.ProgrammingError: relation "accounts_user" does not exist It seems it is failing to migrate my models to the test database. Since it crashes it doesn't remove the test database. I can psql into the database and see that it is empty. This behavior occurs even if I don't have any tests written out. def user_image_path(instance, filename): ''' https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.FileField.upload_to ''' first_name = instance.first_name.lower().replace(" ", "_") last_name = instance.last_name.lower().replace(" ", "_") cleaned_filename = filename.lower().replace(" ", "_") return '{0}_{1}/images/avatar/{2}'.format(first_name, last_name, cleaned_filename) class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, username=None, password=None): if not email: raise ValueError("Users must have a valid email address") if not first_name and last_name: … -
How do I list columns no inherited from base classes?
I have this class: class DataCommonInfoText(models.Model): a_col = model.TextField() def is_data(self): return True class Meta: abstract = True And a class that inherits from it: class MoreData(DataCommonInfoText): another_col = models.IntegerField() I want to list as strings all the columns in MoreData that are not inherited from DataCommonInfoText. How do I do this? -
Django Admin - Create an object and Create+Add a many other object (ForeignKey)
I have a 'Test'(:a.k.a exam) model that can contain an indeterminate number of questions. I would like to be able to create these tests directly in the Admin part of Django. How should I proceed? Do I have to program the logic from scratch or Django has already thought about this case? class Question(models.Model): question = models.CharField() answer_a = models.Boolean() solution_a = models.Boolean() ... class Test(models.Model): name = models.CharField() ... class TestQuestion(models.Model): """connect many questions to a test""" test_fk = models.ForeignKey(Test) question_fk = models.ForeignKey(Question) -
manage.py migrate error for python Django
I entered the code: python manage.py migrate with the return being huge and ending with: RecursionError:maximum recursion depth exceeded The start of the large return was: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/etucks/webapps/env/lib/python3.6/site-packages/django/core/managment/__init__.py", line 371, in execute_from_command_line utility.execute() File "\home\etucks\webapps\env\lib\python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/etucks/webapps/env/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) This goes on for awhile until it gets to: File "/home/etucks/webapps/env/lib/python3.6/site-packages/django/urls/resolvers.py", line398, in check warnings.extend(check_resolver(pattern)) File "/home/etucks/webapps/env/lib/python3.6/site-packages/django/core/checks/urls/py", line 23, in check_resolver return check_method() This repeats a huge number of times until: File "/home/etucks/webapps/env/lib/python3.6/site-packages/django/urls/resolvers.py", line 322, in check warnings = self._check_pattern_name() RecursionError: maximum recursion depth exceeded -
Deploying SSL for my Django 2.0.1 server with Apache on Ubuntu 16.04 (droplet)
I’ve played with a little Django (v2.0.1) locally. Now I am trying to implement a test case on my production Apache web server. I’m running an Ubuntu 14.04 DigitalOcean droplet (will upgrade to 18.04 later this year). I got Django running. Here it is: http://www.angeles4four.info:8000/ Before I log into my admin panel, I figure it’s best practices to set up HTTPS first. But when I visit that URL, Chrome throws this message: This site can’t provide a secure connection www.angeles4four.info sent an invalid response. ERR_SSL_PROTOCOL_ERROR And my shell on my server shows this message: [20/Jan/2018 23:54:39] "GET / HTTP/1.1" 200 16559 [21/Jan/2018 00:01:23] code 400, message Bad request syntax ('\x16\x03\x01\x00Ì\x01\x00\x00È\x03\x03&6U\x10µ\x82\x97\x7f´8\x1e«\x0e¿ÿ§\x89æ\x82\r¢G§\x01ç°P%\x80)ÕÃ\x00\x00\x1c * À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [21/Jan/2018 00:01:23] You're accessing the development server over HTTPS, but it only supports HTTP. That’s because SSL isn’t set up. My current SSL Certificate Authority is Let’s Encrypt. SSL is running properly for my public_html content but not for my recent deployment of Django. I found some resources elsewhere on SO for setting up SSL with Django. In an SO post titled, “Configure SSL Certificate on Apache for Django Application (mod_wsgi)”, a highly upvoted answer by Alexey Kuleshevich suggests a template for 000-default.conf and default-ssl.conf for Apache vhosts. … -
How to remove the backslash after add a word"specifics" in the urlpattern from the Django tutorial 03?
django tutorial 03 I follow the tutorail and add the word "specifics" in the urlpattern # added the word 'specifics' path('specifics/<int:question_id>/', views.detail, name='detail'), But after I add it, the url in the index turns to like this : http://127.0.0.1:8000/polls/specifics/1// There are 2 backslash in the end.Why? Is that a bug? How to fix it? -
How to deploy Django without mod_wsgi
I'm relatively new to web development, but I have a couple years experience working with python, so I figured I would build my first production site using django. I've spent the last few days learning the basics and building a test site running on my local machine. Today, I've been trying to deploy my site to production; however, I've hit a pretty large stumbling block. The django documentation suggests using mod_wsgi for apache deployments. I followed the install instructions here, only to realize that I don't have access to make any changes to apache - I'm currently on a shared hosting plan. Apparently, to perform the install, I would have to upgrade to a VPS plan, which costs a lot more. Any advice for a new web developer trying to get a proof-of-concept web app together (preferably with feedback gathered from real users) on a budget? I think I have two options: Eat the cost on my current web hosting plan. Try to find a cheaper host that specializes in django hosting. I've been looking at the following (suggestions here would be wonderful): Heroku DigitalOcean A2Hosting Try some sort of manual deployment. Is this possible or has anybody ever made … -
How to implement SAML based SSO Authentication to my django app.
I am planning to implement SAML based SSO Authentication to my django app. which is the best Identity provider to use and what are the steps to set up. Any help will be appreciated. Thanks. -
Can't figure out how to configure email settings for cookiecutter-django
I've set up a cookiecutter-django project for testing and it worked just fine printing the confirmation email to the console. However, it's important to me to also test the actual sending of the emails and when I tried to adjust the settings for a local testing environment, it gave me a "SMTP AUTH extension not supported by server." error after adding a new account. I changed EMAIL_BACKEND to EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' and added the relevant EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, and EMAIL_HOST_PASSWORD settings in the local.py settings file. I'm using a yahoo account that was set up for this purpose and worked just fine outside of Django. I can't find anything in the cookie-cutter documentation about how to configure this and the Django documentation has been less than helpful. -
Django REST framework, dealing with related fields on creating records
Preliminary note: this is a rather newbie question, though I have not found a sufficient answer on StackOverflow; many similar questions, but not this one. So I am asking a new question. The problem: I'm having difficulty creating records where one field is a foreign key to an existing record, and I do not know what I'm doing wrong in my code. In my app there are two models in question, a one-to-many relationship between Company and BalanceSheet: models: class Company(models.Model): cik = models.IntegerField(default=0, unique=True) symbol = models.CharField(max_length=4, unique=True) name = models.CharField(max_length=255, unique=True) def __str__(self): return self.symbol class BalanceSheet(models.Model): company = models.ForeignKey(Company, null=True, on_delete=models.CASCADE, related_name='balance_sheets',) date = models.DateField() profit = models.BigIntegerField() loss = models.BigIntegerField() class Meta: unique_together = (('company', 'date'),) def __str__(self): return '%s - %s' % (self.company, self.date) serializers: class BalanceSheetSerializer(serializers.ModelSerializer): company = serializers.StringRelatedField() class Meta: model = BalanceSheet fields = ('company','date','profit','loss') class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('cik', 'symbol', 'name') Views: class BalanceSheetCreate(generics.CreateAPIView): '''Creates a company in the database''' model = BalanceSheet queryset = BalanceSheet.objects.all() serializer_class = BalanceSheetSerializer urls include: url(r'^(?P<symbol>[A-Z]{1,4})/create-balance-sheet/$', views.BalanceSheetCreate.as_view(), name='create_balance_sheet'), To this point, I have zero problem reading data. However, when trying to create records, I get errors I don't understand: curl …