Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
innerHTML not working for select tag when i want to change new options
html code: <div class="row clearfix"> <div class="col-sm-12"> <div class="form-group"> <select id="domain" class="form-control show-tick" onchange="myFunction1()"> {% for item in domains %} <option value=" {{item.0}} ">{{item.1}}</option> {% endfor %} </select> </div> </div> </div> <div class="row clearfix"> <div class="col-sm-12"> <div class="form-group"> <select id="2"> <option></option> </select> </div> </div> </div> js function: <script> function myFunction1() { x = document.getElementById("domain").value; document.getElementById("2").innerHTML += "<OPTION>1</OPTION>"; alert(x); } </script> I am trying to change the drop-down box with id set as 2 when an on-change function is called in other drop-down box. Code looks good but i cant see the new options added. -
Django error SyntaxError: Non-ASCII character '\xff'
I am trying to run the django_tables2 tutorial but it shows error. Unhandled exception in thread started by <function wrapper at 0x7fd6677b4c80> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 28, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 86, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 95, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 38, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_tables2/__init__.py", line 20, in <module> from .tables import Table, table_factory File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_tables2/tables.py", line 1 SyntaxError: Non-ASCII character '\xff' in file /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_tables2/tables.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details -
i am making a django website with multiple forms also used foregin key ValueEror :The view Capp.views.InsertProduct didn't return anHttpResponseobject
i am making a django website with multiple forms also used foregin key(user_id) to link one form with other in the database but at the last i get value error the error is:Exception Type: ValueError Exception Value: The view Capp.views.InsertProduct didn't return an HttpResponse object. It returned None insteated , the following is view.py file code(not complete code but only where error can lie)models.py part def InsertProduct(request): if request.method == 'POST': if request.POST.get('user_id') and request.POST.get('pname') and request.POST.get('pcategory') and request.POST.get('pdetails') and request.POST.get('foundedin') and request.POST.get('orderoftest') and request.POST.get('t1') and request.POST.get('t2') and request.POST.get('t3') and request.POST.get('f1') and request.POST.get('f2') and request.POST.get('f3') and request.POST.get('f4') and request.POST.get('f5'): saveproduct = ProInsert() saveproduct.user_id = request.POST.get('user_id') saveproduct.pname = request.POST.get('pname') saveproduct.pcategory = request.POST.get('pcategory') saveproduct.pdetails = request.POST.get('pdetails') saveproduct.foundedin = request.POST.get('foundedin') saveproduct.orderoftest = request.POST.get('orderoftest') saveproduct.t1 = request.POST.get('t1') saveproduct.t2 = request.POST.get('t2') saveproduct.t3 = request.POST.get('t3') saveproduct.f1 = request.POST.get('f1') saveproduct.f2 = request.POST.get('f2') saveproduct.f3 = request.POST.get('f3') saveproduct.f4 = request.POST.get('f4') saveproduct.f5 = request.POST.get('f5') checkpname = ProInsert.objects.filter( pname=saveproduct.pname).first() if checkpname: msgpname = messages.success(request, 'The user with Product Name ' + request.POST['pname']+' already exist...!') return render(request, 'product_details.html', {'msgpname': msgpname}) saveproduct.save() messages.success(request, 'Product Added..!') return render(request, 'product_details.html') else: return render(request, 'product_details.html') -
Module "django.core.mail.backends.console" does not define a "EmailBacked" attribute/class
i am trying to code reset password of my web application now I am facing this error mentioned in tagline. in my settings.py I have. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBacked' my URLs are: path('password-reset/', auth_views.PasswordResetView.as_view(template_name='app/password_reset.html', form_class=MyPasswordResetForm), name='password_reset'), path('password-reset-done/', auth_views.PasswordResetDoneView.as_view(template_name='app/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='app/password_reset_confirm.html', form_class=MySetPasswordForm), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='app/password_reset_complete.html'), name='password_reset_complete'), -
how can I serialize a multi user model that uses proxy
so I am setting up an app that has 3 types of user admin, customer and Agent I have my model setup this way class UserManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email') user = self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) try: user.save(using=self._db) except IntegrityError: raise IntegrityError('A user already uses this email') return user def create_superuser(self, email, name, password=None): user = self.create_user(email, name, password=password) user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): class Types(models.TextChoices): COSTUMER = "CUSTOMER", "Customer" AGENT = "AGENT", "Agent" type = models.CharField(_('Type'), max_length=50, choices=Types.choices, default=Types.CUSTOMER) email = models.EmailField(_('Email of the user'), unique=True) name = models.CharField(_('Name of the user'), max_length=100) phone_number = PhoneNumberField(_('Phone number of the user'), blank=True, null=True, unique=True) date_joined = models.DateField(_('Date joined'), auto_now_add=True) last_login = models.DateTimeField(_('last login'), null=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.email class CustomerManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args **kwargs).filter(type=User.Types.CUSTOMER) class AgentManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args **kwargs).filter(type=User.Types.AGENT) class Customer(User): '''proxy class for registering customer''' objects = CustomerManager() class Meta: proxy = True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.CUSTOMER … -
How can I mix __str__ and @property?
I have question: I have some property decorator on model in Django: @property def replace_name(self): if not self.name: if self.pay: return self.registration_number else: return self.number else: return self.name When I get my data on page - If I do not use NAME.It means that when I enter data I leave field Name empty it returns me ID of model!But I want that it will return me registration_number! How I understand on this involves this method: def __str__(self): return f'{self.name}' Now it looks like this!But I have idea to added here: def __str__(self): return f'{self.name}{self.registration_number}{self.number}' After I added this it returns me what I want!This data!But!The problem is that @property does not working!It is returns me all data !How to mix this 2 methods to have normal working code?Can anybody explain!I know this way in str add is not correct!Please help! -
django forms .clean method is not getting invoked
Django forms clean method not getting invoked, I read django's full clean doc and other relevant stackoverflow questions. but could not get the answer at all. Frankly speaking, I am not getting what documentation is saying. In my case, few custom checks are required on my hidden form fields, So I need to call django forms .clean method, but .clean is not getting invoked. function is going to clean_client but not in .clean. Looks like its going to .clean_client through full_clean method, but not sure how to add custom checks for my hidden form fields. Here is my forms.py class EnquiryForm(forms.ModelForm): name = forms.CharField(label='Full name', required=True, max_length=100, widget=forms.TextInput(attrs={ 'class': 'form-control input-custom', 'id': 'name', }) ) mobile = forms.CharField(label='Mobile', required=True, widget=forms.TextInput({ "type": "tel", "class": "form-control input-custom", "name": "mobile", "placeholder": "eg. 9823523461" })) ... hidden_enq_code = forms.CharField( required=False, widget=forms.HiddenInput()) hidden_bhks = forms.CharField(required=False, widget=forms.HiddenInput()) hidden_conditions = forms.CharField( required=False, widget=forms.HiddenInput()) class Meta: model = Enquiry fields = ('client', 'if_other', ..., 'notes') def clean(self): print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>In Clean Method") self.cleaned_data = super().clean() client = self.clean_client() if not client: raise forms.ValidationError("Invalid client details", code="invalid") self.cleaned_data['client'] = client self.clean_hidden_fields() return self.cleaned_data def clean_hidden_fields(self): try: hidden_bhks = self.cleaned_data['hidden_bhks'] hidden_conditions = self.cleaned_data['hidden_conditions'] if hidden_bhks: hidden_bhks = hidden_bhks.split(',') self.cleaned_data['bhk'] = BHK.objects.filter( id__in=hidden_bhks) … -
how to make the slug auto in making URL articles in Django
im being making a blog i need to make the slug automatic in making the URL as title of each article without that i have everytime to copy the title and put it and edit it to make it slug manually -
python-django not able to create dir and file
This code snippet gives me error , i don't have idea why it's throwing error because i am opening file '+w' so if file not present there then python will create. response is file path and default_storage from Django anyone have idea why it is not working with default_storage.open(response, 'w+') as csv_file: writer = csv.writer(csv_file) writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) log.info(writer) -
Django: right-align output in admin listview
How can I output a DecimalField right-aligned in Django admin listview? It makes much more sense to have column of, say, prices, right-aligned. I tried this: django align right cannot align, but it doesn't work, presumably, because it doesn't change the output behaviour. -
how to check if I got the right function
I have a model that has 2 foreign keys, therefore I also have a function in view which has to get one of 2 different functions. That's what I want to verify and I wonder how it is possible? models.py class HotelFacilities(models.Model): name5 = models.ForeignKey(HotelSingleRoom, related_name='name', on_delete=models.CASCADE, blank=True, null=True) name_5 = models.ForeignKey(HotelDoubleRoom, related_name='name_2', on_delete=models.CASCADE, blank=True, null=True) views.py @login_required def hotel_facilities(request, id): if request == 'HotelSingleRoom.objects.get(id=id)': hotel = HotelSingleRoom.objects.get(id=id) else: hotel = HotelDoubleRoom.objects.get(id=id) form = HotelFacilitiesForm() if request.method == "POST": form = HotelFacilitiesForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.name5 = hotel data.save() return redirect('hotel:photos', data.id) context = {'form':form,} return render(request, 'hotel/facilities.html', context) I just tried this and of course it is not working... :) -
Django overriding the save method gives error
Disclaimer, I'm still new to a lot of concepts in Django so patiance please. So what I'm trying to do is the value of name from Counter model, assign it to the value of code from Order model. In the counter, I run a function that checks if the code year is 2020, then it gets me a value and concatinates that to make up the name of the Counter. Now when I run this code, it all fills up and instead of getting a value for the code, i get this as the value: django.db.models.query_utils.DeferredAttribute object at 0x04388250> Furthermore, I did some debugging, and when I ran a debug line on the save method in the Order model, it gave me this: queryset = {NameError}name 'queryset'is not defined. But I'm not sure what I need to do exactly. Any help would be appreciated, thanks. class Order(model.Models): code = models.CharField(unique=True) code_year=models.IntegerField def save(self, *args, **kwargs): self.code = Counter.name super().save(*args, **kwargs) class Counter(models.Model): name = models.CharField(max_length=10) value = models.IntegerField def save(self, *args, **kwargs): if Order.code_year == 2020: try: c_2020 = Order.objects.latest('id').id + 1 except Order.DoesNotExist: c_2020 = 1 self.value = c_2020 temp_value = f"P - {c_2020} - 2020" self.name = temp_value … -
Unable to put spacing between rows in Bootstrap while using Django framework
I've read a lot of answers and tried their solutions but nothing seems to work. Here is my code. I've tried using mt-10, row-padding and other custom css using margin-top:10. But nothing works.The image shows no space between rows using mt-10 {% block content %} {% for playlist, progress in user_playlists.items %} <div class="row justify-content-between rounded m-auto"> <div class="col-6 m-auto"><a> {{playlist}}</a></div> <div class="col-6 m-auto"><a>{{ progress }}</a></div> </div> {% endfor %} {% endblock %} -
How to cache a dictionary in Django?
I am using Django as my Webframework. I have a method that takes really long ~10 sec to complete. It returns a Dictionary which I then display in the templates. This method is called on a POST request after a button click. When the user reloads the page the View gets a GET request and all the results from before dont get displayed anymore. How can I somehow cache the Dictionary so I can even display it on a get request when the user once did the POST request? -
Docker django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution
Seems like a common error. I followed every possible suggestion on Stackoverflow(adding links, network etc), but it makes no difference in my case. I am running on Windows. My Dockerfile: #Pull base image. FROM python:3.9.5-slim #Usefull to get logs ENV PYTHONUNBUFFERED 1 #Make local dir RUN mkdir -p /app #set as the working directory WORKDIR /app #https://luis-sena.medium.com/creating-the-perfect-python-dockerfile-51bdec41f1c8 COPY requirements.txt . #now copy all the files in this directory to \code ADD . . #https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ RUN apt-get update && \ apt-get install -y postgresql-server-dev-all gcc python3-dev musl-dev && \ pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app USER app #CMD python manage.py runserver CMD gunicorn --bind 0.0.0.0:8000 app.wsgi:application -k eventlet Next, my docker-compose.yml: services: web: build: . ports: - "8000:8000" volumes: - .:/app links: - db:db container_name: heritageapi_web_1 depends_on: - db networks: - heritage-network db: image: postgres:13.3 container_name: db restart: always networks: - heritage-network environment: POSTGRES_DATABASE: admin POSTGRES_USER: root POSTGRES_PASSWORD: root POSTGRES_ROOT_PASSWORD: root volumes: - .dbdata:/var/lib/postgres ports: - "32768:5432" networks: heritage-network: driver: bridge My .env: DB_NAME=admin DB_USER=root DB_PASSWORD=root DB_HOST=db DB_PORT=5432 Finally my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } -
(python) Github Actions test selenium copy paste
I am testing my python application with e2e tests and use github actions as part of my CI. Normal selenium tests work totally fine. I added a click to copy functionality and want to test it via a unit test. So far I am using pyperclip to do this: import pyperclip link = pyperclip.paste() assert link == "target link" Locally on my machine (OSX) everything works fine. Unfortunately, I am not able to get this library working with ubuntu on github actions. I get this error: Pyperclip could not find a copy/paste mechanism for your system. Please see https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error for how to fix this. I've checked the page but I am not able to get it working. Does someone know a way how to access the clipboard in github actions? -
show price based on product by selecting form option
I have a model for product and purchase. I want whenever a user select product name, the field of price will be auto filled. Thanks in advanced. models.py class ProductDetails(models.Model): id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100, unique=True) purchase_price = models.DecimalField(max_digits=7, decimal_places=2) dealer_price = models.DecimalField(max_digits=7, decimal_places=2) retail_price = models.DecimalField(max_digits=7, decimal_places=2) remarks = models.CharField(max_length=255, blank=True) def __str__(self): return self.product_name class TemporaryData(models.Model): id = models.AutoField(primary_key=True) product_id = models.ForeignKey(ProductDetails, on_delete=models.CASCADE) price = models.DecimalField(max_digits=7, decimal_places=2) quantity = models.IntegerField() amount = models.DecimalField(max_digits=7, decimal_places=2) def __int__(self): return self.id Forms.py class TempoForm(forms.ModelForm): class Meta(): model = TemporaryData fields = '__all__' widgets = { 'product_id':forms.Select(attrs={'class': 'form-control', 'id': 'select1'}), 'price': forms.TextInput(attrs={'class': 'form-control', 'id': 'select2'}), 'quantity': forms.TextInput(attrs={'class': 'form-control'}), 'amount': forms.TextInput(attrs={'class': 'form-control'}), } Views.py def tempoData(request): form = TempoForm() tempo_data = TemporaryData.objects.order_by('id') if request.method == 'POST': form = TempoForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('purchase_form') else: print('Please fill up the form accurately') return render(request, 'product/purchase_form.html', {'form': form, 'tempo_data': tempo_data}) I need the price data from database as per product ID. I need full code so you can also provide me any use full link. Thanks. -
DropzoneJS formData is empty when trying to append new data for S3 Direct upload
I'm working with Django and DropzoneJS, trying to get direct client-to-s3 uploads to work. Currently, I keep getting a 405 Method Not Allowed, though I've specifically set my CORS policy to allow POST. I am dynamically settings two fields on the file object, rdata and rurl, which contain the data necessary to POST to S3, and the URL to post to. rurl is used to POST to, rdata contains all the other stuff like acl: public-read and Content-Type My Dropzone code: <div id="dropzone" class="dropzone"></div> <script> var myDropzone, sendingFiles = false, varMaxFiles = 4; loadJS('vendor/dropzone.min.js', function () { Dropzone.autoDiscover = false; myDropzone = new Dropzone('#dropzone', { {% if existing_files %} init: function () { var myDropzone = this; // Handle displaying existing files }, {% endif %} accept: function (file, done) { file.postData = []; var xhr = new XMLHttpRequest(); xhr.open("GET", "{% url 'sign-s3' experience.id %}?file_name=" + file.name + "?file_type=" + file.type); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { var response = JSON.parse(xhr.responseText) debugger; file.rdata = response.data file.rurl = response.url } } } xhr.send(); done(); }, url: "/", acceptedFiles: ".jpg,.jpeg,.png,.avi,.mov,.m4v,.mp4,.mpeg", addRemoveLinks: true, autoProcessQueue: false, autoQueue: true, maxFiles: varMaxFiles, parallelUploads: 5, thumbnailWidth: 120, maxFilesize: … -
How should I manage my images for my django app
Here I am once again asking a question that might seem stupid: I am new to web development. So far I've made some practice projects with Django and I've deployed two projects so far as github pages but they were simple static websites (no django). Now I'm making a web application for my mom's business with Django. I don't know what I should do with all the images I need for the website. In the past I have uploaded all jpg and png images to imgur and copied the link in my static websites html But now I have more images and I am going to pay for a server for them application. I have two types of images: Images that will always appear on the page. Because that's part of the design Images that the admin can upload when creating a new post for the page So my question is: Should I have all images in the statics folder for my application? And call them like this: <img src="{% static 'website/images/home-slider/myimage.css' %}"> And for the other images should I save a similar path in the database? I just have no idea if things should be done different for production -
django - adding object to manytomany: Cannot add "<object>": the value for field "other object" is None
I am using a form to retrieve a TextField. I then parse each line of the textfield to create students and save a Student object. Finally I add students to a Classroom object. This worked when student was a foreignkey to classroom. I changed this relationship to a ManyToMany relationship and now I get the error: Cannot add "<Student: name>": the value for field "student" is None. Models class Student(models.Model): student_first = models.CharField(max_length=30) student_last = models.CharField(max_length=30) nickname = models.CharField(max_length=31) fullname = models.CharField(max_length=60) attend = models.BooleanField(default=True) do_not_pick = models.BooleanField(default=False) student_number = models.IntegerField() email = models.EmailField(max_length=50) class Classroom(models.Model): """The gradebook is split into courses, classes and students""" classroom_name = models.CharField(max_length=10) course = models.ForeignKey(Course, on_delete=models.CASCADE) students = models.ManyToManyField(Student) View def addmultistudent(request, classroom_id): """Add multiple students at once.""" classblock = get_object_or_404(Classroom, pk=classroom_id) context = {'classblock': classblock} if request.method == 'POST': form = StudentInputForm(request.POST) if form.is_valid(): s = form.save() input_list = [] input_list = s.name_list.split('\n') # the for returns a list of students with student number, fisrt_name, last_name in each line for line in input_list: # remove the carriage return line = line.strip('\r') # removes double quotes line = line.translate({ord(c): None for c in '"'}) # ignore the first line which is a header starting … -
How can I create a form with unknown number of columns and rows?
I don't know if I will be able to explain this very well, so please bear with me, and I will update where/when needed as much as I can. I have a Django app that is designed to take in data from users for products that we need to configure. The products are split into main categories of main products, which are then further split by customer. Main products have default settings, and customer products have SOME of these settings changed, plus some others not listed by the main product. Each customer may have multiple variations of the product too. Example of products: Main Product A | |-> Customer A Product A1 |-> Customer A Product A2 | |-> Customer B Product A1 |-> Customer B Product A2 Main Product B | |-> Customer A Product B1 |-> Customer A Product B2 | |-> Customer B Product B1 |-> Customer B Product B2 What I need/want, is a table for staff to enter the needed settings for a given customer, without the app knowing how many settings are needed, and how many customer products there are, in advance. Example: Setting Product A1 + Low Power TRUE Delayed Start 5 seconds … -
Django how to get inbound data of html fields when not using froms in views?
I am using Django default login in my views. When user typing wrong password or username then it's showing the error message but the data those entered by user are disappeared. I want to to keep the wrong data in my html username and password fields. here is my views.py: def login_view(request): if request.user.is_authenticated: return redirect('blog:my-account') else: if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('blog:my-account') elif username == "": messages.info(request, "Please enter username") elif password == "": messages.info(request, "Please enter password") else: messages.info(request, "Please enter right password or username") context = {} return render(request, 'members/login.html',context) my html fields for username and password: <input type="text" name="username" id="your_name" placeholder="username"/> <input type="password" name="password" id="your_pass" placeholder="Password"/> I tried this but didn't work : ..... else: messages.info(request, "Please enter right password or username") ......... # then trying this code for get inbound value inboud_username = username inboud_password = password context = {'inboud_username':inboud_username,'inboud_password':inboud_password} return render(request, 'members/login.html',context) #html <input type="text" name="username" id="your_name" placeholder="username" {% if inboud_username.is_bound %}value="{{ inboud_username.value }} {% endif %}"/> <input type="password" name="password" id="your_pass" placeholder="Password" {% if inboud_password.is_bound %}value="{{ inboud_password.value }} {% endif %}"/> -
Why do I receive a 403 status when I make this request?
I'm developing a web app in django and vue js. I write a function to make a request to the api, and until now everything gone well, but in my first post request I have a problem: Here there are: 1.question editor component 2. the function to connect at the api 3. the api 4. the permission classes I receive a 403 status code. -
DRF: No param in validated_data
Each account like client has a user foreign key. So my frontend send user as json string, with params, like: '{"username": "fdfdf"}'. So when I create a user, there's a 'user' param in the serializer validated_data (ClientCreateSerializer) When I update a user, there's NO a 'user' param in the serializer validated_data (ClientSerializer) My code: class UserCreateSerializer(ModelSerializer): email = serializers.EmailField(validators=[ UniqueValidator(queryset=User.objects.all()) ]) username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())], required=False # if there's no username, set as email ) first_name = serializers.CharField( max_length=30, required=False ) class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name') class AbstractAccountSerializer(serializers.ModelSerializer): user = UserCreateSerializer() def update(self, instance, validated_data): """Also save User object data""" # HERE'S NO 'user' IN VALIDATED_DATA return super().update(instance, validated_data) class ClientSerializer(AbstractAccountSerializer): class Meta: model = Client fields = [..., 'user'] class ClientCreateSerializer(ClientSerializer): class Meta(ClientSerializer.Meta): pass def create(self, validated_data): # HERE'S A 'user' IN VALIDATED_DATA user = create_user(**validated_data.pop('user')) return create_client(**validated_data, user=user) I send PATCH request to update a client (ClientSerializer) with these parameters: {"user": {"username": "Alex", "last_name": "Terrible"}} And in my update method, there's just no 'user' in validated_data -
Why decorator @property return id in Django
In my models.py I have @property decorator - but it returns me id of model. I wrote method in this decorator but it is does not work: @property def replace_name(self): if not self.name: if self.middle_name: return self.full_name if not self.middle_name: return self.address My html template: {{ object.person.replace_name }} What does it wrong here?