Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django foreign key as primary key?
The question In Django, is it possible to use a foreign key as the primary key for a model? For example: Context Let's say that we have class Reporter that has many Articles, but if we remove our reporter from our database, we also want the articles that belonged to them to be deleted. The schema is a one-to-many relationship, where one reporter has many articles, and the existence of the article instances in the database relies on the reporter instance. What I am confused about specifically What kind of Django relationship would I need to achieve this business requirement? Unfortunately, I have read all of the Django documentation. Therefore, I cannot find which database relationship makes the most sense, and I hope someone with more experience than me in Django and PostgreSQL can help out. Bonus points Imagine that each article needs to be in a specific arbitrary order and that this is also a constraint of the database relationship. -
AWS S3 Lambda Trigger Not Working When Uploaded to Bucket Subfolder
I have a Lambda Python function that will resize images on upload. Everything is working correctly, but only when I upload directly to the bucket. When I upload files to the bucket/uploads/ folder, it would no longer trigger the resize function. I have tried the filtering options in the trigger settings uploads/ to no avail. Assuming it is related to my Lamda function and the folder should/must also be included? Here is my Lambda function: def lambda_handler(event, context): for record in event["Records"]: bucket = record["s3"]["bucket"]["name"] key = record["s3"]["object"]["key"] download_path = "/tmp/{}{}".format(uuid.uuid4(), key) upload_path = "/tmp/resized-{}".format(key) s3_client.download_file(bucket, key, download_path) -
pass value for two different submit buttons in same form methods in Django
Lets us consider my template.html as <form class="form-horizontal" id="adhoc-form" method="post" action="{% url 'contacts:add_item' item.id %}"> {% csrf_token %} <fieldset> <div class="control-group"> <label for="id_item_filename" class="control-label">Items <span class="text-error">*</span></label> <div class="controls"> <select placeholder="Item filename" name="item" id="id_item_filename" class="span3" required="required"> <option value="">---------</option> {% for i in items %} <option value="{{i.0}}">{{i.1}}</option> {% endfor %} </select> </div> </div> </fieldset> <div id="form-buttons-container" class="form-actions" style="padding-left: 0px;"> <div class="controls"> <input type="hidden" class="btn btn-primary btn-medium" id= 'i_id' name='i_id' value="{{data.0.id}}"> <input type="submit" class="btn btn-primary btn-medium" value="Submit"> <input type="submit" class="btn btn-primary btn-medium" value="Delete"> </div> </div> </form> my url.py is url(r'^stock/item/add/item_name/(?P<id>\d+)/$', login_required(UpdateBarcode.as_view()), name="add_item"), my views.py is class UpdateItem(View): def post(self, request, id): item_id = request.POST.get('item') items = Items.objects.get(id=item_id) try: JobItems.objects.filter(id=id).update(item_name=items.name) except: messages.error(request, 'Cannot update') return redirect(reverse("contacts:item_list")) Here when clicking the submit button we need to update item and we click delete button item should be deleted.please help me how can do both the submit and delete operations in the same view -
Django context processor not rendering from shell
Using Django 3.2 Have defined few global variables like app/context_processors.py from app.settings import constants def global_settings(request): return { 'APP_NAME': constants.APP_NAME, 'APP_VERSION': constants.APP_VERSION, 'STATIC_URL_HOST': constants.STATIC_URL_HOST } and in settings.py file TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'app.context_processors.global_settings', ], }, }, ] Have used APP_NAME in the email template footer like templates/account/welcome_message.html Hi {{ username }}, Welcome to the application. {{ APP_NAME }} When the email is sent from the web portal, the APP_NAME is rendered fine, but when the email send is initiated from the Django shell python manage.py shell > from account.emails import welcome_email > welcome_email(user) Then the APP_NAME is not rendered in the email. How the context processor can be rendered from the shell as well? -
TypeError: Complex aggregates require an alias
I have this very normal Sum of various fields, but it always returns the error in the title, what is missing? ticket_history_aggregation = ticket_history_aggregation.aggregate( ticket_total=Sum("ticket_total", 0), ticket_queue=Sum("ticket_queue", 0), ticket_queue_expiring= Sum("ticket_queue_expiring", 0), ticket_processing_expiring =Sum("ticket_processing_expiring", 0), ticket_pending=Sum("ticket_pending", 0), -
error when trying to run "runserver" after reinstalling windows 10
So I reinstalled my computer but before that I backed up my code files and after that I installed python and and venv again. i was able to run the virtualenv but when i tried to do runserver this error pops up Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'C:\coding\e-commerce/Scripts\python.exe' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\coding\\e-commerce\\Scripts\\python.exe' sys.base_prefix = '' sys.base_exec_prefix = '' sys.executable = 'C:\\coding\\e-commerce\\Scripts\\python.exe' sys.prefix = '' sys.exec_prefix = '' sys.path = [ 'C:\\coding\\e-commerce\\Scripts\\python38.zip', '.\\DLLs', '.\\lib', 'c:\\users\\chp\\appdata\\local\\programs\\python\\python38-32', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x000010f8 (most recent call first): <no Python frame> can anyone explain this error to me? thank you very much -
Why my generated docx in javascript from a blob is filled with [Object Object]?
I'm sending data to my Django backend through a POST request, the server then creates a docx using this data and sends it back to me where I'm trying to download it using the following code : axios.post(route, data).then((res) => { const filename = "report.docx" var blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }); var link = document.createElement('a'); var URL = window.URL || window.webkitURL; var downloadUrl = URL.createObjectURL(blob); link.href = downloadUrl; link.style = "display: none"; link.download = filename; document.body.appendChild(link) link.click() link.remove() }); The download of the file works but when I open it, it only contains [Object Object], what am I doing wrong here ? I checked the backend and the document is properly created as it has the right content when I'm saving it when it's generated in the server so it's either that i'm sending it badly or creating the file in the frontend badly. Here is how I send it from the backend : #Generating the doc properly before this... response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') report_filename = 'graph-report-'+now.strftime('%Y-%m-%d_%H-%M-%S')+'.docx' response['Content-Disposition'] = 'attachment; filename=%s'%(report_filename) document.save(response) return response Thanks for helping me. -
lunch a modal after registration login if form in invalid , Django
i want to lunch a modal if the information put on the Form Is incorrect. Here is the view code : def ajouterClient(request): if request.method == "POST": form = ClientForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: erreur = "erreur" return render(request, 'frontend/home.html' , locals()) And Here is the template code: {% if erreur == "erreur" %} <div class="modal fade" id="erreur" tabindex="-1" aria-labelledby="erreurLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header bg-dark text-white"> <h5 class="modal-title" id="loginLabel">Erreur</h5> <button type="button" class="btn-close bg-light" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body bg-light"> <h1>Veuillez remplir tous les champs correctement</h1> </div> <div class="modal-footer"> </div> </div> </div> </div> <script> $(document).ready(function(){ $('#erreur').modal('show') }); </script> {% endif %} <!-- End Erreur Modal ajout --> -
django orm filters and nested Prefetch
I need to get all users who have instances with the status of running or creating, and get instances for these users with the same filter, my query looks like queryset = User.objects.filter( Q(testinstance__status=TestInstance.RUNNING) | Q(testinstance__status=TestInstance.CREATING) ).order_by('first_name').prefetch_related(Prefetch( 'testinstance_set', queryset=TestInstance.objects.filter( Q(status=TestInstance.RUNNING) | Q(status=TestInstance.CREATING) ).order_by('-started_at') )).distinct() models: class TestInstance(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) Can I somehow avoid duplicate filters ? -
Rendering Grafana inside django website using API Key
I’m attempting to pass an API token for a user to grafana from our own internal website so that the main gui renders in an iframe. We don’t want the users to have to log into grafana after they have logged into our site, so we are creating their users in grafana, building an API token and attaching that to the user for our website. When the user goes to the page that has the grafana iframe, we are sending an ajax get request with the token so grafana renders the main dashboards with the users information. If we do just a standard iframe everything works fine and we render inside the frame. We can get to the login page and do everything we need to. When I add the token so we don’t need to authenticate nothing renders and I see no errors/logs on either grafana or the website. If I send an invalid token I see the expected “401 invalid Api key” error on both the website and the grafana logs. This is what I’m sending from the website… <div class="content"> <div class="container-fluid" id="container"> </div> </div> <script> $.ajax({ url: "{{url}}", type: "GET", beforeSend: function(xhr){ xhr.setRequestHeader('Accept', 'application/json'); xhr.setRequestHeader('Authorization', 'Bearer … -
cant change images through html forms but i can change them from django admin panel
I have a form where users can change their profile picture, but for some reason it just stopped working, but when I try to change their profile picture from the admin panel it works, here is a few of my code. settings.html <form method="POST">{% csrf_token %} <div class="VpWhO text-center" style="height: 80px"> <div> <h4 style="text-transform: capitalize;"> {{request.user.username}} </h4> {{form.profile_pic}} </div> </div> <button type="submit">Save Changes</button> </form> views.py for setting.html def settings_view(request): myinstance = User.objects.filter(username=request.user).first() form = SettingsForm(instance=myinstance) if request.method == 'POST': form = SettingsForm(request.POST, request.FILES, instance=myinstance) if form.is_valid(): obj = form.save(commit=False) obj.username = slugify(obj.username) obj.save() messages.success(request, 'Profile Saved.') return redirect('/') else: messages.error(request, 'Can\' save changes.') else: myinstance = User.objects.filter(username=request.user).first() form = SettingsForm(instance=myinstance) class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) name = models.CharField(max_length=30, null=True, blank=True) bio = models.TextField(null=True, blank=True) profile_pic = models.ImageField(default='default_pfp.jpg', upload_to="user_uploaded") date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] @property def imageURL(self): try: url = self.profile_pic.url except: url = 'default_pfp.jpg' return url urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ MY URLS HERE ] if settings.DEBUG: urlpatterns … -
How to call Django model method from admin
I have a model that is seperate to a user model which stores passwords, I have implemented a set_password method on that model, and this works ok, the only place I am facing issues is the admin panel, if I try to update a password in the model from the admin it does not call this set_password method. Instead it inputs the password as plain text. Is there a way to override the admin panel so it calls the set_password method? class MyModel(models.Model): name = models.CharField(max_length=255) created_on = models.DateTimeField(default=timezone.now) encrypted_pass = models.CharField(max_length=255, null=False) def set_password(self, raw_password): self.encrypted_pass = make_password(raw_password) -
Django Annotate using a model method
I'm trying to do an annotate in this model, but considering the get_is_secure into the result. class ScoringStudyLog(TimeStampedModel): scoring_status = models.CharField('Estudio', max_length=255, choices=_STATUS_CHOICES, default='pending') class Meta: # pylint: disable=too-few-public-methods """ Sets human readable name """ verbose_name = "Registro de estudio" verbose_name_plural = "Histórico de estudios" def get_is_secure(self): return self.scoring_status == "approved" How could I do a query like this? indicators["studies_by_status"] = ScoringStudyLog.objects.filter( **studies_filters ).values('is_secure').annotate(times=Count('is_secure')) -
still in same page when i use get_absolute_url in django
i work in django 3.2.7, but when i use get_absolute_url() function (in list of objects) return with no object and still in same page (list of objects), any idea ? models.py : def __str__(self): return self.title def get_absolute_url(self): return reverse("post_detail", kwargs={'slug': self.slug}) def headline(self): return self.content[:50]+'...' views.py : def post_list(request): post_list=Post.objects.all().order_by('-created_at') lastest=post_list.order_by('-created_at')[:4] last_post= post_list.order_by('-created_at')[0] context={ 'allpost':post_list, 'latest':lastest, 'lastpost':last_post } return render(request,'post/post_list.html',context) urls.py : from django.urls import path from . import views app_name="allpost" urlpatterns = [ path('', views.post_list), path('<slug:slug>',views.PostDetail.as_view(),name='post_detail'), ] in templates post_list.html : {% for post in allpost %} <small> نُشر من قبل : {{post.author}}|| </small> <small>بتاريخ : {{post.created_at}}</small> </div> <h3 class="mb-0"style="direction: rtl;">{{post.title}}</h3> <p class="mb-auto"style="direction: rtl;">{{post.headline}} </p> <a href="{{ post_detail.get_absolute_url }}"class="stretched-link">Continue reading</a> </div> <img class="rounded float-left m-1" src="{{post.image.url}}" alt="" style="height: 260px; width: 250px;"> </div> </div> </div> {% endfor %} with this,<a href="{{ post_detail.get_absolute_url }}" class="stretched-link">Continue reading</a> , link doesn't work, but no error shown. how can i resolve this problem ? thanks! -
Article.objects.order_by('order') vs type(self).objects.order_by('order')
I have a model: class Post(models.Model): title = models.CharField(max_length=15) create = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField() And I override save: def save(self, *args, **kwargs): max_order_obj = type(self).objects.order_by('-ordering').first() --- some logics --- super().save(*args, **kwargs) But I can do it: def save(self, *args, **kwargs): max_order_obj = Post.objects.order_by('-ordering').first() --- some logics --- super().save(*args, **kwargs) Without type(self). And it works the same way! But which is better? What is more correct? And what's the difference in that? -
React Native and Django Rest Framework connection problem at local,Cors settings
I am building a react native project. I have already done the same project's website. I deployed it on Heroku and without any problem it works. When I try to fetch data on local server with react native app, It does not work but when I use deployed project url it works. For example; http://127.0.0.1:8000/api/sosyalmedya/ does not work. http://mydeployedwebsite/api/sosyalmedya/ work. My settings.py is the same with deployed one. In my settings.py, I have added these; ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True -
GeoDjango - osm2geojson - IllegalArgumentException: Shell is not a LinearRing
Django is throwing IllegalArgumentException: Shell is not a LinearRing, when I'm trying to convert a osm json to geojson with osm2geojson. The exception is only thrown when osm2geoson is trying to make a MultiPolygon out of a relation. It returns a geojson, but without coordinates. Points are transformed correctly. -
Binding vue js to django template not showing any content
I am trying to binding vue js component into django HTML template file, but it is not showing any content. I am not getting any error. Just blank component. Here is my django HTML template: {% load render_bundle from webpack_loader %} {% render_bundle 'product-filter-app' %} {% block section_main %} <section id="section_main" class="guide_section"> <div id="product-filter-app"> <product-filter-app></product-filter-app> </div> </section> {% endblock %} Here is my vue js app. main.js import Vue from 'vue' import * as Sentry from '@sentry/browser' import 'vue-select/dist/vue-select.css' import ProductFilterApp from './ProductFilterApp' import { sentryOptions } from '@/utils/settings' if (process.env.VUE_APP_MODE !== 'dev') { Sentry.init(sentryOptions) } new Vue({ components: { ProductFilterApp } }).$mount('#product-filter-app') Here is ProductFilterApp.vue <template> <h1>Test</h1> </template> <script> export default { name: 'ProductFilterApp', components: { }, props: { }, data () { return { } }, methods: { } } </script> <style scoped> </style> Web-pack is generating app successfully there is not any error but just showing empty component as per screen shot. Any help will be appreciated. -
No module named myapp
I have this project directory structure: . .pylintrc |--myproj . |--myapp |--myproj (settings.py is here) __init__.py manage.py . In settings.py, INSTALLED_APPS I have the first entry 'myapp'. From the root folder (containing .pylintrc), I call $ DJANGO_SETTINGS_MODULE=myproj.myproj.settings pylint myproj --load-plugins pylint_django However, I get error no module named 'myapp'. If I change the INSTALLED_APPS entry to 'myproj.myapp', then it is able to continue, but now I'm unable to start the project normally with manage.py runserver. What am I doing wrong, and what can I do to proceed? -
ERR_SSL_PROTOCOL_ERROR while local development django
I had set up some https settings for Production and as python manage.py check was giving me warnings. So I added some new lines in settings.py. import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent from environs import Env env=Env() env.read_env() # read .env file, if it exists DEBUG = env.bool("DEBUG",default=True) SECRET_KEY=env.str("SECRET_KEY") ALLOWED_HOSTS = ['127.0.0.1','localhost','theopra.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'EHub.apps.EhubConfig', 'MCourses.apps.McoursesConfig', 'MArticles.apps.MarticlesConfig', 'MProgrammingLanguage.apps.MprogramminglanguageConfig', 'MSoftwareDevelopment.apps.MsoftwaredevelopmentConfig', #ThirdPartyPlugin 'ckeditor', 'ckeditor_uploader', 'taggit', 'mptt', 'admin_honeypot', ] APP_DIRS=True SITE_ID=1 CKEDITOR_UPLOAD_PATH = 'ckeditor/uploads/' CKEDITOR_CONFIGS={ 'default':{ 'toolbar':'Custom', 'uiColor' : '#FFFFFF', 'height':500, 'toolbar_Custom':[ ['Styles','Format','Bold','Italic','Underline','Strike','SpellChecker','Undo','Redo'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','HorizontalRule'], ['TextColor','BGColor'], ['Smiley','SpecialChar'], ['Source'], ] }, 'sourcecode':{ 'codeSnippet_theme': 'monokai', 'toolbar':'SourceCode', 'toolbar_SourceCode':[ ['Styles','Format','Bold','Italic','Underline','Strike','SpellChecker','Undo','Redo'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','HorizontalRule'], ['TextColor','BGColor'], ['Smiley','SpecialChar'], ['CodeSnippet'], ], 'extraPlugins': 'codesnippet', }, } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Dtheopra.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Dtheopra.wsgi.application' DATABASES = { "default": env.dj_db_url("DATABASE_URL") } #NEW SETTINGS FOR HTTP SESSION_COOKIE_SECURE = True #new CSRF_COOKIE_SECURE = True #new SECURE_SSL_REDIRECT = True #new AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization … -
ManytoManyField save and calculate
I just started self learning Python and Django as a hobby recently, and have been trying to self develop a project which helps me in my construction business. I have developed certain functions in my project which give me the result I want, but is not the most ideal in terms of coding practises. However, I am just learning from scratch and modifying my code as I learn. However, now I am stuck (maybe because my basic concept is only not correct?). Require help on how to proceed. So here is my models.py class FootingQuantity(models.Model): member_name = models.CharField(max_length=8, unique=True) --more fields hidden-- x_axis = models.FloatField() y_axis = models.FloatField() class BeamQuantity(models.Model): work = models.ForeignKey(Work, default=1, on_delete=models.CASCADE) member_name = models.CharField(max_length=8, unique=True) location = models.ManyToManyField(FootingQuantity) length = models.FloatField(blank=True) breadth = models.FloatField() height = models.FloatField() -- more fields -- @property def length_of_beam(self): yy = self.location.all().values_list('y_axis', flat=True) xx = self.location.all().values_list('x_axis', flat=True) ylist = list(yy) xlist = list(xx) return abs(ylist[1] - ylist[0] + xlist[1] - xlist[0]) @property def total_concrete_quantity(self): return float(self.length) * float(self.breadth) * float(self.width) def save(self, *args, **kwargs): self.length = self.length_of_beam self.total_quantity = self.total_concrete_quantity super(BeamQuantity, self).save(*args, **kwargs) def __float__(self): return self.length, self.total_quantity I want my model to accept ManytoManyRelation of 2 Footings selected and then … -
Django reset password url in email only works if copy and paste it, not click on it
When I request a password reset with the built in django machinery, it will generate a URL in the email like this: https://example/accounts/reset/MTA/atspc3-7c45df8a600243fde3dfb60c44873f15/ In gmail if I go show URL, the text is indentical since it is being generated as a plain/text email. If I click the link in gmail, or outlook then it goes to (maybe after a redirect, I can't tell since its so fast): https://example.com/accounts/reset/MTA/set-password/ And it says Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. However if I copy and paste the URL into the browser, then it works. However no-one copies and paste the URL, they all click the link and say it does not work. I don't get why clicking on the link does not work since it is correct? How does one even debug this? -
Project Ideas for Django
I look for project suggestions. Or if you are working on it and ready for collaboration. I really interested in. Project stack: Django REST Any DB Or anything just want to learn!!! -
nested serializer not returning expected values Django Rest Framework
I've started learning django recently and can't seem to figure out how to get the data I want. I'm looking to build an object that can give me each part name and all of the reports of that part and then get the report data but only for the part I'm currently on This is an example of the data I would want. { "count": 2536, "next": "http://127.0.0.1:8000/esd/salesreportsdetail2/?page=2", "previous": null, "results": [ { "id": 2, "name": "A0012", "sales_report_parts": [ { "id": 5, "date": "2021-08-31T00:00:00Z", "sales_report_items": [ { "quantity": 1, "site": "FBA" }, { "quantity": 3, "site": "Vendor" }, { "quantity": 4, "site": "Main" } ] } ] } ] } But instead, I keep getting all the sales report items for each item. { "count": 2536, "next": "http://127.0.0.1:8000/esd/salesreportsdetail2/?page=2", "previous": null, "results": [ { "id": 2, "name": "A0012", "sales_report_parts": [ { "id": 5, "date": "2021-08-31T00:00:00Z", "sales_report_items": [ { "quantity": 1, "site": "FBA" }, { "quantity": 3, "site": "Vendor" }, { "quantity": 4, "site": "Main" }, { "quantity": 45, "site": "FBA" }, { "quantity": 102, "site": "Vendor" }, { "quantity": 161, "site": "Main" }, { "quantity": 7, "site": "FBA" },... and so on gets me all of the data Below are my … -
KeyError: 'user_id' when using PUT request
Recently started working with Django REST framework. I have a user table and another table that stores some relevant data for each user. I've set up POST/GET/DELETE methods fine, but I can't get the method for perform_update working - I keep getting a KeyError at /api/sdgdata/1 'user_id' error in Postman when I attempt a put request for a user. Plz see code below: Models: class TestDataTwo(models.Model): user = models.ForeignKey("auth.User", related_name="testdatatwo", on_delete=models.CASCADE) test_name = models.CharField(max_length=1024, null=True, default="N/A") Serializers: class TestDataTwoSerializer(serializers.ModelSerializer): class Meta: model = TestDataTwo fields = ( "id", "test_name", ) def update(self, instance, validated_data): # get user id from validated data: user_id = validated_data.pop('user_id') # get user: user = User.objects.get(id=user_id) # set user on instance: instance.user = user instance.save() # continue with update method: super().update(instance, validated_data) Views: class TestDataTwoViewSet(ModelViewSet): queryset = TestDataTwo.objects.all().order_by('id') serializer_class = TestDataTwoSerializer paginator = None # CREATE NEW TESTDATATWO ROW FOR USER def perform_create(self, serializer): serializer.save(user=self.request.user) # GET ALL ENTRIES OF TESTDATATWO FOR SPECIFIC USER, EXCEPT IF SUPERUSER, THEN RETURN ALL def get_queryset(self): # if self.request.user.is_superuser: # return self.queryset # else: return self.queryset.filter(user=self.request.user) def perform_update(self, serializer): instance = self.get_object() serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_200_OK) # DELETE TESTDATATWO ID def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return …