Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store JWTs in HttpOnly Cookies?
I am currently developing a React-Django App and using JWTs for authentication. After a little research I found out that storing JWTs in client is not safe(XSS and XSRF) and most of the people advice that I should store them in server-side with HttpOnly cookies but nobody tells how to do it. So can anybody help with that? -
Save the voice recorder by Recorder js to the backend database DJANGO
So I was able to create a js code that takes user input and display it to the user so he can hear it, however, I'm not sure exactly how can I save it in Django database to be a voice message in short I don't know which thing I should pass to Django to save it within my ajax function Template view (index.html): <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <link rel='stylesheet prefetch' href='https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" href="https://medias.pylones.com/9387-thickbox_default/pen-rocket-pen.jpg" type="image/jpg" sizes="16x16"> <title>Recorder</title> </head> <body> <div id="ok"></div> <div class="col-md-5 container"> <button class="btn btn-secondary p-3" style="border-radius: 50%;" id="recorder"> <i class="fa fa-microphone" style="font-size: 67px"></i> </button> </div> <script> $(document).ready(function () { var i = 0, timeOut = 0; $('#recorder').on('mousedown', function (e) { timeOut = setTimeout(() => { $(this).addClass('btn-success') $(this).removeClass('btn-secondary') navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { mediaRecorder = new MediaRecorder(stream) mediaRecorder.start(); chuck = []; mediaRecorder.addEventListener("dataavailable", e => { chuck.push(e.data) }) mediaRecorder.addEventListener("stop", e => { blob = new Blob(chuck); audio_url = URL.createObjectURL(blob); audio = new Audio(audio_url); audio.setAttribute("controls", 1); ok.appendChild(audio) }) }) }, 500); }).bind('mouseup touchhend', function (e) { $(this).addClass('btn-secondary') $(this).removeClass('btn-success') clearInterval(timeOut); mediaRecorder.stop() console.log(chuck) $.ajax({ url: "{% url 'create_voice' %}", method: 'get', dataType: 'json', data: { … -
Integrating Sqlalchemy with django
I am working on django project and new requirement is to change my django ORM to sqlalchemy and graphene. I am new to sqlalchemy and graphene. I need to perform crud using graphene. I am able to perform insert record using sqlalchemy, but not do with graphene. If any one has idea how to do that It would be highly helpful. Below is the my model definition in models.py file class Movie(models.Model): name = models.CharField(max_length=100) genere = models.CharField(max_length=50) budget = models.FloatField() releaseYear = models.IntegerField() I have converted for sqlalchemy as class Movie(Base): __tablename__:'movie' name = Column(String(100)) genere = Column(String(50)) budget = Column(Numeric) releaseYear = Column(Integer) -
How to create objects of forms through Django Admin
I have a problem that I need to solve. I have no clue what to search or how to approach the problem. I want with the help of Django, create my "own" custom forms through Django Admin so I can use these as Objects. For example through Django Admin I want to for example press a button "Create new form" and select what new field I want to use, for example I want to have one field of charfield, and two fields of datefield. So it will create a new form, and then next time when i press that button I want to create a different one, one with IntegerField and one with charfield. What things should I look into to solve this problem? I have already knowledge in Django but I have no idea what to use to solve this perticular problem. I have read through the documentation. -
Pythonanywhere Django app does not work with MySql
What do we have: Django app hosted on Pythonanywhere with sqlite db initialized MySql DB activated on Pythonanywhere (it provided me with db name, pasword and host - everything that I need to setup settings.py) pip install mysqlclient finished successfully python manage.py makemigrations - DONE python manage.py migrate - DONE mysql console on Pythonanywhere shows all my tables created but restarting app causes pythonanywhere error page and link to error log 2020-08-15 17:22:56,536: Error running WSGI application 2020-08-15 17:22:56,569: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. 2020-08-15 17:22:56,569: Did you install mysqlclient? So the question is how could it be possible? As i got it right migrations are used mysqlclient to manipulate DB, how can it be not installed? Might be someone did face with similar issue? -
Consume POST request data
I have two endpoints here as shown below. When I hit the app1 endpoint(http://localhost:8000/app1) i want to send ans to data_receiver via POST request and print the data but its printing None def app1(request): ans = {'key' : 1} headers = {'content-type': 'application/json'} requests.post("http://localhost:8000/data_receiver", data=ans, headers=headers) return JsonResponse({'message': 'ok'}) def data_receiver(request): user = request.POST.get('data') print(user) # printing None here return JsonResponse({'message': 'ok'}) Please suggest where I am doing wrong -
Scrapyd Django: how to properly check when the crawl has finished
I’m asking for help with an issue I’m stuck with and I cannot figure out how to proceed. There are some similar questions but the answers are not what I’m looking for. Basically I wrote a spider with Django and Scrapy. I’m using Scrapyd to run a big number of spiders for various users. What I need to do is to check the status of a crawl in order to see if it is running or has finished. This is because I want to show the crawl analysis to the users (via an HTML button)only after a crawl has finished, and not before when it’s halfway through the process. Scrapyd has the listjobs endpoint which gives back the status for each crawl: {"status": "ok", "pending": [{"id": "78391cc0fcaf11e1b0090800272a6d06", "spider": "spider1"}], "running": [{"id": "422e608f9f28cef127b3d5ef93fe9399", "spider": "spider2", "start_time": "2012-09-12 10:14:03.594664"}], "finished": [{"id": "2f16646cfcaf11e1b0090800272a6d06", "spider": "spider3", "start_time": "2012-09-12 10:14:03.594664", "end_time": "2012-09-12 10:24:03.594664"}]} The problem with this is that I need to check this until the status is “finished”, so that I can show the button. So I would need to call it every X seconds to check for the status. I also know there is close_spider method in Scrapy pipeline, but not sure if … -
When does Django / Mongo dereference a ReferenceField?
When does Django/ Mongo dereference a ReferenceField. Let’s say I do something like: class ModelA: rf=fields.ListField(fields.ReferenceField(ModelB)) class ModelB: pass A=[ x for x in ModelA.rf] B=ModelB.objects.filter(id__in=[ x.id for x in ModelA.rf]) Would there be a difference in number of DB calls in case of A and B -
Ajax: How to send FormData inside of json object
To give you a better understanding consider my ajax request: $.ajax({ url: '{% url "validate-upload-single" %}', type: "POST", data: JSON.stringify({ 'mainForm': Myform, 'currentForm': 1, }), dataType: 'json', // response type Where: var Myform = new FormData( $(this)[0] ); The problem is that when i send the request, i get back an empty 'dict' on the server side. Im using Django as my backend DJANGO VIEW: print('SORTING THE POST REQUEST') body = request.body.decode('utf-8') serialized = loads(body) print(f'POST: {request.POST}') print(f'Body: {body}') print(f'Serialized: {serialized}') RESULT: SORTING THE POST REQUEST POST: <QueryDict: {'{"mainForm":{},"currentForm":1}': ['']}> Body: {"mainForm":{},"currentForm":1} Serialized: {'mainForm': {}, 'currentForm': 1} I've tried $("form").serializeArray() but this only return text data, files seem to be missing -
Save Django's tests results to real database
Triyng to run Selenium tests in Django. I need to get data from the database, update it and save it to the real database. What will be the best way to achive that? -
Getting the Network Console Response object in django rest framework api using Reactjs
Hello Guys Iam making an app in reactjs that will allow users to upload csv and xlsx files and give them alerts if the files fail to upload so am trying to get the object from the response in network console when you inspect the page and to be able to display the message on the js page for users so that they wont have to right click to inspect the page, click network and response to see the error or succes messages what I want them to do is if a file fails to upload that message object should be presented on the page. Here is a sample code: import React from "react"; import PropTypes from "prop-types"; import axios from 'axios' class Uploaddatastore extends React.Component { constructor(props) { super(props); this.state = { UploadNotification: [] } } componentDidMount(){ let notificationComponent = this; axios.get("http://127.0.0:8000/uploads/file_upload/") .then(function (response) { console.log(response); console.log(response.data); notificationComponent.setState({ UploadNotification: response.data.items }); }) .catch(function (error) { console.log(error); }); } render() { let renderItems; if (this.state.UploadNotification.length) { renderItems = this.state.UploadNotification.map(function(item, i) { return <li key={i}>{item.title}</li> }); } return ( <div className="App"> <div className="form-group mt-3"> <label className="mr-2">Upload your File:</label> <input type="file" name="title" accept=".xlsx , .csv" multiple onChange={(e) => this.handleFile(e)} filetype={'.csv,.xlsx'} /> </div> … -
Django: How to make many filters on the same related field?
I have a Django model called Format, that has some fields, and another model called DepartmentFormat that looks like this class DepartmentFormat(models.Model): department = models.ForeignKey(Department, on_delete=models.CASCADE) format = models.ForeignKey(Format, on_delete=models.CASCADE, related_name='format_dptfmt') status = models.ForeignKey(FormatStatus, on_delete=models.CASCADE, null=True, default=None) In my view to display the formats, I have some filters, like this: class FormatFilter(FilterUserMixin): # SOME OTHER FILTERS class Meta: model = Format fields = ("business_type", "rfc", "economic_sector", "cellphone", "format_dptfmt__status__status") However, the same Format can have multiple DepartmentFormat objects related to it, because they can have the same Format, but different Department. For example, this is a possible case: A format has two DepartmentFormat objects related to it. One of those has "Ecology department" as its department, and another has "Public works department" as its department. There exists a third Department, which has still no DepartmentFormat object related to it. So this same Format could have zero, one, two or three DepartmentFormat objects related to it, with each of the Department objects that exist. What I'm after, is having three filters, one for each of the departments. The first one, for instance, could filter only those Formats for which there is a related DepartmentFormat that happens to have "Ecology department", and the … -
How to get a SQL queryset in Django?
I am new to django, and now I am making a query to my models, the query is already made in mysql. How can I get the following SQL queryset in Django? Query made in mysql MySql SELECT `ae`.`id` AS `event_id`, `ae`.`startdatetime` AS `startdatetime`, `ae`.`enddatetime` AS `enddatetime`, `ae`.`active` AS `active`, `ae`.`logged_user` AS `logged_user`, `aa`.`id` AS `area_id`, `aa`.`area_name` AS `area_name`, `ad`.`id` AS `device_id`, `ad`.`device_name` AS `device_name`, `ad1`.`user_description` AS `digitaloutput_user_description`, `al`.`user_description` AS `lighstate_user_description`, CONCAT(`ad1`.`user_description`, ' - ', `al`.`user_description`) AS `do_lightstate_user_description`, `ad1`.`color` AS `color`, `ae`.`shift_startdatetime` AS `shift_startdatetime`, `ae`.`shift_enddatetime` AS `shift_enddatetime`, `ae`.`shift_name` AS `shift_name` FROM ((((`andon_event` `ae` JOIN `andon_lightstate` `al` ON ((`ae`.`lightstate_id_id` = `al`.`id`))) JOIN `andon_device` `ad` ON ((`ae`.`device_id_id` = `ad`.`id`))) JOIN `andon_area` `aa` ON ((`ae`.`area_id_id` = `aa`.`id`))) JOIN `andon_digitaloutput` `ad1` ON ((`al`.`do_id_id` = `ad1`.`id`))) These are my class models: MODELS Event Model: class event(models.Model): device_id = models.ForeignKey('device', on_delete=models.CASCADE, null=True) startdatetime = models.DateTimeField(auto_now=False, auto_now_add=False, null=False) enddatetime = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) active = models.BooleanField(default=False) logged_user = models.CharField(max_length=100, null=True) shift_startdatetime = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) shift_enddatetime = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) shift_name = models.CharField(max_length=100, null=True) . . . Devie Model: class device(models.Model): device_name = models.CharField(max_length=50, unique=True, help_text='Station Name', validators=[validate_slug]) Area Model: class area(models.Model): area_name = models.CharField(max_length=100, unique=True, default='New Unnamed Area', help_text='Area Name') Digitaloutput Model: class digitaloutput(models.Model): user_description = … -
Django Rest Framework - Filter fields of nested relationships
I want to return a nested representation of Customer with Image objects, where a Customer can have many Images. Currently, the nested representation returns ALL images from the Image queryset for each Customer object as shown below. How can I show only related Image(s) under each Customer object instead? # 'images' field Currently returns all images rather than related images to the customer id. { 'id': 1, 'name': 'John Doe', 'images': [ {'id': 1, 'name': 'foo.jpg', 'customer': 1}, {'id': 2, 'name': 'bar.jpg', 'customer': 2}, {'id': 3, 'name': 'foobar.jpg', 'customer': 3}, ... ], } ... This is my current setup Example Models class Customer(models.Model): name = models.CharField() class Image(models.Model): name = models.CharField() customer = models.ForeignKey( Customer, on_delete=models.CASCADE) Example Serializers class CustomerSerializer(serializers.ModelSerializer): # My Customer nested relationship is expressed using ImageSerializer as a field images = ImageSerializer(many=True) class Meta: model = Customer fields = ('id', 'name', 'images') read_only_fields = ('id',) class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' read_only_fields = ('id',) Please let me know if my question is unclear and I will update my question. Thank you. -
Celery asynchronous in django does not work
I am trying to create an asynchronous task using celery, but I am not achieving success. I have a task that sends emails: @shared_task() def send_email_example(email_id): ... I call it using the delay() method: class SomeModelExample: ... def example(self): ... send_email_example.delay(self.id) Locally, I run the celery and can use it. However, in my server, when I use the method that calls the function it takes more than 30 seconds and I receive a status code 502. I hope that my celery setup is ok, because my periodc tasks works. -
Is a mailto URL with slashes still valid?
I am using a subclassed Django URLField to perform some validation on clicked URLs. I added mailto as one of the supported URLValidator default_validators: class MyURLField(forms.URLField): default_validators = [ validators.URLValidator( schemes=['http', 'https', 'ftp', 'ftps', 'mailto'] ) ] class MyForm(forms.Form): url = MyURLField(required=True) form = MyForm({'url': 'mailto:test@example.com'}) if not form.is_valid(): raise Exception() clean_url = form.cleaned_data['url'] print(clean_url) # this prints 'mailto://test@example.com' Is a mailto URL still valid with the two extra protocol slashes? mailto:test@example.com versus mailto://test@example.com (what Django produces) -
Django Models compare 2 model and filter
i want to get the model details with corresponding another model my models.py class Device(models.Model): DeviceName = models.CharField(max_length=50, null=True, default=None, blank=True) Camera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId') class Meta: db_table = "Device" class Camera(models.Model): CameraId = models.AutoField(primary_key=True, db_column='CameraId') CameraName = models.CharField(max_length=50) class Meta: db_table = "Camera" i want my camera details that is the camera details that not saved in Device foreign key (means the camera details that not used the foreign key for device) -
Form with bootstrap
I'm trying to make the create form look better but it just doesn't work. It shows fine but when I try to submit it doesn't do anything. I've already tried with different forms of one field, I think I can't make it work because this has file fields and foreign keys, etc. Why it doesn't work? forms.py class Lcreate(forms.ModelForm): class Meta: model = Auction fields = ('name', 'img', 'description', 'category', 'starting_bid') widgets = { 'description' : forms.Textarea(attrs={ 'rows': '5', 'cols': '90', 'maxlength': '500', }), 'name' : forms.Textarea(attrs={ 'rows': '1', 'cols': '100', 'maxlength': '30', }), } views.py @login_required(login_url="login") def create(request): if request.method == "POST": form = Lcreate(request.POST or None, request.FILES or None) if form.is_valid(): user = request.user starting_bid = form.cleaned_data["starting_bid"] description = form.cleaned_data["description"] name = form.cleaned_data["name"] img = form.cleaned_data["img"] category = form.cleaned_data["category"] listing = Auction(user=user, starting_bid=starting_bid, description=description, name=name, img=img, category=category) listing.save() return redirect('index') else: form = Lcreate() return render(request, "auctions/create.html", { "form": Lcreate, "categories": Category.objects.all() }) html <div class="space"></div> <div class="create-form"> <h1>Create Listing</h1> <form method="POST" enctype="multipart/form-data"> {%csrf_token%} <div class="form-group"> <label for="name">Title</label> <input autofocus class="form-control" id="name" type="text" name="name" placeholder="Title"> <div class="space"></div> <label for="img">Image</label> <input type="file" id="img" name="img" class="form-control-file"> <div class="space"></div> <label for="description">Description</label> <textarea class="form-control" name="description" id="description" rows="3" placeholder="description"></textarea> <div class="space"></div> <label for="category">Category</label> … -
django throwing ImproperlyConfigured error while importing data using 'django-import-export' library
I'm trying to import data into a model through django admin using dajngo-import-export library, though I'm facing "Improperly Configured" error. This is the error message: ImproperlyConfigured at /admin/pages/quote/import/ No exception message supplied Request Method: POST Request URL: http://127.0.0.1:8000/admin/pages/quote/import/ Django Version: 3.0 Exception Type: ImproperlyConfigured Exception Location: C:\Users\Dell\.virtualenvs\read_bus-UfMQ3ck8\lib\site-packages\import_export\resources.py in import_data, line 737 Python Executable: C:\Users\Dell\.virtualenvs\read_bus-UfMQ3ck8\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\\Users\\Dell\\Downloads\\read_bus', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\Scripts\\python37.zip', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\DLLs', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\Scripts', 'c:\\users\\dell\\anaconda3\\Lib', 'c:\\users\\dell\\anaconda3\\DLLs', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages', 'C:\\Users\\Dell\\Downloads\\read_bus', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf',] I'm following the documentation as mentioned here. This is the admin.py file: class QuoteResource(resources.ModelResource): class Meta: model =Quote import_id_fields=('quote',) fields = ('quote','book','author',) class QuoteAdmin(ImportExportModelAdmin): list_display=('quote','book','author') resource_class =QuoteResource admin.site.register(Quote,QuoteAdmin) I've tried with and without 'QuoteResource', without success. I'm successfully able to export the data from admin. But facing challenge during import. Snip of admin during import: Following is one of the various ways in which I tried to import data: Does it has somthing to do with the django settings or the csv data format? Let me if you need any more information. -
Will migrate zero save my migrate --fake mishap?
I have Django webapplication running on Heroku with Heroku Postgres. A few days ago I made a few changes to an app's models, adding and then removing unique=True to some model fields (among other things, just messing around a bit) and making some migrations. This surely broke something, and unfortunately I didn't discover this until a few days later, after I had made a lot of additional migrations in my local db. The only way I was able to fix it was with a: python manage.py migrate --fake This worked out OK on my local/dev postgres, but in production it is still broken when I try to make migrations and migrate. When running migrate: django.db.utils.ProgrammingError: table "publicinteraction_smoothmessage_extra_software" does not exist Since it has been a few days, I don't know exactly which migration I faked or not, and the section in Django docs about "risk of manually having to correct --fake" was also seen too late... Will it help to run python manage.py migrate publicinteraction zero or will this result in my data getting lost? This is my first project in production with real users and encountering such issues is all new to a self-taught developer in Python and Django. … -
NoReverseMatch at /'blog' is not a registered namespace
I am trying to link two pages. Page files are home.html and pageOne.html. I am getting "NoReverseMatch at /'blog' is not a registered namespace". I am using django. When I first created the app, I named it artclBlog, I then created a templates folder and another folder within that one, this one I named blog. I think I should have kept these two names the same, this may have caused some confusion in my code. pic of error my views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def home(request): blogs = Blog.objects.order_by('-date') return render(request, 'blog/home.html', {'blogs': blogs}) my urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from artclBlog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('<int:blog_id>/', views.PageOne, name='PageOne') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my models.py from django.db import models class Blog(models.Model): title = models.CharField(max_length=200, default='') summary = models.CharField(max_length=200, default='') pageOne = models.TextField(default='') pageTwo = models.TextField(default='') pageThree = models.TextField(default='') pageFour = models.TextField(default='') date = models.DateField(default='') def __str__(self): return self.title -
Django Forms Crispy- change, clear and currently fields do not appear
I am not Software Engineer, I hate programming , but I would like to know how to solve this problem. PLEASE When I try to change a model instance using a form, the fields/messages/text Currently, Change, Clear for a File or Image are not appearing What is the solution? models.py class Part(models.Model): ... image = models.FileField(upload_to='images/', blank=True) datasheet = models.FileField(upload_to='files/', blank=True) ... form.py class PartForm(forms.ModelForm): class Meta: model = Part exclude = ["owner"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs['autocomplete'] = 'off' self.helper.form_method = "POST" self.helper.layout = Layout( Row( ... ), 'description', 'detailed_description', Row( ... ), Row( .... ), Row( Column('image', css_class='form-group col-md-6 mb-0'), Column('datasheet', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Submit('submit', 'Submit') ) urls.py urlpatterns = [ path("<uuid:pk>/change-part/", add_or_change_part, name="manage_change_part"), ] views.py def add_or_change_part(request, pk=None): part = None if pk: part = get_object_or_404(Part, pk=pk) if request.method == 'POST': form = PartForm(request.POST, request.FILES, instance = part) if form.is_valid: form = form.save(commit=False) form.owner = request.user form.save() return redirect ('part_main') else: form = PartForm(instance=part) context = {"form": form} return render(request, 'part_form.html', context) part_form.html {% extends '_base.html' %} {% load static %} {% load crispy_forms_tags %} {% block title %} {% endblock title %} {% block page_header %} {% endblock page_header … -
Django doesn't recognize my custom update method in a serializer
i'm trying to patch an object in an app in Django Rest Framework But im getting the following error AssertionError at /requirements/material/12/ The .update() method does not support writable nested fields by default. Write an explicit .update() method for serializer requirement.serializers.MaterialRequirementDetailSerializer, or set read_only=True on nested serializer fields. The main problem here is that i already create an explicit update method. Here is my View.py where i make the patch request def patch(self, request, pk, format=None): requirement = models.MaterialRequirement.objects.get(pk=pk) serializer = serializers.MaterialRequirementDetailSerializer( requirement, data = request.data, partial = True ) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and here is the serializer that i'm using class MaterialRequirementDetailSerializer(serializers.ModelSerializer): owner = UserListSerializer() construction_site = ConstructionSiteListSerializer() quotations = QuotationListSerializer( source='quotation_set', many=True, read_only=True ) items = RequirementItemSerializer( many=True ) state = serializers.CharField(source='get_state_display') type = serializers.CharField(source='get_type_display') delivery_time = serializers.CharField(source= 'get_delivery_time_display') class Meta: model = MaterialRequirement fields = ( 'id', 'code', 'state', 'type', 'deadline', 'description', 'observation', 'owner', 'construction_site', 'delivery_date', 'delivery_time', 'quotations', 'items' ) def update(self, instance, validated_data): requirement = super().update(instance, validated_data) items = self.context.get('items', None) if items: for item in items: if 'id' in item.keys(): requirement_item = RequirementItem.objects.get(pk=item['id']) if requirement_item: requirement_item.name = item['name'] requirement_item.description = item['description'] requirement_item.is_urgent = item['is_urgent'] requirement_item.quantity = item['quantity'] requirement_item.save() else: RequirementItem.objects.create(requirement … -
How do you access parent model fields in forms.py?
For context, I'm trying to create a form that allows users to upload info about their own custom Pokemon. Basically, they are creatures that you can catch, name, and level up. To draw a comparison, it is a similar concept to dogs; there are labradors, German Shepherds, huskies, etc. that would be variations of a base Dog model, but then each individual would have a name and other defining characteristics. I've created Pokemon and CustomPokemon models and imported the latter into my forms.py file. I'm trying to access some parent fields but am unable to: from django import forms from .models import CustomPokemon class PokemonForm(forms.ModelForm): class Meta: model = CustomPokemon fields = ['pokemon.poke_name', 'name', 'level'] The poke_name field is inherited from the base model while the other two fields belong to the CustomPokemon model. I'm getting this FieldError: Unknown field(s) (pokemon.poke_name) specified for CustomPokemon. The issue isn't resolved by using poke_name, so I'm curious how I can access the parent model's fields so they can be displayed in the form. -
Can I block users from accessing my API url?
I am making an Ecommerce website in DJango/Django-Rest-Framework. Now for update/delete/add to cart operations I am using AJAX so that JSON is sent dynamically to the API and data is serialized there. Now I have added permission that user can't see other people's API data but I don't want user to see his API data as well. I just want him to use the website while AJAX is done in the background.