Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to send data from the view to the template
how to send data from django views into the template in order to display the data stored in database. i have a function that insert data into a model and what i need is to retrieve the inserted data and display in template until now i tried this code but it did not display anything. Note i am sure that is correct but i do not know why its not displayed. views.py dbFolder = Folder.objects.create(folder_num = FolderNum, title = FolderTitle,date_on_folder = DateInFolder, folder_type = Type, content_folder = Content) dbFolder.save() print("dbfolder = ", dbFolder.id) print("title====", dbFolder.title) update2.html <h1>{{dbfolder.title}}</h1> Note its printed the values in the cmd. -
Django ValueError - not enough values to unpack (expected 2, got 1) list of tuples error
This is what is causing the error, I know that much: forms.py file: class CustomSignupForm(UserCreationForm): ENGLISH_INTEREST = EnglishInterest.get_english_interest_data() english_interest = forms.MultipleChoiceField(choices=ENGLISH_INTEREST, widget=forms.CheckboxSelectMultiple()) models.py file: class EnglishInterest(models.Model): english_interest = models.CharField(max_length=255) def get_english_interest_data(): return EnglishInterest.objects.values_list('english_interest') I know there must be some simple solution to get this multiple choice field to work. It does work if I were to use instead: ENGLISH_INTEREST= [ ('general speaking', 'General Speaking'), ('work opportunities', 'Work Opportunities'), ('travel', 'Travel'), ('study abroad', 'Study Abroad'), ] -
DRF Token Authentication: { "detail": "Authentication credentials were not provided." }
I am working on a Django e-commerce project. I tried to implement a token authentication system. I added rest_framework.authtokento INSTALLED_APPS and REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } to settings file. Here's my urls.py path('admin/', admin.site.urls), path('login_signup/',include('login_signup.urls')), path('profile',include('profile_info.urls')), path('',include('category.urls')), path('cart',include('cart.urls')), path('api_token_auth',views.obtain_auth_token,name='auth-token'), ] I am able to obtain tokens by providing username and password at api_token_auth end point. Now, I should be able to access any API provided I add Authorization HTTP header in this format. Authorization:Token "xyz" But I keep getting {"detail":"Authentication credentials were not provided"} Here is the view I am trying to access. class SubcategoryView(APIView): def get(self,request): serializer=SubcategorySerializer(Subcategory.objects.all(),many=True) return JsonResponse({"subcategories":serializer.data}) Why do I keep getting this error? What am I doing wrong? -
Accesing django jinja authenticated user in angularjs
I would like to access authenticated user in angularjs. How can I do that ? Also I can access jinja user in my index.html but when I try to access user in angularjs state templateUrl's html file, it does not work.? Thanks for any help. -
How querry a class with custom __init__
I save my model's class into database and now trying to querry it by using default manager's method .objects.all(). And got an error: __init__() takes 2 positional arguments but 3 were given Here is my model: class BaseCrudEntity(models.Model): pass class Meta: abstract = True class BaseListViewPreset(BaseCrudEntity): RelativeClass = models.CharField(max_length = 255, null = True) def __init__(self, context): BaseCrudEntity.__init__(self) self.model = context self.columns = [] #self.setColumns(self.model) self.RelativeClass = ".".join([context.__module__, context.__name__]) def addColumn(self, prop): _column = Column(system_name = prop.name, Preset = self) self.columns.append(_column) def setColumns(self, context): _props = context._meta.get_fields() for prop in _props: self.addColumn(prop) class Column(models.Model): system_name = models.CharField(max_length = 255) lookup_name = models.CharField(max_length = 255) Preset = models.ForeignKey(BaseListViewPreset, on_delete = models.CASCADE) I have a record in database for Preset and several records for its columns. The error i receive when calling BaseListViewPreset.objects.all() I try to comment the init inside preset class and it helps me to querry it. But I need init for initializing. So how can I solve this problem? The traceback is here: http://dpaste.com/15449TR Thanks for any help -
How to pass custom data to a django template?
I like to pass some custom data to a template in django admin. How do I access myData in the sample below? class MyAdmin(admin.ModelAdmin): def get_object(self, request, object_id, form_field=None): obj = super().get_object(request, object_id, form_field) self.myData = MyModel.objects.filer(id=obj.myData_ID) return obj In the template: {% for p in myData %} <p>{{p}}</p> {% endfor %} -
How to Read the Barcode in image using Python 3.6 without using Zbar
I am New to Barcode Reader i found some Tutorial about Zbar and which seems to not support in ZBAR. I like to raed the Barcode in a Image and extract the Data in it. This is What is Actually Tried. def detect_barcode(request): try: import pyqrcode import zbarlight qr = pyqrcode.create("HORN O.K. PLEASE.") qr.png("download.png", scale=6) import qrtools from qrtools.qrtools import QR from qrtools.qrtools import Image,BOM_UTF8 qr = qrtools.QR() qr.decode("download.png") True print(qr.data); qr.data except Exception as e: test = str(e) def detect_barcode(request): try: import pyqrcode import zbarlight qr = pyqrcode.create("HORN O.K. PLEASE.") qr.png("download.png", scale=6) import qrtools from qrtools.qrtools import QR from qrtools.qrtools import Image,BOM_UTF8 qr = qrtools.QR() qr.decode("download.png") True print(qr.data); qr.data except Exception as e: test = str(e) I Need to Decode the Barcode and extract the Data. I don't like to use Zbar. -
How to add user in admin page after downgrading the django version to 2.1.3?
I have a problem in making new user in admin page in django but whenever I add user in admin page in django version 2.2.3, it gives me NotImplementedError but when I downgraded it to 2.1.3, it gave me another error in command prompt. Now the browser page is not loading anything. I also equaled uses_savepoints = True which is by default False NotImplementedError at /admin/auth/user/add/ UNKNOWN command not implemented for SQL SAVEPOINT "s6856_x1" C:\Users\Bilal\Envs\trial\lib\site-packages\djongo\sql2mongo\query.py in parse handler = self.FUNC_MAP[sm_type] Error after downgrading to 2.1.3 django version File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\loader.py", line 273, in build_graph raise exc File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\loader.py", line 247, in build_graph self.graph.validate_consistency() File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\graph.py", line 243, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\graph.py", line 243, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\graph.py", line 96, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0012_auto_20190724_1222 dependencies reference nonexistent parent node ('auth', '0011_update_proxy_permissions') -
How to implement autocomplete_fields with Proxy model?
I want to implement autocomplete_fields feature but it doesn't work. I assume it happens because of Proxy model. So I have Customer Proxy model and PromoCode model. PromoCode has FK to Customer model. And I need to have search field for customers in PromoCode change form. Here are models and admin classes: class Customer(User): # User is a class based on django.contrib.auth.models.AbstractUser class class Meta: proxy = True class CustomerAdmin(admin.ModelAdmin): search_fields = ['email',] admin.site.register(Customer, CustomerAdmin) class PromoCode(TimeStampedModel): customer = models.ForeignKey(Customer, on_delete=PROTECT, null=True, blank=True) class PromoCodeAdmin(admin.ModelAdmin): autocomplete_fields = ('customer',) admin.site.register(PromoCode, PromoCodeAdmin) There are no errors but Customer field is still default Select input without desired filter. What I am doing wrong and how to properly implement autocomplete_fields here? p.s. python_version = "3.6" Django = "==2.2.3" -
Django Inlineformsets - Custom validation with django-extra-views
So I have a question about the form_valid for django-extra-views. I used the CreateWithInlinesView method to create a form with multiple inline formsets. The base form called "Order" contains two different formsets, "Booking" and "Payment". An Order always has to include a minimum of one Booking but does not necessarily need to have a Payment when the Order is created. The form for the Payment will be generated nonetheless. I would like to validate the Payment form on a "payment_amount" > 0. If no payment is made at the moment the order is created, no PaymentInline should be saved. views.py class BookingInline(InlineFormSetFactory): model = Booking form_class = BookingForm prefix = 'booking_formset' factory_kwargs = { 'extra': 0, 'min_num': 1, 'validate_min': True, 'can_delete': True } class PaymentInline(InlineFormSetFactory): model = Payment form_class = PaymentForm prefix = 'payment_formset' factory_kwargs = { 'extra': 1, 'min_num': 0, 'validate_min': False, 'can_delete': True } class OrderCreateView(NamedFormsetsMixin, CreateWithInlinesView): model = Order inlines = [BookingInline, PaymentInline] inlines_names = ['booking_formset', 'payment_formset'] form_class = OrderForm template_name = 'orders/order_form.html' def get_success_url(self): return reverse_lazy('order_detail', kwargs={'pk': self.object.pk}) def forms_valid(self, form, inlines): """ If the form and formsets are valid, save the associated models. """ self.object = form.save(commit=False) self.object.created_by = self.request.user form.save(commit=True) for formset in inlines: … -
u"Key 'bank' not found in 'CreditForm'"
I'm trying to expand the base model, but I get the following error. u"Key 'bank' not found in 'CreditForm'" models.py class Credit(AbstractBaseProduct): bank = models.ForeignKey('banks.Bank', verbose_name=_('bank')) class Meta: verbose_name = _('credit') verbose_name_plural = _('Credits') admin.py class BaseCreditAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'slug', 'created_at', 'updated_at'] list_display_links = ['slug',] fieldsets = [ (None, {'fields': [('best', 'hot'), 'name', 'slug']}), ('SEO', {'fields': [('breadcrumbs',), ('meta_title',), ('meta_keywords',), ('meta_description',),('short_description',)]}) ] model = AbstractBaseProduct class CreditAdmin(BaseCreditAdmin): model = Credit def get_list_display(self, requset): self.list_display.insert(2, 'bank') return self.list_display def get_fieldsets(self, request, obj=None): fieldsets = copy.deepcopy(super(CreditAdmin, self).get_fieldsets(request, obj)) self.fieldsets[0][1]['fields'].insert(1, 'bank') return fieldsets -
how o fix this error i am doing crud operation there is no error but in vies file
Class 'Employee' has no 'objects' memberpylint(no-member) See every employee has a red line and that red line is saying what see in the picture enter image description here -
AttributeError: module 'django.db.models' has no attribute 'get_models'
why am i getting issue when calling for get_model() function? Here is what I am trying to do @classmethod def get_content_models(cls): """ Return all Package subclasses. """ is_content_model = lambda m: m is not Package and issubclass(m, Package) return list(filter(is_content_model, models.get_models())) This used to work before but now after updating to new django, it's throwing an error. How can this be resolved? -
Heroku/Django - Cannot find Postgresql db
When I am running my server in heroku, I get this error saying: Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? On my heroku app, it says that it does have a Postgres db addon added. -
How to interpret this parsing error of the image variable that was rendered in the django template in heroku?
The error says (ImageFieldFile' object is not subscriptable) I wanted to call an image url using an image variable in the html django templates. I thought it was a date-util version error as i have been seeing other users recommend using date-utl version 1.5 which heroku only works with even after deprecating the date-util 2.8 to v 1.5 it still didnt work. SyntaxError at / invalid syntax (parser.py, line 158) this is where the error occured src="{{ tweet.user.profile.image.url }}" Error was this SyntaxError at / invalid syntax (parser.py, line 158) Request Method: GET Request URL: https://meawesometwitterapp.herokuapp.com/ Django Version: 2.2.2 Exception Type: SyntaxError Exception Value: invalid syntax (parser.py, line 158) Exception Location: /app/.heroku/python/lib/python3.7/site-packages/botocore/credentials.py in , line 27 Python Executable: /app/.heroku/python/bin/python Python Version: 3.7.3 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages'] Server time: Mon, 29 Jul 2019 09:32:44 +0000 I cant intepret the error in the production heroku django app -
Django annotate count doesn't work always return 1
My models: class PicKeyword(models.Model): """chat context collection """ keyword = models.TextField(blank=True, null=True) Myfilter: from django.db.models import Count PicKeyword.objects.annotate(Count('keyword'))[0].keyword__count The result always get 1 just like: print(PicKeyword.objects.filter(keyword='hi').count() show: 3 PicKeyword.objects.filter(keyword='hi').annotate(Count('keyword'))[0].keyword__count show: 1 Is it because I use sqllite or my keyword type is Textfield? -
Change admin form name for overridden User
I've overridden the standard django User by extending AbstractUser. Now this all works fine, but for some reason I can't make the admin display "Profiles" (the name of the model now set in settings.AUTH_USER_MODEL instead of "Users". This is my code for admin.py for the profiles app from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm from .models import Profile class ProfileChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = Profile verbose_name_plural = "Profile" class ProfileAdmin(UserAdmin): form = ProfileChangeForm # fieldsets = UserAdmin.fieldsets + ((None, {"fields": ("some_extra_data",)}),) fieldsets = UserAdmin.fieldsets admin.site.register(Profile, ProfileAdmin) I'd figured there should be some Meta setting I can put in here, but after significant amounts of googling I can't find anything. I'm sure this is a simple answer - could somebody point me in the right direction? I've tried setting "name" and "verbose_name", but no joy. At the end of the day, I could live with this, as it's just the admin interface, but it's bugging me ... -
How can I change fieldsets from BaseAdmin model? Unhashable type: 'list'
I decided to create a basic model for admin panel, from which I will inherit. It has fieldsets. How can I insert certain fields into the first and second tuples? Found the get_fieldsets method. But for now, I get an error. TypeError: unhashable type: 'list' admin.py class BaseCreditAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'slug', 'created_at', 'updated_at'] list_display_links = ['slug',] fieldsets = [ (None, {'fields': [['best', 'hot'], 'name', 'slug']}), ('SEO', {'fields': [['breadcrumbs',], ['meta_title',], ['meta_keywords',], ['meta_description',],['short_description',],]}) ] model = AbstractBaseProduct Tracebck: Unhandled exception in thread started by <function wrapper at 0x7f799fddb1b8> Traceback (most recent call last): File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 22, in ready self.module.autodiscover() File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/m0nte-cr1st0/work_projects/startup/finbee/credits/admin.py", line 60, in <module> admin.site.register(Credit, CreditAdmin) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 109, in register system_check_errors.extend(admin_obj.check()) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 113, in check return self.checks_class().check(self, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/contrib/admin/checks.py", line 495, in check errors … -
Determining the number of connected clients in django channels 2
for a webrtc project, I need to transform the server code from https://codelabs.developers.google.com/codelabs/webrtc-web/#6 to a django channels 2 version. In the code, as you can see, the server sends/emits some events based on the number of clients connected. here is the code: 'use strict'; var os = require('os'); var nodeStatic = require('node-static'); var http = require('http'); var socketIO = require('socket.io'); var fileServer = new(nodeStatic.Server)(); var app = http.createServer(function(req, res) { fileServer.serve(req, res); }).listen(8080); var io = socketIO.listen(app); io.sockets.on('connection', function(socket) { // convenience function to log server messages on the client function log() { var array = ['Message from server:']; array.push.apply(array, arguments); socket.emit('log', array); } socket.on('message', function(message) { log('Client said: ', message); // for a real app, would be room-only (not broadcast) socket.broadcast.emit('message', message); }); socket.on('create or join', function(room) { log('Received request to create or join room ' + room); var clientsInRoom = io.sockets.adapter.rooms[room]; var numClients = clientsInRoom ? Object.keys(clientsInRoom.sockets).length : 0; log('Room ' + room + ' now has ' + numClients + ' client(s)'); if (numClients === 0) { socket.join(room); log('Client ID ' + socket.id + ' created room ' + room); socket.emit('created', room, socket.id); } else if (numClients === 1) { log('Client ID ' + socket.id + ' … -
gunicorn keeps rebooting it's worker when Django is starting Python project
I am running a web-based project with a data science focussed backend which is hosted on a Microsoft Azure cloud server. Large deep learning models need to be loaded and initialized when Django starts the project. I am running the project through an nginx server which communicates to the Django server through gunicorn. If I run the project on the same Azure cluster through Django alone (not using nginx or gunicorn) it initializes and starts just fine. However, when I run it on nginx through gunicorn, one of the workers keeps rebooting as the project is starting up (it takes maybe ~2 mins to initialize. Here is the output from the gunicorn command when I try to start the Django project: user@host:/home/libor/libor_transition/libor_transition_api$ sudo gunicorn --pythonpath="$(pwd)" --log-level=DEBUG -t 1000 libor_transition_api.wsgi:appli> [2019-07-29 08:43:44 +0000] [33808] [DEBUG] Current configuration: config: None bind: ['127.0.0.1:8000'] backlog: 2048 workers: 1 worker_class: sync threads: 1 worker_connections: 1000 max_requests: 0 max_requests_jitter: 0 timeout: 1000 graceful_timeout: 30 keepalive: 2 limit_request_line: 4094 limit_request_fields: 100 limit_request_field_size: 8190 reload: False reload_engine: auto reload_extra_files: [] spew: False check_config: False preload_app: False sendfile: None reuse_port: False chdir: /home/libor/libor_transition/libor_transition_api daemon: False raw_env: [] pidfile: None worker_tmp_dir: None user: 0 group: 0 umask: 0 initgroups: False … -
How to set a timedelta in between two model datefields
i'm strugling some time already trying to set a timedelta in two fields of my model, then display de difference between then. i've tried Stack and a lot of others tutorials and not quite shure if a should make a function on my models or my views, or a basic variable on the views i've tried all of them here is my code: MODELS.PY from django.db import models from datetime import datetime from datetime import timedelta class To_do (models.Model): task = models.CharField(max_length=150) topic = models.CharField(max_length=150) how = models.TextField(max_length=600) start = models.DateField(blank=False) end = models.DateField(blank=False) def __str__(self): return self.task VIEWS.PY class DetailView(DetailView): template_name = 'details.html' model = To_do def get_queryset(self): return To_do.objects.all() def get_delta(self): d1 = To_do.start d2 = To_do.end tdelta = d1-d2 return tdelta i want to display the difference between the star and end and after that, and after that setup an alarm if get less than three days. appreciate your help. -
User authentication using django and MYSQL
i am trying to authenticate the user using MYSQL (running on XAMPP). however the table in the database has been created but when i manually add a user and password in database and then try to authenticate then it show invalid credentials. the above thing has been succesfully done using sqlite3 Objectives to be achieved :- A) User authentication using MYSQL B)Everytime the user log-in, In database the name and datetime of the user login should be reflected. Here's code:- models.py from django.db import models from datetime import datetime from django.contrib.auth.models import AbstractUser # Create your models here. class Login(AbstractUser): username = models.CharField(max_length=50,blank=False) password = models.CharField(max_length=32) def __str__(self): return self.username Views.py from django.shortcuts import render from first_app.forms import CmdForm #view after login from django.http import HttpResponse, HttpResponseRedirect #some imports from django.urls import reverse import csv from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib import messages #from django.contrib.sessions import serializers # Create your views here. def login_view(request): context = {} if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('IP form')) else: messages.error(request,'Please provide valid credentials') return render (request,"first_app/login.html", context) else: return render (request,"first_app/login.html", context) @login_required def user_logout(request): … -
IF statement not working with list difference
Trying to get the result of the difference between two list, using below code, but doesn't seemed to work, Please help list1 = ['one', 'two', 'three'] list2 = ['one', 'two', 'three', 'four'] list3 = list(set(list1) - set(list2)) if not list3: #if not empty, print list3 print(list3) else: # if empty print none print("None") -
I keep getting a 404 error when django is looking for static files
I keep getting a 404 error when django is looking for static files. settings.py STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn') STATIC_URL = '/static_cdn/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) project tree structure of app - business -- migrations --- .... -- static --- business ---- main.css ---- scripts.js -- templates --- business ---- base.html ---- home.html -- templatetags --- ... -- __init__.py -- admin.py -- apps.py -- models.py -- tests.py -- urls.py -- views.py Error [29/Jul/2019 13:09:45] "GET / HTTP/1.1" 200 12670 [29/Jul/2019 13:09:45] "GET /static_cdn/business/main.css HTTP/1.1" 404 77 [29/Jul/2019 13:09:45] "GET /static_cdn/business/scripts.js HTTP/1.1" 404 77 I also link to static files like {% static 'business/main.css' %} and I do have {% load static %} at the top of my document. Why isn't django able to find the static files? The error says it is looking in the correct place but it is returning 404 error. If you need anything else, you can look at my code -
Overwriting nested serializer's create method throws TypeError: create() got multiple values for keyword argument
I want to send data to my API. My data structure is nested. So I am trying to overwrite the create method following the docs and SO. When sending data it gives me the following error: TypeError: create() got multiple values for keyword argument 'graph' My data structure looks like this: { "project": "project1", "name": "Graph1", "description": "Graph belongs to Projekt1", "nodes": [ { "id": 2, "name": "Node1 of Graph 1", "graph": 3 } ] } Her is what I am trying in my serializer (which is pretty standard I assume): class GraphSerializer(serializers.ModelSerializer): nodes = NodeSerializer(many=True) class Meta: model = Graph fields = ('project', 'name', 'description', 'nodes', ) def create(self, validated_data): nodes_data = validated_data.pop('nodes') graph = Graph.objects.create(**validated_data) print(graph) for node_data in nodes_data: Node.objects.create(graph=graph,**node_data) return graph The error is in the for loop. When I debug though and print graphit give me back just one Graph (Graph1). So I don't understand why I should get a multiple values error. Here is more info if needed: Node serializer class NodeSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = Node fields = ('id', 'name', 'graph', ) My models class Graph(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=120, blank=True) description = models.CharField(max_length=400, blank=True) def __str__(self): …