Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use registration(signup/login) modal(bootstrap template) with django views?
I am new to programming. I found nice bootstrap modal for registration, so i put it to my html code and it looks nice but nothing can be pressed or post. Before i was using django and UserCreationForm without modals. So help me to concatenate these two things: so this is my bootstrap modal that i found <!-- Modal --> <div class="modal fade" id="elegantModalForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <!--Content--> <div class="modal-content form-elegant"> <!--Header--> <div class="modal-header text-center"> <h3 class="modal-title w-100 dark-grey-text font-weight-bold my-3" id="myModalLabel"><strong>Войти</strong></h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <!--Body--> <form type="post" action="{% url 'common:login' %}"> <div class="modal-body mx-4"> <!--Body--> <div class="md-form mb-5"> <input type="email" name="useremail" id="Form-email1" class="form-control validate"> <label data-error="wrong" data-success="right" for="Form-email1">Ваша почта</label> </div> <div class="md-form pb-3"> <input type="password" id="Form-pass1" class="form-control validate"> <label data-error="wrong" data-success="right" for="Form-pass1">Пароль</label> <p class="font-small blue-text d-flex justify-content-end">Забыли <a href="#" class="blue-text ml-1"> пароль?</a></p> </div> <div class="text-center mb-3"> <button type="button" class="btn blue-gradient btn-block btn-rounded">ок</button> </div> <p class="font-small dark-grey-text text-right d-flex justify-content-center mb-3 pt-2"> или войти с помощью:</p> <div class="row my-3 d-flex justify-content-center"> <!--Facebook--> <button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-facebook-f text-center"></i></button> <!--Twitter--> <button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-twitter"></i></button> <!--Google +--> <button type="button" class="btn btn-white btn-rounded z-depth-1a"><i … -
Django orm left join queries without foreign keys
This is my SQL query: select (case when a.hosting <= b.yr and (a.hosting * 1000) <= b.yo then 1 else 2 end) as status from a left join b on a.phone_user = b.phone_u and a.per = b.lotus_number; I have tried the following modules: from django.db.models.sql.datastructures import Join from django.db.models.fields.related import ForeignObject I've implemented virtual fields but I don't know how to Join with subtable fields without using loops I want to give me a virtual field, but now that I can't implement it, my mind is in a loop -
TypeError: 'datetime.date' object is not subscriptable
I'm trying to create a custom template tag which takes 3 arguments. I'm trying to calculate the number of days between two dates, while excluding the weekends days from that count. And depending on the department, the weekend is different for each user. So I need start_date, end_date, user_id to be passed onto the template tag function. This is what I have done so far: from django import template from datetime import datetime, timedelta, date register = template.Library() @register.filter('date_diff_helper') def date_diff_helper(startdate, enddate): return [startdate, enddate] @register.filter(name='date_diff') def date_diff(dates, user_id): start_date = dates[0] end_date = dates[1] count = 0 weekends = ["Friday", "Saturday"] for days in range((end_date - start_date).days + 1): if start_date.strftime("%A") not in weekends: count += 1 else: start_date += timedelta(days=1) continue if start_date == end_date: break start_date += timedelta(days=1) return count This is how I'm calling these functions in template: {{ leave.start_date|date_diff_helper:leave.end_date|date_diff:leave.emp_id }} When I run the code, it gives me TypeError saying 'datetime.date' object is not subscriptable. When I tried to check the type of dates parameter in date_diff function, it says: < class 'list'> < class 'datetime.date'> But when it tries to assign start_date as the first date object, as in start_date = dates[0], it throws … -
Does 'creating' a new record override existing ones with same key?
The first code below both creates (if it doesn't exist yet) and override (if it exists) record in db. It's convenient. I would like to know if this creates problem in the DB. I reviewed the table records and it doesn't create duplicates. record = Foo(key='123', value='Hello) record.save() or try: foo_q = Foo.objects.get(key='123') foo_q.value = 'Hello' foo_q.save() except: record = Foo(key='123', value='Hello) record.save() It works but is it safe to continue using or should I query if it exists and update the model. -
Django model: TypeError: 'Manager' object is not callable
I'm developing a Rest API with django. I have this model: from django.db import models from devices.models import Device class Command(models.Model): id = models.AutoField(primary_key=True, blank=True) command_name = models.CharField(max_length=70, blank=False, default='') time = models.DateTimeField(auto_now_add=True, blank=True) timeout = models.TimeField(blank=True) command_status= models.IntegerField(blank=False) tracking = models.IntegerField(blank=False) result_description = models.CharField(max_length=200, blank=False, default='') ssid = models.CharField(max_length=31, blank=False, default='') device = models.ForeignKey(Device, on_delete=models.CASCADE) in the views I have this part of code: @csrf_exempt def command_detail(request, rssid): try: print("Heeeeeeeeeeeeeeeeeeeeeeeeelllo 1111 rssid: ", rssid) commands=Command.objects().filter(ssid=rssid) print("Heeeeeeeeeeeeeeeeeeeeeeeeelllo 2222") command=commands[0] except Command.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) If I execute my server it works fine without any error but if I trie to test the corresponding server with curl like that: curl -X POST http://127.0.0.1:8000/api/commands/cmdssid1?command_status=40 I get as curl result a so big html indicating an Internal Error in the server and in the django part I got those traces: July 30, 2019 - 08:00:01 Django version 1.10.1, using settings 'project-name.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ('Heeeeeeeeeeeeeeeeeeeeeeeeelllo 1111 rssid: ', u'cmdssid1') Internal Server Error: /api/commands/cmdssid1 Traceback (most recent call last): File "/path-to-home/.local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/path-to-home/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/path-to-home/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, … -
Exception in thread django-main-thread: TypeError:__init__() got an unexpected keyword argument 'fileno'
I am trying to perform load tests on a django application with locust. However, when I try to perform these with multiple simulated users, I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/<user>/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/<user>/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "/home/<user>/.local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 213, in run httpd.serve_forever() File "/usr/lib/python3.6/socketserver.py", line 241, in serve_forever self._handle_request_noblock() File "/usr/lib/python3.6/socketserver.py", line 315, in _handle_request_noblock request, client_address = self.get_request() File "/usr/lib/python3.6/socketserver.py", line 503, in get_request return self.socket.accept() File "/usr/lib/python3.6/socket.py", line 210, in accept sock = socket(self.family, type, self.proto, fileno=fd) TypeError: __init__() got an unexpected keyword argument 'fileno' This error seems very weird to me, because the socket __init__() function is part of a default library in which this error shouldn't occur. I suspect that the error I see here is a red herring, and that the real error is hidden, but I thought that I might as well ask here in case someone knows why this occurs. Some additional information: When I did the load test on django's built-in development server (wsgi) (i.e. started the … -
How to avoid the error This field is required without changing the model field?
How to avoid the error This field is required in modellformset without changing the model fields and allowing to call the form_valid method instead of form_invalid. That is, if the model is created, all fields are required, if the fields are empty, then it simply does not save the model, but validation passes. Now I get that all the forms must be filled in, but the user can only memorize what he needs, and leave the rest empty. Is there a solution? views.py class SkillTestCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillCreateForm template_name = 'skill_create.html' def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs)) context['formset_framework'] = SkillFrameworkFormSet(queryset=Skill.objects.none()) context['formset_planguage'] = SkillPLanguageFormSet(queryset=Skill.objects.none()) context['tech_group'] = Techgroup.objects.all() return context def post(self, request, *args, **kwargs): if 'framework' in request.POST: form = SkillFrameworkFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(request) elif 'language' in request.POST: form = SkillPLanguageFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(request) else: return self.form_invalid(request) def form_valid(self, form): """If the form is valid, redirect to the supplied URL.""" for form in form: self.object = form.save(commit=False) self.object.employee =Employee.objects.get(pk=self.kwargs['pk']) employee_current_technology = Technology.objects.filter(skill__employee__id=self.kwargs['pk']) if self.object.technology not in employee_current_technology: self.object.save() return redirect("profile", pk=self.kwargs['pk']) def form_invalid(self, request): return render(request, 'skill_create.html', {'formset_framework': SkillFrameworkFormSet(queryset=Skill.objects.none()), 'formset_planguage': SkillPLanguageFormSet(queryset=Skill.objects.none())}) Is the behavior in which I need … -
django templates index of array does not work
Index in templates of django is like this: {{somearray.i}} for my code this is not working!! this is views.py def fadakpage(request): tours = tour.objects.order_by('tourleader') travelers = traveler.objects.order_by('touri') j=0 for i in tours: j+=1 args={'tours':tours,'travelers':travelers,'range':range(j)} return render(request,'zudipay/fadakpage.html',args) this is fadakpage.html / template (it shows empty): {% for i in range %} {{tours.i.tourleader}} {% endfor %} but if i change {{tours.i.tourleader}} to {{tours.0.tourleader}} it works!! i also checked i values and it was true !! -
Improve the calculation of distances between objects in queryset
I have next models in my Django project: class Area(models.Model): name = models.CharField(_('name'), max_length=100, unique=True) ... class Zone(models.Model): name = models.CharField(verbose_name=_('name'), max_length=100, unique=True) area = models.ForeignKey(Area, verbose_name=_('area'), db_index=True) polygon = PolygonField(srid=4326, verbose_name=_('Polygon'),) ... Area is like city, and zone is like a district. So, I want to cache for every zone what is the order with others zones of its area. Something like this: def get_zone_info(zone): return { "name": zone.name, ... } def store_zones_by_distance(): zones = {} zone_qs = Zone.objects.all() for zone in zone_qs: by_distance = Zone.objects.filter(area=zone.area_id).distance(zone.polygon.centroid).order_by('distance') zones[zone.id] = [get_zone_info(z) for z in by_distance] cache.set("zones_by_distance", zones, timeout=None) But the problem is that it is not efficient and it is not scalable. We have 382 zones, and this function get 383 queries to DB, and it is very slow (3.80 seconds in SQL time and 4.20 seconds in global time). is there any way efficient and scalable to get it. I had thought in something like this: def store_zones_by_distance(): zones = {} zone_qs = Zone.objects.all() for zone in zone_qs.prefetch_related(Prefetch('area__zone_set', queryset=Zone.objects.all().distance(F('polygon__centroid')).order_by('distance'))): by_distance = zone.area.zone_set.all() zones[zone.id] = [z.name for z in by_distance] This obviously does not work, but something like this, caching in SQL (prefetch related) the zones ordered (area__zone_set). -
django static files (including bootstrap and javascript) problem
The javascript and CSS files are not properly working in dJango. I have tried all the possible ways to i could have. I have attached Index.html and settings.py files code below. // Index.html {% load static %} <title>Careers &mdash; Website Template by Colorlib</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static 'css/custom-bs.css' %}"> <link rel="stylesheet" href="{% static 'css/jquery.fancybox.min.css'%}"> <link rel="stylesheet" href="{% static 'css/bootstrap-select.min.css'%}"> <link rel="stylesheet" href="{% static 'fonts/icomoon/style.css'%}"> <link rel="stylesheet" href="{% static 'fonts/line-icons/style.css'%}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css'%}"> <link rel="stylesheet" href="{% static 'css/animate.min.css'%}"> <link rel="stylesheet" href="{% static 'css/style.css'%}"> <!-- SCRIPTS --> <script src="{% static 'js/jquery.min.js'%}"></script> <script src="{% static 'js/bootstrap.bundle.min.js'%}"></script> <script src="{% static 'js/isotope.pkgd.min.js'%}"></script> <script src="{% static 'js/stickyfill.min.js'%}"></script> <script src="{% static 'js/jquery.fancybox.min.js'%}"></script> <script src="{% static 'js/jquery.easing.1.3.js'%}"></script> <script src="{% static 'js/jquery.waypoints.min.js'%}"></script> <script src="{% static 'js/jquery.animateNumber.min.js'%}"></script> <script src="{% static 'js/owl.carousel.min.js'%}"></script> <script src="{% static 'js/custom.js'%}"></script> // Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', ] -
How to make a model in django without predefined attributes?
I am little bit confused with the django model as the title said. I also cannot find any posts in google. Let's say in the normal way, we will have a model like this: class something(models.Model): fName = models.TextField() lName = models.TextField() ...... lastThings = models.TextField() However, I don't want to have a model like this. I want to have a model with no predefined attributes. In order words, I can put anythings into this model. My thought is like can I use a loop or some other things to create such model? class someModel(models.Model): for i in numberOfModelField: field[j] = i j+=1 Therefore, I can have a model that fit in any cases. I am not sure is it clear enough to let you understand my confuse. Thank you -
Daemonization celery in production
i'M trying to run celery as service in Ubuntu 18.04 , using djngo 2.1.1 and celery 4.1.1 that is install in env and celery 4.1.0 install in system wide . i'm going forward with this tutorial to run celery as service.here is my django's project tree: hamclassy-backend ├── apps ├── env │ └── bin │ └── celery ├── hamclassy │ ├── celery.py │ ├── __init__.py │ ├── settings-dev.py │ ├── settings.py │ └── urls.py ├── wsgi.py ├── manage.py └── media here is celery.py : from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hamclassy.settings') app = Celery('hamclassy') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() here is /etc/systemd/system/celery.service: [Unit] Description=Celery Service After=network.target [Service] Type=forking User=classgram Group=www-data EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/home/classgram/www/classgram-backend/hamclassy/celery ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target and /etc/conf.d/celery: CELERYD_NODES="w1" CELERY_BIN="/home/classgram/www/env/bin/celery" CELERY_APP="hamclassy.celery:app" CELERYD_CHDIR="/home/classgram/www/classgram-backend/" CELERYD_MULTI="multi" CELERYD_OPTS="--time-limit=300 --concurrency=8" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_LOG_LEVEL="INFO" when i run service with systemctl start celery.service the error appear: Job for celery.service failed because the control process exited with error code. See "systemctl status celery.service" and "journalctl -xe" for detail when i … -
Most Pythonic/Django way to dynamically load client libraries at runtime
I'm writing a Django application in which we will have multiple client libraries that make calls to third party APIs. We want to be able to determine which client library to load at runtime when calling different endpoints. I'm trying to determine the most Django/Pythonic way to do this The current idea is to store class name in a model field, query the model in the View, and pass the class name to a service factory that instantiates the relevant service and makes the query. I've also considered writing a model method that uses reflection to query the class name For example lets say we have a model called Exchange that has an id, a name, and stores the client name. class Exchange(models.Model): exchange_name = models.CharField(max_length=255) client_name = models.CharField(max_length=255) def __str__(self): return self.exchange_name Then in the View we might have something like: from rest_framework.views import APIView from MyProject.trades.models import Exchange from django.http import Http404 from MyProject.services import * class GetLatestPrice(APIView): def get_object(self, pk): try: exchange = Exchange.objects.get(pk=pk) except Exchange.DoesNotExist: raise Http404 def get(self, request, pk, format=None): exchange = self.get_objectt(pk) service = service_factory.get_service(exchange.client_name) latest_price = service.get_latest_price() serializer = PriceSerializer(latest_price) return Response(serializer.data) This syntax may not be perfect but it hasn't been … -
Django - Can not upload file using my form
Here's the situation: I'm quite new to Django and I'm trying to upload some files using a form I created. When I click on the submit button, a new line is created in my database but the file I selected using the FileField is not uploaded.But I can upload files via the admin page without any trouble. I've been trying to find a solution for a while now, but I still haven't found anything that could help me, so if one of you has any idea how to solve my problem I would be really thankful. Here you can find some code related to my form: forms.py class PhytoFileForm(forms.ModelForm): class Meta: model = models.PhytoFile fields = ['general_treatment', 'other'] def __init__(self, *args, **kwargs): super(PhytoFileForm, self).__init__(*args, **kwargs) models.py class PhytoFile(models.Model): date = models.DateTimeField("Date", default = datetime.datetime.now) general_treatment = models.FileField("Traitements généraux", upload_to='fichiers_phyto/', blank=True, null=True) other = models.FileField("Autres traitements", upload_to='fichiers_phyto/', blank=True, null=True) class Meta: verbose_name = "Liste - Fichier phyto" verbose_name_plural = "Liste - Fichiers phyto" def __str__(self): return str(self.date) views.py class AdminFichiersPhyto(View): template_name = 'phyto/phyto_admin_fichiers.html' form = forms.PhytoFileForm() def get(self, request): return render(request, self.template_name, {'form': self.form}) def post(self, request): form = forms.PhytoFileForm(request.POST, request.FILES) form.save() return render(request, self.template_name, {'form': self.form}) phyto_admin_fichiers.html {% block forms … -
Throttles connection in day using Djang REST Framework
I want to limit the amount of connection to the web in a day. I have searched on Internet that using Djano REST Throttling, but I don't know how to use Django REST API. I wish I had a sample code to solve the problem. Thanks. -
Setting cache in nginx does not delete files for inactivity
I have an S3 bucket and AWS RDS Postgres database attached to my EC2 instance. I want to reduce S3 egress by setting up a linux server that caches data. For that reason I have attached the uWSGI of my django app to a nginx server. Although I have specified the inactive time for the proxy_cache_path, the cached files do not get deleted from my folder. Please help. I have set up the nginx.conf file in sites-available and created a symlink in sites-enabled and reload my nginx server. This is my conf file: ` proxy_cache_path /home/clyde/Downloads/new/automatic_annotator_tool/queried_data keys_zone=mycache:10m inactive=2m use_temp_path=off max_size=1m; upstream django { server local_ip; } server { listen 8000; server_name public_ip; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /static { alias /home/clyde/Downloads/new/automatic_annotator_tool/django_app/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /etc/uwsgi/sites/uwsgi_params; proxy_cache mycache; } location /images { alias /home/clyde/Downloads/new/automatic_annotator_tool/queried_data; proxy_cache mycache; expires 2m; proxy_cache_valid any 2m; } location /nginx_status { stub_status; allow public_ip; deny all; } } This is the uwsgi command i run for starting the webserver: uwsgi --socket :8001 --module uvlearn.wsgi -p 2 --master` … -
How include location when upload photo?
I'm using IstangramApi this is my py: from InstagramAPI import InstagramAPI InstagramAPI = InstagramAPI("username", "password") InstagramAPI.login() # login photo_path = '/home/user/image/index.jpeg' caption = "Sample photo" location = "Rome" InstagramAPI.uploadPhoto(photo_path, caption=caption, location=location) without location it work... how can i post with location? It seems not official documentation.... Please Help -
How to add new input text in admin page in django?
Whenever I try to add new user in django admin page, it gives me username, password and new password input text but I have added Id_payment also in registration page but it is not showing. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id_number = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id_number'] -
Django form hidden field but previously load with value
I have a form with 6 field where 2 of then need to be preloaded with a specific values. Then I need those 2 fields to be hidden since the user doesn't need to deal this those. I found plenty of ask here in stackoverflow, most of the are applicable to my problem using HiddenInput() method, but when I preload the field, the HiddenInput() method doesn't work any more. here is my forms.py code class SurveyCreateForm(BSModalForm): def __init__(self, *args, **kwargs): self.wellbore = kwargs.pop('wellbore', None) self.profile = kwargs.pop('profile', None) super(SurveyCreateForm, self).__init__(*args, **kwargs) self.fields['wellbore'] = forms.ModelChoiceField(queryset=Wellbore.objects.filter(pk=self.wellbore), empty_label=None) self.fields['profile'] = forms.ModelChoiceField(queryset=SurveyProfile.objects.filter(pk=self.profile), empty_label=None) class Meta: model = Survey fields = ['wellbore', 'profile','md','inc','azm','time_stamp'] # Django Form : 2 : Model Forms @2:45 labels = {'wellbore':'Wellbore', 'profile':'Profile','md':'MD','inc':'Inclination','azm':'Azimuth','time_stamp':'Date Time'} widgets = {'wellbore':forms.HiddenInput(), 'profile':forms.HiddenInput() } and here the html template <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Add New Survey</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div style="margin: 10px 10px 10px 10px;"> <table> {{ form.as_table }} </table> </div> <div class="modal-footer"> <p> <button type="button" class="submit-btn btn btn-primary">Save</button> </p> </div> </form> I need those fields to be populated but at the same time hidden from the user. Thanks in advance. -
How to render two form fields as one field in Django forms?
I'm working on Django application where I need to render a form differently. The form contains multiple fields related to a person. Firstname Lastname email address city country Phone Pincode There are two flows in my application. In the first flow I can render all the form fields and save them when the user enters some data and submit. But in the second flow, I need to display only three fields as below. Name - Combination of Firstname and Lastname Email Phone The data entered in the name field should be split and saved as Firstname and Lastname. And for other remaining mandatory fields in the form that are not rendered, I can fill empty values and save the model in Backend. What is the best way to render the forms differently for each flow? Python: 3.7.3 Django: 2.1.5 -
when I deploy my project to heroku, it is not sending a confirmation email on signup but when I signup in my local computer I get the mail
django app gaierror at / [Errno -2] Name or service not known Request Method: POST Request URL: https://mangoinstagram2.herokuapp.com/ Django Version: 1.11 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /app/.heroku/python/lib/python3.6/socket.py in getaddrinfo, line 745 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Tue, 30 Jul 2019 09:07:58 +0300 -
Dynamic choices model
I'm working on my first commerce website. I have various products with totally different choices.(models,colors,quality,etc) So I want each of my products to have different choices. I'm confused what kind of Field should I add to my product Model. And how to I manage to add choices to each product. Thank you very much class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.DecimalField(max_digits=5,decimal_places=2) category = models.ForeignKey('Category', null=True, blank=True,on_delete=models.DO_NOTHING) slug = models.SlugField(default='hello') image = models.ImageField(null=True, blank=True) available = models.BooleanField(default=True) -
How to set the time for AXES_LOCK_OUT_AT_FAILURE in django?
I am trying to lockout the users if the user attempt too many failed login attempts.And after 5 minutes I want to give access to login user again and I tried like this.I followed this documentation and write this settings in my settings.py file.However i failed to set the times for AXES_COOLOFF_TIME.I got this error : Exception Type: TypeError Exception Value: can't subtract offset-naive and offset-aware datetimes settings.py INSTALLED_APPS = [...., 'axes',] AUTHENTICATION_BACKENDS = ['axes.backends.AxesBackend',] MIDDLEWARE = [..............., 'axes.middleware.AxesMiddleware', ] from django.utils import timezone now = timezone.now() AXES_COOLOFF_TIME = now + timezone.timedelta(minutes=5) -
Use Django Permission in Pure Javascript
I used Django Permission in Django Template before like {% if perms.assets.change_log %} and it works. I want to this to render a server-side datatable in JavaScript but it failed, like <script> console.log(perm.assets.change_log) </script> There is nothing output on the console. Could you please help me with this? Thanks a lot. -
How to filter through textfield in models in django
I am trying to create a small search feature within my django project and i need to filter through my data My models are all in textfield formats, and when i try to use .filter() to search for what i want, i get an error saying that an instance of textfield has no filter. is there any way to work around this? #My Model class api_data(models.Model): data_source = models.TextField() brief_description_of_data = models.TextField() datasets_available = models.TextField() brief_description_of_datasets = models.TextField() country = models.TextField() api_documentation = models.TextField() #what I'm trying to do def index(request): query = request.Get.get('q') if query: queryset_list = api_data.datasets_available.filter(Q(title__icontains=query))