Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How do to subtract two annotations with different models
a = Category.objects.annotate(total_products=Count('product')) b=Order.objects.values('category__name').annotate(total_approve=Sum('approve_quantity')).order_by('-total_approve') so I want to subtract a - b -
drf-spectacular post method not working with form field
I am using Django Rest Framework. And for documentation I am using drf-spectacular. But the problem I am facing is that when I am trying to submit using form, I can not submit. But I can submit using JSON type normally. This Does not Work: This Works: How can I make the form to work? It does not even let me submit the form. Also, How can I make the profile_pic as filefield? Below is my code: settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.FileUploadParser', ], 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } SPECTACULAR_SETTINGS = { 'TITLE': 'Your Project API', 'DESCRIPTION': 'Your project description', 'VERSION': '1.0.0', } serializers.py from rest_framework import serializers from app_restaurant import models class RestaurantSerializer(serializers.ModelSerializer): """ Restaurant Create Serializer """ class Meta: model = models.Restaurant fields = '__all__' extra_kwargs = { 'slug': {'read_only': True}, } views.py from rest_framework import generics from app_restaurant import serializers, models from app_user import apipermissions # Create your views here. class RestaurantCreateView(generics.CreateAPIView): """ Restaurant Creation View """ permission_classes = [apipermissions.IsOwner] serializer_class = serializers.RestaurantSerializer queryset = models.Restaurant.objects.all() -
Django with Nginx and Gunicorn prompt null warning
I am running Django project in server using Nginx and Gunicorn. When user visit the website, I can find the NULL warning message in server. Anyone know how to solve it? -
parse array of objects sent from frontend in python Django backend
I have a web app, backend using Django, frontend using normal HTML5. I the frontend, I use axios to send an array of objects via POST request. axios ({ method: 'POST', url: test_url, data: { [{title:1, isbn:1234},{title:2, isbn:5678}] } }) However, in the backend, I could not succeed in parsing the data send from frontend. def test_url(request): body = request.body.decode("utf-8") json_acceptable_string = body.replace("'", "\"") d = json.loads(json_acceptable_string) title = d.get('title') ... I got json decode error in the backend. How could I easily parse the array of objects sent from frontend in python? -
Django: Get all inline objects in Admin's save_model
I have two related (via foreignKey relation) models and created admin model for parent with inlines. In a certain use-case, I need to fetch all related models and use those to update 1 particular field for parent model. What is the efficient way to do it? My Models: class ParentModel(BaseModel): text = models.CharField() // This is generated from inline children's data ... class ChildModel(BaseModel): parent = models.ForeignKey(ParentModel, on_delete=models.RESTRICT) ... class ChildModelInline(TabularInline): model = ChildModel class ParentModelAdmin(admin.ModelAdmin): inlines = [ChildModelInline] ... What I want is something similar to this: class ParentModelAdmin(admin.ModelAdmin): inlines = [ChildModelInline] ... def save_model(self, request, obj, form, change): inline_objects = <get_all_inline_objects> obj.text = <generate_text(inline_objects)> super(ParentModelAdmin, self).save_model(request, obj, form, change) -
CKEditor not rendering on Deploy
I installed CKEditor in my Django blog app and all worked fine in development. Once I deployed through Heroku the text editor window has disappeared from both the admin panel and the client front end, showing these errors in the console: Console Error Messages I have it in installed apps in settings.py My configs are CKEDITOR_CONFIGS = { 'default': { 'width': 'auto', }, } Static Files are set as: STATIC_URL = "/static/" STATICFILES_STORAGE = ( "cloudinary_storage.storage.StaticHashedCloudinaryStorage" ) STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = "/media/" DEFAULT_FILE_STORAGE = "cloudinary_storage.storage.MediaCloudinaryStorage" CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "/media/" And I have path("ckeditor/", include('ckeditor_uploader.urls')), set up in my urls.py It has also been imported into my models.py, I have it in my requirements.txt and I have ran the collectstatic command. Any suggestions please? -
Race condition when two different users inserting new records to database in Django
There is a race condition situation, when I want to create a new instance of model Order. There is a daily_id field that everyday for any category starts from one. It means every category has its own daily id. class Order(models.Model): daily_id = models.SmallIntegerField(default=0) category = models.ForeignKey(Categoty, on_delete=models.PROTECT, related_name="orders") declare_time = models.DateField() ... } daily_id field of new record is being calculated using this method: def get_daily_id(category, declare_time): try: last_order = Order.objects.filter(declare_time=declare_time, category=category).latest('daily_id') return last_order.daily_id + 1 except Order.DoesNotExist: # If no order has been registered in declare_time date. return 1 The problem is that when two different users are registering orders in the same category at the same time, it is highly likely that the orders have the repetitive daily_id values. I have tried @transaction.atomic decorator for post method of DRF APIView and it didn't work! -
returning only one response from the database in Django rest-framework
I'm trying to return all the results from the SQL using this approach I'm able to retrieve it but its the static one. I have tried looping the result_set but its returning only the first response out of 5 responses but I want to return all the 5 response Here, What I have tried expected response: [{"Value8":"Avail-On queue","Value1":"Avail-On queue"},{"Value8":"Coaching","Value1":"Coaching"},{"Value8":"Huddle","Value1":"Huddle"},{"Value8":"Outage","Value1":"Outage"},{"Value8":"Training","Value1":"Training"}] views.py: @api_view(['GET']) def GetClaimsActivity(request, UserId): if request.method == 'GET': cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaimsPlusActivity] @UserId=%s', (UserId,)) result_set = cursor.fetchall() data = [] # for row in result_set: #data.append({ #'Value8':row[0], #'Value1':row[0], #}) #return Reponse(data) data = [] data.append({ 'Value8':result_set[0][0], 'Value1':result_set[0][0], }) data.append({ 'Value8':result_set[1][0], 'Value1':result_set[1][0], }) data.append({ 'Value8':result_set[2][0], 'Value1':result_set[2][0], }) data.append({ 'Value8':result_set[3][0], 'Value1':result_set[3][0], }) data.append({ 'Value8':result_set[4][0], 'Value1':result_set[4][0], }) return Response(data) -
Conditionally return JSON or XML response from Django django-rest-framework's class based view
How can i get response ap per body request passing output_format = 'json' or 'xml'. It's only return one type of response. How can i get both response as per condition. Below is My code. djangorestframework==3.13.1 Setting.py REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework_xml.renderers.XMLRenderer', ] } views.py class AddressAPI(APIView): renderer_classes = (XMLRenderer, JSONRenderer) def post(self, request): try: serializer = GeoLocationSerializer(data=request.data) if serializer.is_valid(): address = serializer.data['address'] output_format = serializer.data['output_format'] address_body = format_address(address) url = f"https://maps.googleapis.com/maps/api/geocode/json?address={address_body}&key={api_key}" response = requests.request("GET", url) source = response.text data = json.loads(source) for source in data['results']: if output_format == 'json' or output_format == 'JSON': # print(serializer.data) return Response({ 'coordinates' : source['geometry']['location'], 'address' : address, }) elif output_format == 'xml' or output_format == 'XML': return Response({ 'coordinates' : source['geometry']['location'], 'address' : address, }) else: return Response({ 'message' : 'Invalid output_format' }) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as e: print(e) -
Getting HTTP/1.1" 500 27 when debug set to FALSE in my django local environment
I have the settings.py like below Basically our DEBUG will be set to TRUE. But since to the production we need to set FALSE, we have to handle the code to set debug FALSE. even with debug=FALSE the app should work as it is. But in my case, because debug is set to FALSE , my app is giving HTTP/1.1" 500 27 error. May i know what i am missing here. import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'MyApp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Django jwt and React redirect to different pages for different users after log in
I have 2 roles which are member and staff, and i want to redirect to the different pages depend on the users' roles using username and password e.g. after logging in as a member would redirect to member page and as a staff would redirect to onlystaff page. How I can do it. I'm using React Django JWT and Material UI. Sorry for my bad English. the code: axios.js const baseURL = 'http://127.0.0.1:8000/api/'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem('access_token') ? 'JWT ' + localStorage.getItem('access_token') : null, 'Content-Type': 'application/json', accept: 'application/json', }, }); axiosInstance.interceptors.response.use( (response) => { return response; }, async function (error) { const originalRequest = error.config; if (typeof error.response === 'undefined') { alert( 'A server/network error occurred. ' + 'Looks like CORS might be the problem. ' + 'Sorry about this - we will get it fixed shortly.' ); return Promise.reject(error); } if ( error.response.status === 401 && originalRequest.url === baseURL + 'token/refresh/' ) { window.location.href = '/login/'; return Promise.reject(error); } if ( error.response.data.code === 'token_not_valid' && error.response.status === 401 && error.response.statusText === 'Unauthorized' ) { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { const tokenParts = JSON.parse(atob(refreshToken.split('.')[1])); const now = Math.ceil(Date.now() / 1000); … -
Error 502: Deploy Django application with Gunicorn and Nginx
I have developed a web application with Django and I am trying to publish it in a virtual machine created with Azure. To do that I'm using the following software stack: Ubuntu (20.04) Django (3.0.7) Virtualenv (20.0.17) Gunicorn (20.1.0) Nginx (1.18.0) To deploy the app I followed that guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 My django project folders are organized as follows: home/ ├─ useradmin/ │ ├─ myproject/ │ │ ├─ proj/ │ │ │ ├─ settings.py │ │ │ ├─ urls.py │ │ │ ├─ wsgi.py │ │ │ ├─ ... │ │ ├─ static/ │ │ ├─ templates/ │ │ ├─ venv/ │ │ ├─ manage.py │ │ ├─ ... This is my /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=useradmin Group=www-data WorkingDirectory=/home/useradmin/myproject ExecStart=/home/useradmin/myproject/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/useradmin/myproject/myproject.sock proj.wsgi:application [Install] WantedBy=multi-user.target This is my /etc/nginx/sites-available/myproject: server { listen 80; server_name mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/useradmin/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/useradmin/myproject/myproject.sock; } } When I navigate to mydomain.com I get a 502 Bad Gateway error. If I check the Nginx logs by running "sudo tail -F /var/log/nginx/error.log" I see the following error: 2022/03/16 08:27:33 [crit] 64480#64480: *3 connect() to … -
gunicorn active: failed, why don`t active gunicorn service?
i hav ubuntu server 20.04 and a django project i set /etc/systemd/system/gunicorn.socket Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target and i have this error gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2022-03-16 11:49:31 +0330; 12min ago TriggeredBy: ● gunicorn.socket Process: 1891 ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bi> Main PID: 1891 (code=exited, status=217/USER) Mar 16 11:49:31 srv174847 systemd[1]: Started gunicorn daemon. Mar 16 11:49:31 srv174847 systemd[1891]: gunicorn.service: Failed to determine user credentials: No such process:: Failed to determine user credentials: No such process Mar 16 11:49:31 srv174847 systemd[1891]: gunicorn.service: Failed at step USER spawning /home/sammy/myprojectdir/myprojectenv/bin/gunicorn: No such process Mar 16 11:49:31 srv174847 systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Mar 16 11:49:31 srv174847 systemd[1]: gunicorn.service: Failed with result 'exit-code'. please help me -
how to get the number of row in a csv file in django
How can i solve? how can i get the count of no. of rows in a csv file using django.how can i solve this issue. while wrote code below its not working it showing the no.of. columns not row. Here my view def upload_csv(request): template = "upload_csv.html" if request.method == "GET": return render(request,template) csv_file=request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.info(request,'* This is not a csv file') return render(request,template) data_set = csv_file.read().decode('UTF-8') data =io.StringIO(data_set) next(data) for row in csv.reader(data,delimiter=',',): Company.objects.get_or_create( name = row[0], hr_name =row[1], hr_email=row[2], hr_verified=row[3], user_id=row[4], primary_phone=row[5], comments=row[6], ) context={} file_name = request.FILES['file'].name count = len(list(row)) company =UploadCsv( file_name=file_name, no_of_row =count, user = request.user ) company.save() return render(request, template,context) -
Can't Install xmlsec for Mac
I'm new to django. i am tring to implement python3-saml which requires Xmlsec. i am trying to install it Using "pip install xmlsec" on my virtal environment. but throwing this error. Collecting xmlsec Using cached xmlsec-1.3.12.tar.gz (64 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Requirement already satisfied: lxml>=3.8 in /opt/anaconda3/envs/conda_saml_env/lib/python3.10/site-packages (from xmlsec) (4.8.0) Building wheels for collected packages: xmlsec Building wheel for xmlsec (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for xmlsec (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [14 lines of output] running bdist_wheel running build running build_py package init file 'src/xmlsec/__init__.py' not found (or not a regular file) creating build creating build/lib.macosx-10.9-x86_64-3.10 creating build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/py.typed -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/tree.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/__init__.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/constants.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/template.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec running build_ext error: xmlsec1 is not installed or not in path. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for xmlsec Failed to build xmlsec ERROR: Could not build wheels for xmlsec, which is required to install pyproject.toml-based projects I … -
How to get foreign key detailed values based on id in html template in django
In Models.py class Interview(models.Model): Current_Date = models.DateField(auto_now_add=True ) User = models.ForeignKey(User,on_delete=models.CASCADE) Recuirement = models.ForeignKey(Client_Requirement,on_delete=models.CASCADE) Candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) Interviewer = models.ForeignKey(Interviewer, on_delete=models.CASCADE) Interview_Mode = models.ForeignKey(Interview_Mode, on_delete=models.CASCADE) Date = models.DateField() Time = models.TimeField() Interview_status = models.ForeignKey(Interview_status, on_delete=models.CASCADE) Interview_Location = models.CharField(max_length=30) Comments = models.TextField(max_length=1000) Update_Date = models.DateTimeField(auto_now=True) def __str__(self): return str(self.Interviewer) in Views.py def BD(request): Interview_data = Interview.objects.all() context={'Interview_data':Interview_data} return render(request,'Sub/BD.html', context) How i can get all the data individual details of Recuirement, Candidate table In for loop tag in django -
Html - Create dropdown menu from logged in user's account
I would like to create a dropdown menu from the logged-in user account. Something like this: The dropdown menu can contain two options (MyOrder and Logout). Please do not provide the external stylesheet as it will mess up my current page. CSS <style> * { box-sizing: border-box; } body { margin: 0; } .nav { overflow: hidden; background-color: #939596; //background-color: #454545; //background-color: #808080; } .nav a { float: left; display: block; color: #ffffff; text-align: center; padding: 5px 16px; text-decoration: none; font-size: 18px; } .nav span { float: left; display: block; color: #ffffff; text-align: center; //padding: 45px 16px; padding-top: 40px; padding-right: 16px; padding-bottom: 20px; //padding-left: 80px; text-decoration: none; font-size: 13px; } .nav h1, .nav h1 a, .nav h1 a:visited, .nav h1 a:active { color: #ffffff; font-size: 25pt; text-decoration: none; } .nav a:hover { background-color: #eeeeee; color: #000000; } .nav a.active { background-color: #0e002b; color: #ffffff; } .nav .login-container { float: right; } .nav input[type=text], .nav input[type=password] { padding: 6px; margin-top: 8px; font-size: 17px; border: none; width: 120px; } .nav .login-container button { float: right; padding: 6px 10px; margin-top: 33px; margin-right: 16px; background-color: #1c87c9; color: white; font-size: 17px; border: none; cursor: pointer; } .nav .login-container button:hover { background-color: #0e002b; } @media screen … -
Delete all objects from model on specific value using button django
Please see screen shot of table for context: I'm trying to delete the table row using the corresponding Delete Asset button (i.e. delete all rows in a django model with Symbol: 1INCHUP) How I am mapping this out would be the Delete Asset button would send the corresponding Symbol to the following view: View FYI - this View is creating the table but I'm trying to get the delete button working here # CryptoAssets is a model def get_asset_price(request, symbol): sym = CryptoAssets.objects.filter(user_id=request.user.id).values('symbol') obj = sym.annotate(total_units=Sum('units'),total_cost=Sum('cost')).order_by('symbol') cp = [CryptoPrices.objects.filter(ticker=s['symbol']).values('current_price').order_by('ticker')[0] for s in sym] for i, o in enumerate(obj): o.update({'purchase_price': round(o['total_cost']/o['total_units'], 5)}) o.update({'current_price': cp[i]['current_price']}) pl = cp[i]['current_price']*o['total_units']-o['total_cost'] o.update({'profit_loss': round(pl, 5)}) o.update({'profit_loss_p': round(pl/o["total_cost"]*100, 2)}) # Delete Asset request if request.METHOD == "POST": asset = CryptoAssets.objects.filter(user_id=request.user.id, symbol=symbol) asset.delete() return redirect('coinprices/my-dashboard.html') context = { 'object': obj, } return render(request, 'coinprices/my-dashboard.html', context) HTML {% for row in object %} <tr> <td style="text-align:center">{{ row.symbol }}</td> <td style="text-align:center">{{ row.total_units }}</td> <td style="text-align:center"><span class="prefix">${{ row.total_cost }}</span></td> <td style="text-align:center"><span class="prefix">${{ row.purchase_price }}</span></td> <td style="text-align:center"><span class="prefix">${{ row.current_price }}</span></td> <td style="text-align:center"><span class="prefix">${{ row.profit_loss }}</span></td> <td style="text-align:center"><span class="suffix">{{ row.profit_loss_p }}%</span></td> <td style="background-color:white; border: 1px solid white;"> <form action="." method="POST">{% csrf_token %} <button href="{% url 'dashboard' row.symbol %}" class="btn btn-outline-danger btn-sm">Delete Asset</button> </form> … -
Django API calls on SSO enabled service now
the requirement is to fetch the incident details based on incident number from service now which is SSO enabled. Currently we are trying to fetch the incident details of service now from a Django application by django APIs but it is saying authentication failed because service now is SSO enabled. I am passing URL with username and password as below r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass')) and its saying not valid. The service now API is being called from the same server. -
Am a newbie in django, am trying to count number of app registration request but result does not display on the template?
below is my code that i was trying to implement the task my views.py this is my view for counting the request def appSummary_view(request): context = {} user = request.user applications = ApplicationRequest.objects.all().filter(developer=user) total_request = applications.count() registered_app = applications.filter(status=1).count() pending_app = applications.filter(status=0).count() context = {'total_request':total_request, 'registered_app':registered_app, 'pending_app':pending_app} print(applications) return render(request, 'dashboard.html', context) #my models this is my model for app request class ApplicationRequest(models.Model): id = models.BigAutoField(primary_key=True) developer = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="%(app_label)s_%(class)s", null=True, blank=True, on_delete=models.CASCADE, ) name_of_app = models.CharField(max_length=255, blank=True,null=True) domain = models.CharField(max_length=100, unique=True,null=True) org_name = models.CharField(max_length=200,null=True) redirect_uris = models.TextField( blank=True, help_text= ("Allowed URIs list, space separated") ) claim_of_property = models.TextField( blank=False, help_text= ("Proof of property, space separated"),null=True ) date_requested = models.DateTimeField(auto_now_add=True) status = models.IntegerField(default=0) def __str__(self): return self.name_of_app #my forms.py this is my form for registering the applications class RegisterAppForm(forms.ModelForm): name_of_app = forms.CharField(max_length=255, help_text='Required.Please enter the name of your applications') domain = forms.CharField(max_length=100, help_text='Required.Please enter the domain for your application') org_name = forms.CharField(max_length=200, help_text='Required.Please enter the name of the organization of your application') redirect_uris = forms.CharField(max_length=400,help_text='Required.Please enter redirect uris for your app') claim_of_property = forms.CharField(max_length=400, help_text='Required.Please provide the proof of property') class Meta: model = ApplicationRequest fields = ('name_of_app', 'domain', 'org_name', 'redirect_uris' , 'claim_of_property') template code this is my template … -
how can remove city name and update society name and save it into the database?
So I want to know how can I remove the city name from the society name and update the society name and save it into the database? Below code is taking all the society names that contain the city name. but I want to update all the society's names and save them. qs = Society.objects.all() citys = City.objects.values_list('name', flat=True) clauses = (Q(name__iendswith=name) for name in citys) query = reduce(operator.or_, clauses) data = qs.filter(query) Thanks!! -
Django Grapelli change background column headers
I'm using django grapelli. In my model there is color field which users can select color with colorfield widget. I want to change columns header background color. Does anyone know anything about this? I couldn't found anything. -
Django - How do you handle Two way Bindings
I have the following two models: class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) steps = models.ManyToManyField('manager.Step', related_name='steps') However when editing the Schedule and adding steps via admin the Step does not update its schedule? How do you handle two way binding like this in Django? -
Get rid of   in ckeditor Django
How I can get rid of &nbsp appearing on templates, when using django-ckeditor, I tried with 'entities_additional': '' in settings as follows but still it is visible when using quotes or double space. CKEDITOR_CONFIGS = { 'default': { 'toolbar': [["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Subscript", "Superscript"], ['Undo', 'Redo'], ["Source"], ["Maximize"]], 'height': 250, 'width': '100%', 'entities_additional': '' }, } -
why if i call the fields of the form one by one and i have action on the button reliant to this form there was no result displayed on Django
i want to use a form but what i want is calling the fields of the form one by one on the Html template and then if i click on a button "there was some calculation results will be displayed" , after much tries I have found that if i call the all the form in the html template using: <form action="{% url 'areas' %}" method="post" id="maincont" novalidate> {% csrf_token %} {{ form }} <button id="reslink" >Result</button> </form> --------> It works fine and show me the result values what i want to do call the fields of the form one by one on the html <form action="{% url 'areas' %}" method="post" id="maincont" novalidate> {% csrf_token %} <p>{{ form.domestic_residential}} Domestic and residential areas ml</p> <p>{{ form.office_area}} Office areas ml</p> <input id="submit" type="button" value="Click"/> <p >{{ resultat }}</p> </form> --------> It doesn't show any result. Any help will be appreciated because really i want to do it ( i want to call the fields one by one for things reliant to the design of the page). I want Just to know How i can correct this part of template to make me show some results( or any advices or some one had …