Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing Django 2.2 database constraint across multiple columns
I have a Django model with start date/time and end date/time where all four components may (independently) be a null value (and there is a semantic difference between a null/unknown value and a known value). I am trying to implement a database constraint [1, 2] to check that if they are non-null that the start date/time is before the end date/time. I have implemented the constraint in two different ways (commented as Option 1, a single constraint, and Option 2, as two constraints) below: from django.db import models class Event( models.Model ): start_date = models.DateField( blank = True, null = True ) start_time = models.TimeField( blank = True, null = True ) end_date = models.DateField( blank = True, null = True ) end_time = models.TimeField( blank = True, null = True ) class Meta: constraints = [ # Option 1 models.CheckConstraint( check = ( models.Q( start_date__isnull = True ) | models.Q( end_date__isnull = True ) | models.Q( start_date__lt = models.F( 'end_date' ) ) | ( ( models.Q( start_time__isnull = True ) | models.Q( end_time__isnull = True ) | models.Q( start_time__lte = models.F( 'end_time' ) ) ) & models.Q( start_date = models.F( 'end_date' ) ) # This line ) ), name … -
Django- Foreign key constraint failed related error
I am new in Django, I'm making an item-category exercise. each item belongs to a category via a foreign key.I'm not able to understand problem in my code during submission of item detail. I'm getting an error "FOREIGN KEY constraint failed". I wrote the code for models.py which is working fine in the admin dashboard of Django, but if same thing I'm trying to implement by HTML form page, I'm getting error. models.py class ColorCat(models.Model): name = models.CharField(max_length=20, default="other") def __str__(self): return self.name class ListItems(models.Model): name = models.CharField(max_length=25, default='item') item_cat = models.ForeignKey(ColorCat, on_delete=models.CASCADE, default=0, null=True,blank=True) views.py def index(request): list = ListItems.objects.all() cat = ColorCat.objects.all() return render(request, 'colorlist.html', {'color': cat, 'item':list }) def colorlist(request): new_list = ListItems new_cate = ColorCat if request.method=="POST": item = str(request.POST["item"]) cat = str(request.POST["category"]) f_key = ColorCat.objects.filter(name="orange").get() new_list(name="item").save() new_list(item_cat=f_key.id).save() item = ListItems.objects.all() color = ColorCat.objects.all() return render(request, 'colorlist.html', {"item": item, "color": color}) def addcat(request): if request.method=="POST": newcat = str(request.POST["name"]) ColorCat(name = newcat).save() item = ListItems.objects.all() color = ColorCat.objects.all() return render(request, 'colorlist.html', {"item":item, "color":color}) colorlist.html {% extends 'base.html'%} {% block content%} <h2>Welcome in color cards</h2> <form action="addcat" method="POST"> {% csrf_token %} <lable>add new cat<input type="text" name="name"></lable><br> <label>submit<input type="submit"></label> </form> <form action="colorlist" method="post"> {% csrf_token %} <label>new item<input type="text" … -
can not import name 'model' from 'app.model'
I have two apps 'user' and 'game' and here is my user/models.py: from django.db import models from django.db.models.fields import related from django.contrib.auth.models import AbstractBaseUser , User, AbstractUser , PermissionsMixin from .managers import CustomUserManager from game.models import Game class User(AbstractBaseUser,PermissionsMixin): username = models.CharField(max_length=150, unique=True, blank=True , null=True,) email = models.EmailField( blank=True , null=True , unique=True) password = models.CharField(max_length=100, null=True , blank=True) objects = CustomUserManager() class Meta: db_table = 'user' class Team(models.Model): name = models.CharField(max_length=40, unique=True) players = models.ManyToManyField(User, related_name="players") game = models.ManyToManyField(Game) is_verfied = models.BooleanField(default=False) class Meta: db_table = 'team' and here is my game/models.py: from django.db import models from user.models import User, Team from leaga.settings import AUTH_USER_MODEL class Game(models.Model): name = models.CharField(max_length=50) is_multiplayer = models.BooleanField(default=False) class Event(models.Model): title = models.CharField(max_length=100) start_date = models.DateTimeField() end_date = models.DateTimeField() class Tournament(models.Model): title = models.CharField(max_length=50) is_team = models.BooleanField(default=False) price = models.PositiveIntegerField() info = models.TextField(max_length=1000) user = models.ManyToManyField(AUTH_USER_MODEL, related_name='tounament_user') team = models.ManyToManyField(Team, related_name='team') game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='tournament_game') event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='tournament_event') # some other code and classes here but unnecessary to mention . . . . when i run : python manage.py makemigrations user this is the console log: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", … -
Different templates for UpdateView for the same model in Django
So I've got a template listing different products in user cart - I would like to give user a chance to update each product from this view. But depending on product type I would like to display different 'update_templates'. What should be the best scenario for this situation? Should I use few different UpdateViews for the same model? Like: class ProductType1UpdateView(UpdateView): model = CartItem fields = '__all__' template_name_suffix = '_product1_update_form' class ProductType2UpdateView(UpdateView): model = CartItem fields = '__all__' template_name_suffix = '_product2_update_form' Or should I make it in one view, and add some if statements that will display proper template depending on product type? Like: class ProductUpdateView(UpdateView): model = CartItem fields = '__all__' {here if statement checking product id} template_name_suffix = '_product1_update_form' {elif} template_name_suffix = '_product2_update_form' The first option works, but it doesn't feel right to me. How would I formulate my if statement to make it with the second option. Or is there maye another, better way to do it? -
Add Django endpoint that doesn't require database connection
I have a typical Django project that uses PostgreSQL as it's database backend. I need to set up a specific endpoint (/status/) that works even when the connection to the database is lost. The actual code is very simple (just returns the response directly without touching the DB) but when the DB is down I still get OperationalError when calling this endpoint. This is because I use some pieces of middleware that attempt to contact the database, e.g. session middleware and auth middleware. Is there any way to implement such /status/ endpoint? I could theoretically implement this as a piece of middleware and put it before any other middleware but that seems as kind of hack. -
how to verify emails after link is clicked usind django rest auth
I am using Django rest auth to authenticate users in my app, the users are successfully getting the email to verify their account but on clicking the link, they get an error KeyError at /account-confirm-email/MTU:1iNTcO:lRoljcqAs3HQMlyy9AzUJH6Kq5w/ Please, how can the users be successfully verified when they click the link my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'users', ] ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='/accounts/login/' LOGIN_REDIRECT_URL = '/accounts/profile' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'test@gmail.com' EMAIL_HOST_PASSWORD = 'testE' DEFAULT_FROM_EMAIL = 'test@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/ urls.py from rest_auth.registration.views import VerifyEmailView urlpatterns = [ path('admin/', admin.site.urls), url('api/rest-auth/', include('rest_auth.urls')), url('api/account/', include('users.api.urls')), url('api/rest-auth/registration/', include('rest_auth.registration.urls')), re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), ] -
updating the readonly_fields in django based on the change permission
i have python django project where i am using to display all the books and rendering a single book when clicking on each book so django will automatically generate the book details. so while rendering i want to make the price_upgrade boolean field read only if the user doesn't have a group called author so my codes like this class BookAdmin(admin.ModelAdmin): list_per_page = 10 list_display_links = ['name'] readonly_fields = ('id', 'name', 'city', 'price_upgrade') ... ... ... def has_change_permission(self, request, obj=None): if request.user.groups.all().filter(Group ='author').exists(): print('author group is there') else: print('author group is not there') #print('request', request.user.groups.all(), type(request.user.groups.all())) return True how can i add the price_upgrade field to readonly_fields if current user doesn't have the group of author else we should remove the price_upgrade field from readonly_fields because he is part of author group so he can edit it Version python 2.7 django 1.8 Any help appreciated -
Browser complains about access control header missing even thought it is there
I'm using a simple Django middleware to set the access control headers. class CorsMoiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Credentials"] = True response["Access-Control-Allow-Methods"] = "GET" response["Access-Control-Max-Age"] = "3600" response["Access-Control-Allow-Headers"] = "Content-Type, Accept, X-Requested-With, remember-me" return response Using curl i clearly see the correct headers. < HTTP/1.1 200 OK < Date: Thu, 24 Oct 2019 09:40:35 GMT < Server: WSGIServer/0.2 CPython/3.7.4 < Content-Type: application/json < Vary: Accept, Cookie < Allow: GET, POST, HEAD, OPTIONS < Access-Control-Allow-Origin: * < X-Frame-Options: SAMEORIGIN < Content-Length: 176 < Access-Control-Allow-Credentials: True < Access-Control-Allow-Methods: GET < Access-Control-Max-Age: 3600 < Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With, remember-me ... But if I try to fetch the url from JavaScript, I see the following error in the console. Access to fetch at 'http://localhost:8000/api/v1/todo' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. -
How could i display that output on my project?
I am creating one project that is work like Sympy gamma. I am done mostly all code but my problem is how to display that output (given in image). I am used sympy build in function but not any function can give me that type of output I want that type of code: -
DRF Relation with two independent columns
I have DB structure like this: common_org: id, code, title special_org: id, code, address Okay. For this I've created models: class CommonOrg(models.Model): code = models.CharField() title = models.CharField() class SpecialOrg(models.Model): code = models.CharField(null=True) address= models.CharField() Now I want to output SpecialOrg as usual, but if I have CommonOrg.code == SpecialOrg.code, then attach CommonOrg to SpecialOrg like this: { "id": 1, "code": "XYZ", "address": "ADDRESS", "common_org": { "id": 2, "code": "XYZ", "title": "TITLE" } } Now I have solution with serializers.RelatedField: class CommonOrgField(serializers.RelatedField): def to_representation(self, value): class _CommonOrgSerializer(serializers.ModelSerializer): class Meta: model = CommonOrg fields = '__all__' representation = None try: common_org = CommonOrg.objects.get(code=value) representation = _CommonOrgSerializer(common_org).data except CommonOrg.DoesNotExist: pass return representation class SpecialOrgSerializer(serializers.ModelSerializer): class Meta: model = SpecialOrg fields = '__all__' common_org = CommonOrgField(read_only=True, source='code') But it looks ugly for me. So the question is: what is the right approach to implement it in DRF? Database is not mine and I cannot to alter it. -
Trying to convert users input into a word document using pandoc
I want to take users response of a form and convert it into a templated word document that will be downloaded. I am trying to use pandoc but I am beginner at both python and django and do not know how I am a beginner in python and do not know what to do. This is my create_proposal.html file: {% extends 'base.html' %} {% block content %} <h2>New Financial Proposal</h2> <form class="form-group" action="result/" method="get"> {% csrf_token %} {{form.as_p}} <input type="Submit" class="btn btn-primary" value="Create"/> </form> {% endblock content %} And in my views.py file I have a class like this: class InputPage(CreateView): model = CostOfGood template_name = 'create_proposal.html' fields = '__all__' The class CostOfGood in models.py looks like: class CostOfGood(models.Model): item_no = models.CharField(max_length= 200) part_no = models.TextField() product_description = models.TextField() unitMarketPrice = models.FloatField() quantity = models.FloatField() markup = models.FloatField() -
Can we custom whole Django Admin site is it possible?
here I have superuser(admin) which has a button and after clicking on it it should show another database table details in admin after clicking on button it should show all data of table -
Having a bootstrap carousel for Wagtail problem
I have been testing my code out and come across a small problem. My indicators at the bottom allow for navigation but to get to the final image in the carousel I need to click on the second last indicator? I cant see the bug :(. All the others work fine. <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ul class="carousel-indicators"> {% for item in page.blogpage_images.all %} <li data-target="#carouselExampleIndicators" data-slide-to="{{ forloop.counter }}" class="{% if forloop.counter == 1 %}active{% endif %}"></li> {% endfor %} </ul> <div class="carousel-inner"> {% for item in page.blogpage_images.all %} {% image item.image fill-900x400 as img %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ img.url }}" class="d-block w-100" alt="{{ img.alt }}"> </div> {% endfor %} </div> </div> -
How to setup Django Channel with uWSGI
My Django application is set up with uWSGI, Nginx. Everything is fine. Now I want to set up with Django Channel. The server is running good in a localhost environment, with command python manage.py runserver. But when I deploy to a server, the WebSocket URL is not found. I think I need to config the uWSGI and Nginx config. But I don't know how to do it? Does everyone have any idea? -
how to fix error in django addition url path not find not link to new code
My url path finder doeds not find result.html page when i click on submit button it will not find that result.html page . it can not find the second url path.Iam trying to add two numbers in Django a basic django Programmge in first it will open the home.html page then on click submit it will not open the result.html page on which the result is displaed i have tried to import pattrens but it will show errors pattrens can not be imported somethig like i have also tried to direct the page from This is my url.py file from django.conf.urls import include, url from django.contrib import admin from . import views admin.autodiscover() urlpatterns = [ url('', views.home,name='home'), url(r'^add/', views.add, name ='add'), ] ##this is my home.html file {% extends 'base.html' %} {% block content %} <body> <h1> Hello {{name}} !!!!!!! </h1> <form action="add"> Enter First Number : <input type="text" name ="first"> Enter Second Number : <input type="text" name ="second"> <input type ="submit"> </form> </body> ## this is my view.py file from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request,'home.html',{'name': 'Harsh'}) def add(request): val1= int(request.GET['first']) val2= int(request.GET['second']) res … -
I want to extract image cordinates from pdf in python. i am not able find any solution for python
I tried using the third party libraries but not the same thing i want. i just want the coordinates of image not the image itself. i have found some solution for text coordinate extraction using pdfminer. -
Deploy django project and frontend in apache
I'm using django==1.11 apache 2.4 django project /var/www/myproject and frontend code /var/www/html/frontend directories. I want to deploy on apache server where i have modified 000-default.conf file as <VirtualHost *:80> ServerName www.mysite.in ServerAlias mysite.in ServerAdmin myemail@abc.com DocumentRoot /var/www/ ErrorLog ${APACHE_LOG_DIR}/mysite_error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias / /var/www/html/frontend/ <Directory /var/www/html/frontend> Require all granted </Directory> <Directory /var/www/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite.in python-path=/var/www/myproject python-home=/usr/local/lib/python3.5/dist-packages WSGIProcessGroup mysite.in WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py </VirtualHost> In this case i'm not able to hit to my django rest apis. If i use <VirtualHost *:80> ServerName www.mysite.in ServerAlias mysite.in ServerAdmin myemail@abc.com DocumentRoot /var/www/ ErrorLog ${APACHE_LOG_DIR}/mysite_error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite.in python-path=/var/www/myproject python-home=/usr/local/lib/python3.5/dist-packages WSGIProcessGroup mysite.in WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py </VirtualHost> then i'm able to hit my django rest apis. Here, alias are conflicting. I'm not using my static files in my django project as i have all static files are not in myproject. How to deploy django rest apis and backend code with different directories on apache server? Thanks. -
500 apache server error on django page with contact form
I create my first page in django 2.2. I have implemented it on the apache server, but I have a problem displaying the page with the contact form. I receive a 500 error in response. I use the send_mail function to send messages. I checked the server logs. Unfortunately they don't tell me much. I added the {% csrf_token%} tag under the form tag in the html code. I think the problem is because of the wrong view for the page, but I don't know what to do to fix it. def contact(request): message = request.POST.get('message', False) sender = request.POST.get('email', False) subject = "New message from example.com form" + sender send_mail(subject, message, 'contact@example2.com', ['contact@example3.com'], fail_silently=False) return render(request=request, template_name="main/contact.html") Below, I paste the apache server log: [Thu Oct 24 10:47:28.394512 2019] [:error] [pid 17558] [client x.x.x.x] ModSecurity: Warning. Pattern match "^5\\d{2}$" at RESPONSE_STATUS. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_50_outbound.conf"] [line "53"] [id "970901"] [rev "2"] [msg "The application is not available"] [data "Matched Data: 500 found within RESPONSE_STATUS: 500"] [severity "ERROR"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "9"] [tag "WASCTC/WASC-13"] [tag "OWASP_TOP_10/A6"] [tag "PCI/6.5.6"] [hostname "example.com"] [uri "/contact/"] [unique_id "XbFlIH8AAQEAAESWGb4AAAAA"] [Thu Oct 24 10:47:28.397631 2019] [:error] [pid 17558] [client x.x.x.x] ModSecurity: Warning. Operator GE matched 4 … -
Django REST API query on related field
I have 3 models, Run, RunParameter, RunValue: class Run(models.Model): start_time = models.DateTimeField(db_index=True) end_time = models.DateTimeField() class RunParameter(models.Model): parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE) class RunValue(models.Model): run = models.ForeignKey(Run, on_delete=models.CASCADE) run_parameter = models.ForeignKey(RunParameter, on_delete=models.CASCADE) value = models.FloatField(default=0) A Run can have a RunValue, which is a float value with the value's name coming from RunParameter (which is basically a table containing names), for example: A RunValue could be AverageTime, or MaximumTemperature A Run could then have RunValue = RunParameter:AverageTime with value X. Another Run instance could have RunValue = RunParameter:MaximumTemperature with value Y, etc. I created an endpoint to query my API, but I only have the RunParameter ID (because of the way you can select which parameter you want to graph), not the RunValue ID directly. I basically show a list of all RunParameter and a list of all Run instances, because if I showed all instances of RunValue the list would be too long and confusing, as instead of seeing "Maximum Temperature" you would see: "Maximum Temperature for Run X" "Maximum Temperature for Run Y" "Maximum Temperature for Run Z", etc. (repeat 50+ times). My API view looks like this: class RunValuesDetailAPIView(RetrieveAPIView): queryset = RunValue.objects.all() serializer_class = RunValuesDetailSerializer permission_classes = [IsOwnerOrReadOnly]] … -
Django TruncDay limit by largest grouping
I am trying to draw a day series graph, whereby it will show the number of employees of the division(s) in a day series. The problem here is that I want to find a way to limit to the division with the most employees so I dont need to draw too many lines and stress the database. (for example limit it to top 3 division with the most employee attendance) I am using: Django 1.11.x Postgres 9.4 The goal is to create a day series graphing of this sort. has the grouping of division and the number of employee. I have manage to achieve it with the following code: from datetime import date, datetime from django.db.models import Count from django.db.models.functions import ( TruncDate, TruncDay, TruncHour, TruncMinute, TruncSecond, ) emp_by_day = Attendance.objects.annotate(day=TruncDay('created_at')).values('day', 'division_id').annotate(cnt=Count('employee_id', distinct = True)).order_by('day') for exp in emp_by_day: print(exp['day'], exp['division_id'], exp['cnt']) however, it currently output displays like this (i am generally happy but want to limit it): count<-> division_id<-> <---day-----------------> 2019-10-22 00:00:00+00:00 15 6 2019-10-22 00:00:00+00:00 16 6 2019-10-22 00:00:00+00:00 18 5 2019-10-22 00:00:00+00:00 20 4 2019-10-22 00:00:00+00:00 21 12 <-- largest 3 2019-10-22 00:00:00+00:00 25 14 <-- largest 3 2019-10-22 00:00:00+00:00 28 12 <-- largest 3 2019-10-23 00:00:00+00:00 … -
You cannot call `.save()` after accessing `serializer.data`
Error Showing when post data from API You cannot call `.save()` after accessing `serializer.data`.If you need to access data before committing to the database then inspect 'serializer.validated_data' instead. My written Code is: serializerdata = serializers.CreateSerializer(data=request.data) if serializerdata.is_valid(): user_id = serializerdata.data.get('user_id') if user_id==2: serializerdata.save(i_created_by=request.user) return JsonResponse({"message": "success"}) else: return JsonResponse({"message": "user invalid"}) else: return JsonResponse({"message": "error"}) -
Django ManyToManyField with many same IDs
I'm trying to make a simple pizza order app in Django. I have 3 models (Toppings, Pizzas, Orders). In Orders model have ManyToManyField to Pizza. It's working fine if "user" orders one each pizza (Margarita and Pepperoni for example) but if order 2 Margarita in POST request I got only one Margarita ID in my result. How i can pass n-pizzas in one Order? My models looks like this: class Toppings(models.Model): name = models.CharField(blank=False, max_length=100, unique=True) class Meta: ordering = ['name'] def __str__(self): return self.name class Pizza(models.Model): name = models.CharField(blank=False, max_length=100, unique=True) ingredients = models.ManyToManyField(Toppings, blank=False, null=False) class Meta: ordering = ['name'] def __str__(self): return self.name class PizzaOrder(models.Model): created = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField(Pizza, blank=False, null=False) status = models.CharField(max_length=1, choices=[ (1, 'placed'), (2, 'approved'), (3, 'cooked'), (4, 'delivered'), (5, 'canceled') ], default=1) class Meta: ordering = ['created'] def __str__(self): return self.created I send POST with this data: { "items": [1, 1, 1, 2, 2], "status": 1 } and got this only 1 and 2 in items list (not 1,1,1,2,2): { "id": 2, "items": [ 1, 2 ], "status": 1 } -
Django-select2 is not showing model data
I have configured django-select2 but data from models is not showing in field. I had tried many methods like normal forms as well as modelform. I have also tried initialise the field as query, still its not working accordingly. Same code: forms.py class PricekeyForm(forms.ModelForm): uom = forms.ModelChoiceField( queryset=UnitOfMeasurement.objects.all(), widget=ModelSelect2Widget( model=UnitOfMeasurement, search_fields=['unit__icontains'] ) ) class Meta: model = Pricekey fields = ['uom', 'sales_price', 'return_price', 'damage_return_price',] def __init__(self, *args, **kwargs): self.fields['uom'].widget.queryset models.py class Pricekey(BaseModel): itemcode = models.CharField(max_length=255,null=True,blank=True) uom = models.ForeignKey('UnitOfMeasurement',on_delete=models.CASCADE,null=True,blank=True) sales_price = models.FloatField(null=True,blank=True) return_price = models.FloatField(null=True,blank=True) damage_return_price = models.FloatField(null=True,blank=True) expiry_return_price = models.FloatField(null=True,blank=True) What i wanted is, select2 filled with data from the db. Please tell me where i went wrong. I checked the documentation also for django-select2. please help me. -
Multiple Model File Uploader Using DRF
I have a models.py as the following and I'm trying to make multiple upload files in one request. and the other fields in the model i put the values in the back-end so, what i need exactly how to to send array of data (files) in one request and handle the files and create record for every single files separate? I also read a lot and see a lot of answers, but I felt the solution depends on the case maybe because I didn't got it will please any one can help me ? models.py file_name = models.FileField(upload_to='docs/', null=True, blank=True) created_by = models.ForeignKey(User, related_name='file_created_by', blank=True, null=True,on_delete=models.DO_NOTHING) created_date = models.DateTimeField(auto_now_add=True) serializers.py class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = '__all__' def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) user = kwargs['context']['request'].user super(FileSerializer, self).__init__(many=many, *args, **kwargs) def create(self, validated_data): validated_data['status'] = 'in_progress' self.context["file_name"] = self.context['request'].FILES.get("file_name") obj = File.objects.create(**validated_data) return obj views.py class FileCreateAPIView(CreateAPIView): queryset = File.objects.all() serializer_class = FileSerializer permission_classes = [IsOwnerOrReadOnly] def get_queryset(self): return File.objects.all() def perform_create(self, serializer): serializer.save(created_by=self.request.user, updated_by=self.request.user) -
How to choose my table for permissions in django?
Good day to all. I created a custom user model with custom permissions. I have several projects and permissions merged into one table. Is it possible to somehow set the table itself for these permissions?(like db_table = '"schema"."table"' to the models.) Google did not give answers. class TestUser(AbstractUser): phone = PhoneNumberField(null=False, blank=False, unique=True) email = CharField(unique=True, max_length=35, null=False, blank=False) class Meta: db_table = '"fyzzys"."users"' permissions = [ ("can_see_payments", "payments"), ("can_see_analytics", "analytics"), ]