Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting Dockerized Django App with AWS EC2 instance
I am trying to deploy a test app to an AWS EC2 instance. My setup is a dockerized cookiecutter django app in which I use nginx instead of caddy. What I am doing is this: I created an EC2 instance with docker: docker-machine create -d amazoneec2 --amazoneec2-region=eu-central-1 machine-aws This successfully created an EC2 instance with ubuntu and docker on it. Now I pointed my docker client there: eval $(docker-machine env machine-aws) Then I up the server with docker-compose -f production.yml up It starts up, but when I enter my aws public dns (XXXX.eu-central-1.compute.amazonaws.com) in my browser I get a timeout error, so I can't access anything. I was under the assumption that my docker images should be now on the EC2 server running. Or am I missing something? I am not an expert with AWS and docker so I am a bit lost on what I could do.... Maybe docker is doing this locally and not on my EC2 instance? Any help is very much appreciated! Thanks so much! MORE INFO: The output when booting up is this: Attaching to nginx_redis_1, nginx_postgres_1, nginx_django_1, nginx_nginx_1 redis_1 | 1:C 02 Jan 2020 13:29:11.917 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis_1 | 1:C … -
How to allow normal users to add navigation menu from admin panel in Django?
I have no code. Just wanted to know how can I do that ? -
django one to one relationship deletes user model
class EngrRegModel(models.Model): engineer = models.OneToOneField(User, on_delete=models.CASCADE) skills_description = models.TextField() reg_date = models.DateTimeField(default=timezone.now) def __str__(self): return f'Engineer {self.engineer.username}' I created this EngrRegModel that have one of its field in one to one relatonship with the Django User Model, the problem is that whenever an instance of EngrRegModel is deleted, the User is deleted also, i want it to be a one way street kind of implementation, such that when a User is Deleted the instance of EngrRegModel is deleted but when an instance of EngrRegModel is deleted the user shouldn't be deleted. How do i fix this? -
Transform a base 64 encoded string into a pdf file using django rest framework
Here is how you can handle a Base64 encoded image file in a post request at the Django-based (drf also) API end which saves it as an ImageField. Let say you have a Model as follows: Class MyImageModel(models.Model): image = models.ImageField(upload_to = 'geo_entity_pic') data=model.CharField() So the Corresponding Serializer would be as follows: from drf_extra_fields.fields import Base64ImageField Class MyImageModelSerializer(serializers.ModelSerializers): image=Base64ImageField() class meta: model=MyImageModel fields= ('data','image') def create(self, validated_data): image=validated_data.pop('image') data=validated_data.pop('data') return MyImageModel.objects.create(data=data,image=image) The corresponding View can be as follows: elif request.method == 'POST': serializer = MyImageModelSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400) Notice In the Serializer I have used Implementation of Base64ImageField provided in the module django-extra-field To install this module run the command pip install django-extra-fields Import the same and Done! Send (via post method) your image as an Base64 encoded String in JSON object along with any other data you have. This is the code for image file. I need a similar code to execute operation on pdf file. -
Django : how to make rest api comment with Modelviewset
I tried to use Django's Modelviewset to implement the comment function, but there was a problem. model : class Comment(models.Model): created = models.DateTimeField(auto_now_add= True) content = models.CharField(max_length = 255, null = True) author = models.ForeignKey(User, on_delete= models.CASCADE, null = True) writer = models.CharField(max_length = 255, null = True) class Meta: abstract = True ordering = ['-id'] class TalkComment(Comment): title = "talk" post = models.ForeignKey(Talk, on_delete= models.CASCADE, null = True) serializers : class TalkCommentSerializer(serializers.ModelSerializer): class Meta: model = models.TalkComment fields = '__all__' view : class TalkCommentViewset(viewsets.ModelViewSet): queryset = models.TalkComment.objects.all() serializer_class = serializers.TalkCommentSerializer url : router.register(r'talk/(?P<id>\d+)/comment', postview.TalkCommentViewset) /api/talk/2/comment/ All I wanted was to get the comments from that one post, but all the comments are coming. How can I get a specific comment from a specific post? -
Do Django fetches ALL database objects for the paginator function and make it inefficient?
from django.core.paginator import Paginator from .model import blog b = blog.objects.all() p = Paginator(b, 2) The above code is from the official Django Pagination Documentation. Can somebody please explain me how this is not inefficient If I have a table with many records? Doesn't the above code fetch everything from the db and then just chops it down? Destroying the purpose of Pagination... -
How can I know default field name in Django-Allauth
I'm developing a web system using python3 and Django. and using Allauth module for user authentication such as login. I tried to customize CSS of the tags(input) in the form tag used the default ones of Allauth, and I could custom login.html referring to this case but I could custom the only login.html because I could know the class name and field name I have to design from another stack overflow page. and in cases I want to custom other pages like signup.html, email_confirm,I don't know what field name, a class name I should use... could someone please help to solve this case? I want to know what name do I have to design at places I changed as AAA,BBB,CCC,DDD,EEE,FFF,GGG in case of signup.html, email_confirm. and if there is something I have to add, could you please it as well. #settings.py ACCOUNT_FORMS = {'AAA': 'myapp.forms.MyLoginForm'} and #forms.py from allauth.account.forms import BBB class MyLoginForm(BBB): def __init__(self, *args, **kwargs): super(MyLoginForm, self).__init__(*args, **kwargs) self.fields['CCC'].widget = forms.DDD(attrs={'type': 'EEE', 'class': 'myclass'}) self.fields['FFF'].widget = forms.GGG(attrs={'class': 'myclass'}) my condition Python: 3.7.5 Django: 2.2.2 Django-Allauth: 0.39.1 -
Apache2 + SSL fails while using boto3
I'm running and a web application using apache2.4, django 2.2.9 and boto3 on Debian9. If apache2 runs without SSL parameters in apache conf (see below), everything works fine. With SSL parameters, web application displays 500 internal server error, and I have the following error logs: Truncated or oversized response headers received from daemon process 'example.com': /usr/local/www/my_app/wsgi.py, referer: https://example.com/my_page/ [Thu Jan 02 12:12:20.286195 2020] [core:notice] [pid 32039:tid 139769937991232] AH00052: child pid 32044 exit signal Segmentation fault (11) Quick search on "Truncated or oversized response headers" gives recommendation to add WSGIApplicationGroup %{GLOBAL} to apache.conf, but it does not help. The same is with changing number of threads to 1. Can anyone recommend anything? Thanks, Veronika Apache conf: ServerTokens Prod ServerSignature Off FileETag MTime Size Header set X-Frame-Options SAMEORIGIN <Location /> <LimitExcept HEAD GET POST PUT DELETE> order deny,allow deny from all </LimitExcept> </Location> RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} WSGIRestrictEmbedded On <VirtualHost *:443> RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.example.com$ RewriteRule ^(.*)$ https://example.com/ [R=301,L] SSLEngine On SSLProtocol +TLSv1.1 +TLSv1.2 SSLHonorCipherOrder On SSLCertificateFile /etc/apache2/ssl/my_app.crt SSLCertificateKeyFile /etc/apache2/ssl/my_app.key SSLCertificateChainFile /etc/apache2/ssl/my_app.ca-bundle ServerName example.com DocumentRoot /usr/local/www <Directory /usr/local/www/> Require all granted Satisfy Any </Directory> WSGIScriptAlias / /usr/local/www/my_app/wsgi.py WSGIPassAuthorization On WSGIDaemonProcess example.com processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup example.com <Directory … -
Django using FilterSet for filtering on boolean values
On my website I have a page displaying the list of all products with a search engine built with FilterSet. Everything is working perfectly but I want to add one more search option. I want to be able to filter all products with an attribute set to True, but when the checkbox is not marked I want to dislay all the products. With checkbox, the filtering is working but like I said I want to display all the products when the box isn't marked. I know using checkbox is a bad way to do that because when the checkbox is not marked, it considered the value to be False. So I tried using RadioSelect but nothing is working, in my filter tab I only have the title of the radioselect and a white rectangle below but I can't write on it or do anything with it. So what do I have to use ? Here is my code. The products I want to display are from the model Plat and the attribute is the attribute is_delivering from the model Chef that is linked to Plat with a foreign key in Plat. models.py class Chef(models.Model): is_delivering = models.BooleanField(verbose_name = "Livraison ?", … -
Creating multiple instances for every form in a formset
I have 2 models: Post and Date. A Post can have multiple Dates so I used formset for the latter. As expected, after submitting the form, my view expects multiple Date contained in request.POST. However, I still want to create multiple instances of Date for every form in the formset. I tried the ff code below but it doesn't produce my desired results. def create_post(request, method="POST"): DateFormSet = formset_factory(ExtraDateForm, extra=2, max_num=10, can_delete=True) if request.method == "GET": post_form = PostForm(request.GET or None) formset = DateFormSet(request.GET or None) elif request.method == "POST": post_form = PostForm(request.POST) formset = DateFormSet(request.POST) if post_form.is_valid() and formset.is_valid(): post = post_form.save() for form in formset: male_total = form.cleaned_data['male_number'] x = 0 while x < male_total: date = form.save(commit=False) date.post = post date.sex_of_professional = "Male" date.save() x += 1 -
Enable datepicker for HTML table in Django
I have an HTML table in a Django template. This table consists of three columns: start date, stop date and difference between the two. I want to include a date-picker above that allows me to set a "From" and "To" date and get the overall records for that particular time period. How can I do this? models.py: class Startdate(models.Model): user_id= models.ForeignKey(User, on_delete = models.CASCADE) start_time = models.DateTimeField() class Stopdate(models.Model): user_id= models.ForeignKey(User, on_delete = models.CASCADE) stop_time = models.DateTimeField() diff = models.DurationField(null = True, blank=True) views.py: def interface(request): data = User.objects.filter(pk__gt=1) #All users apart from the SuperUser admin store_data = [] for user in data: sta_time = Startdate.objects.filter(user_id = user) sta_data = sta_time.values_list('start_time', flat=True) sto_time = Stopdate.objects.filter(user_id = user) sto_data = sto_time.values_list('stop_time', flat=True) diff_data = sto_time.values_list('diff', flat = True) store_data.append((sta_data, sto_data, diff_data)) return render(request, 'users/interface.html', {'data': store_data}) interface.html: <table> <tr> <th> Start Time </th> <th> Stop Time </th> <th> Difference </th> </tr> {% for column in data %} <tr> <td>{{column.0}}</td> <td>{{column.1}}</td> <td>{{column.2}}</td> </tr> {% endfor %} </table> How do I include a date picker for the table, above? Also, how can I implement the functionality to set a From and To date and get back those rows between the chosen time period? -
Deploying a Django project with Docker and Nginx
Can you help me figure this out - I am trying to deploy a stage version of a Django (DRF and Mezzanine CMS combined) project using Docker, Gunicorn and NginX, however I can't load the static files from the Nginx container. I have a free domain that I use to play around - http://hidro-stage.tk, but the project only seems to load at http://hidro-stage.tk:8000/, without the static files. This makes me believe that the Gunicorn server is running, but something is wrong with the Nginx part. Here is what my docker compose file looks like: ``` version: '3.7' volumes: static_files: services: web: build: context: . dockerfile: docker/prod/web/Dockerfile.prod volumes: - .:/hidro - static_files:/static_files ports: - 8000:8000 command: gunicorn -w 4 Asociacija.wsgi -b 0.0.0.0:8000 env_file: - ./.env.prod depends_on: - db db: image: postgres environment: - POSTGRES_USER=oooooo - POSTGRES_PASSWORD=zzzzzz - POSTGRES_DB=hhhhhh ports: - 5432 nginx: build: context: . dockerfile: docker/prod/nginx/Dockerfile volumes: - static_files:/static_files ports: - 80:80 ``` It successfully builds and runs 3 containers - web, db and nginx. I run the collectstatic command automatically in the entrypoint of the web container's Dockerfile (probably there is a smarter way of doing it, so that it does not collect static files every time I run … -
How to change placeholder value on date widget in django-filter?
Finally managed to get my table filters working using django-filter. As a final piece of eye-candy I want to set the initial value of the date widget in my filter to show epoch-date (1970-01-01). I've followed the documentation but no luck. class LineItemFilter(django_filters.FilterSet): user = django_filters.ModelChoiceFilter(empty_label="User", field_name='journal_entry__user', queryset=User.objects.all()) TYPE0_CHOICES = list(journal.models.JOURNALENRTY_TYPE_CHOICES) type0 = django_filters.ChoiceFilter(field_name='journal_entry__type', choices=TYPE0_CHOICES, empty_label="Type") date_from = django_filters.DateFilter(widget=DateTypeInput(attrs={'placeholder': '1970-01-01'}), field_name='journal_entry__date', lookup_expr='gte', label='From') <!-- Epoch data set here but not showing --> date_to = django_filters.DateFilter(widget=DateTypeInput(), field_name='journal_entry__date', lookup_expr='lte', label='To') ledger = django_filters.ModelChoiceFilter(empty_label="Ledger", queryset=Ledger.objects.all()) project = django_filters.ModelChoiceFilter(empty_label="Project", queryset=Project.objects.all()) Note that my data widget is defined in forms.py: class DateTypeInput(forms.DateInput): input_type = 'date' This is what my table looks like. I've enabled sortable columns, filters, and pagination, and it's working lovely :) -
Permissions to certain groups and users?
In my project, the user can login into my application. I have two groups in my project. When User gets login into my application, I am able to recognize, the user is in which group. Now My problem is I need to denied the access to few users based on groups(example: User1 is of Group1, user1 has a accesss for viewapi1,viewapi2, etc.... and User2 is of group2, user2 has a access for viewapi8,viewapi9,etc.....). Now how to denied permissions on API level. I am not good in API's and new to this. Please help me how to do. -
Django/Python Where to find a list of available filter functions when querying
I'm currently working with a Python Django project and in there I filter data from PostgreSQL where I need to find the functions that can be called after each field followed by two underscores. Ex: birthday__year, birthday__month start_time__hour, start_time__seconds salary__gte, salary__lt Like wise from where can we get a list of all possibilities (except for foreign key fields) that can be called through the TestObj.objects.filter() ? -
I can't use my LoadBalancer service with Ingress as NodePort service - 502 Server error
I have a working LoadBalancer service on Google Cloud Platform that I want to use with Ingress. I changed the type of that service to NodePort. After that service is not working anymore. I keep getting 502 error - The server encountered a temporary error and could not complete your request. As a service api, I run Django app that is working on port 8000. Ingress yaml file: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: my-ingress spec: rules: - http: paths: - path: /* backend: serviceName: api servicePort: 8080 Service api yaml file apiVersion: apps/v1 kind: Deployment metadata: name: api spec: replicas: 1 selector: matchLabels: app: api template: metadata: labels: app: api spec: containers: - image: mkozmelj/pl_microservices_api:1.0.0-39.1 name: api ports: - containerPort: 8000 name: server protocol: TCP --- apiVersion: v1 kind: Service metadata: name: api spec: type: NodePort selector: app: api ports: - port: 8080 protocol: TCP targetPort: 8000 I am stuck at this point and cannot find out where the problem is. -
Issue with CreateView ,object not created in model on submit
I have issue might missed something , i have created CreateView view for submitting objects in db , all seems to ok , but when i try to submit i don't get anything happen no error at all except "POST /create_task/ HTTP/1.1" 200 12972 , MY code goes as follows , please advice Thanks models.py class MainTask(models.Model): task_title = models.CharField(max_length=200) global_task_info = models.TextField(max_length=500,default=None) complete = models.BooleanField(default=False) overall_precent_complete = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(default=datetime.datetime.now()) updated_at = models.DateTimeField(default=datetime.datetime.now()) due_date = models.DateTimeField(default=datetime.datetime.now()) task_location = models.CharField(max_length=400, blank=True, null=True) global_task_assign = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="global_task_assign",default=1) TASK_STATUS_CHOICES = [ ('ST', 'STARTED'), ('NS', 'NOT STARTED'), ('IP', 'IN PROGRESS'), ('PA', 'PAUSED'), ('CO', 'COMPLETED'), ] task_status = models.CharField(max_length=2,choices=TASK_STATUS_CHOICES,default='NOT STARTED') def __str__(self): return self.task_title forms.py class TaskCraetionForm(forms.ModelForm): TASK_STATUS_CHOICES = [ ('ST', 'STARTED'), ('NS', 'NOT STARTED'), ('IP', 'IN PROGRESS'), ('PA', 'PAUSED'), ('CO', 'COMPLETED'), ] task_title = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Task Title'})) global_task_info = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Task Description'})) due_date = forms.DateTimeField(widget=forms.DateTimeInput(attrs={ 'class': 'form-control', 'id': 'picker' })) global_task_assign = forms.ModelChoiceField(queryset= UserProfile.objects.all(), widget=forms.Select(attrs={'class':'form-control'} )) task_status = forms.ChoiceField(label='', choices=TASK_STATUS_CHOICES, widget=forms.Select(attrs={'class':'form-control'})) class Meta: model = MainTask fields = ['task_title', 'global_task_info', 'due_date', 'global_task_assign', 'task_status', ] views.py class CreatTaskView(CreateView): model = MainTask template_name = "create_newtask.html" form_class = TaskCraetionForm success_url = None def form_valid(self, form): f = form.save(commit=False) f.save() return super(CreatTaskView, self).form_valid(form) -
Django: form not valid
I am trying to perform a file upload. However, when the file data is passed to Django, I don't know why it is not valid. This is my error message: There's a mistake in field 'file': <ul class="errorlist"><li>This field is required.</li></ul> My JSON message: <JsonResponse status_code=200, "application/json"> html: <body ng-app="myApp" ng-controller="appCtrl"> <input type="file" id="file" name="files" accept="text/*" data-url="file" class="inputfile_upload" select-ng-files ng-model="uploadedFile"/> <label for="file"> <span id="chooseFile"></span>Upload a file!</label> <button id="submitBtn" type="submit" ng-click="upload()">Upload</button> </body> views.py: @csrf_exempt def uploadFile(request): try: if request.method == 'POST': # When files are submitted to the server, the file data ends up placed in request.FILES. form = UploadFileForm(request.POST, request.FILES) for error_field in form.errors: print("There's a mistake in field '{field}': {problem}".format( field=error_field, problem=form.errors[error_field] )) if form.is_valid(): # file is saved form.save() data = request.FILES['file'].read(); print(data); messages.success(request, 'File uploaded successfully!', extra_tags='alert') return JsonResponse({"status": "success", "message": "Success"}) else: print(JsonResponse({"status": "error", "message": form.errors})) return JsonResponse({"status": "error", "message": form.errors}) else: form = UploadFileForm() return render(request, uploadFile(), {'form': form}) except Exception as e: return JsonResponse({"error": str(e)}, status=500) Model.py: class UploadFile(models.Model): file = models.FileField(null=True) def __unicode__(self): return self.file form.py class UploadFileForm(ModelForm): class Meta: model = UploadFile fields = '__all__' -
python manage.py runserver identified 0 issues but there are errors
python manage.py runserver was working fine until I started creating django channels when suddenly everything stopped. I've tried running other sites that worked fine but its still the same C:\personal\website>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by .wrapper at 0x0000028159B61048> Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 49, in init self.build_graph() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 268, in build_graph raise exc File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 242, in build_graph self.graph.validate_consistency() File "C:\Users\user\AppData\Roaming\Python\Python37\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\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 243, in [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\user\AppData\Roaming\Python\Python37\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 admin.0004_auto_20190704_0341 dependencies reference nonexistent parent node ('admin', '0003_logentry_add_action_flag_choices') -
csrf_token verification with Javascript XMLHttpRequest() (403 Forbidden)
i am trying to send a XMLHttpRequest() post request to the Django Server but it shows 403 Forbidden, after searching i found that it is due to CSRF verification , after seeing lot of similar content still i am unable to figure out how to implement csrf in XMLHttpRequest i am including the js snippet that i am using document.addEventListener("DOMContentLoaded", () => { document.addEventListener('click',event => { if (event.target.id === "add-cart-button") { event.preventDefault(); const add_cart_button_id = event.target.dataset.pid const item_class = event.target.dataset.type const item_name = event.target.dataset.item const size_chooser = `#${item_class}-size-${add_cart_button_id}` var sel = document.querySelector(size_chooser) const size = sel.value const quantity_chooser = `#${item_class}-quantity-${add_cart_button_id}` const quantity = document.querySelector(quantity_chooser).value var request = new XMLHttpRequest() request.open('POST','/addcart') request.onload = () => { const data = request.responseText } var data = new FormData() data.append('iten_class',item_class) data.append('item_name',item_name) data.append('size',size) data.append('quantity',quantity) request.send(data) } }) }) i am sending this request to /addcart route of django server def addcart(request): return JsonResponse({'status':True}) which just returns this status can anyone help me in csrf verification -
Why order_by has miscellaneous behavior with nulls in databases?
There is a difference between the behaviour of ORDER_BY in cases where value is null, for instance, Postgres treats these values as greatest. I guess there is no "correct" behaviour and it depends on a particular case. I found this after some of the tests on the SQLite started to fail. For example: # Postgres >>> Person.objects.order_by('age').values('age') >>> <QuerySet [{'age': 10}, {'age': 30}, {'age': None}]> # SQLite >>> Person.objects.order_by('age').values('age') >>> <QuerySet [{'age': None}, {'age': 10}, {'age': 30}]> It is possible to bring behaviour on all databases to one style? And by the way, why there are differences in behaviour? -
while trying to create django-admin startproject :No module name django-admin
while trying to create project using django i installed globally, it says module not found.everything was working fine before i Tried to install another version python, even going back to the previous version didnt help and also tried to uninstall every pip package and reinstall again. i have set path and django is in the script folder as mentioned in the path. virtualenvironment is working fine and i can actually install django in virtual environment but not using the locally installed django. D:\ALL_PROJECTS>python -m django-admin startproject sangalo C:\Users\myuser\AppData\Local\Programs\Python\Python36\python.exe: No module named django-admin -
Cant crack what the syntax error is here: [closed]
'django.contrib.auth.backends.ModelBackend', ^ SyntaxError: invalid syntax -
category subcategory drf django
i have this category and subcategory models: class Category(MPTTModel): name = models.CharField(max_length = 100) slug = models.SlugField() parent = TreeForeignKey('self',blank=True, null=True, related_name='children', on_delete=models.CASCADE, db_index = True) class MPTTMeta: unique_together = ('slug', 'parent') verbose_name_plural = "categories" order_insertion_by = ['name'] def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class SubCategory(models.Model): Sub_Category = models.ForeignKey(Category, on_delete = models.CASCADE) sub_category_name = models.CharField(max_length=100) serializers.py: class SubCategroySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name','slug', 'children') category Listing Api class CategorySerializers(serializers.ModelSerializer): children = SubCategroySerializer(many=True, required=False) class Meta: model = Category fields = ('id','name','slug','children') currently its working but i want to show subcategory inside category only not as a main category as you can see subcategory are listed inside main category and with maincategory also -
How to do validation of user i.e whether the user with same email stored in the database or not in django?
I am having users model and user registration form and the user model is not the custom model so now I want to validate the user email in the database before registering if the same email present it should give an error message My users model models.py class users(models.Model): email=models.CharField(max_length=50,default='0000000') password=models.CharField(max_length=50,default='0000000') room = models.ForeignKey(rooms,on_delete=models.CASCADE) goal = models.ManyToManyField(goals) style = models.ManyToManyField(designs) furn = models.ForeignKey(furniture,on_delete=models.CASCADE) My views for registration: def user_register(request): if request.method == 'POST': username=request.POST["username"] email = request.POST['email'] password = request.POST['password'] room = request.POST['room'] g=goal=request.POST['goal'] g = g.split(',') s=style=request.POST['style'] s=s.split(',') furn=request.POST['furn'] user = users(password=password,email=email) user.room=rooms.objects.get(pk=room) goal = goals.objects.filter(pk__in=g) style = designs.objects.filter(pk__in=s) request.encoding = 'koi8-r' user.furn = furniture.objects.get(pk=furn) user.save() user.goal.add(*goal) user.style.add(*style) return render(request,'register.html')