Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
select anwser ajax model query django
Hi i make a search field in django it's work but i want select the result of the query and put it in the fiels search fields, i already use <select> or <datalist> but it's don't work. how do it. my code: views.py: def searchPlanteur(request): if request.method == 'POST': form = PacageForm(request.POST) planteurs = "" if form.is_valid(): pacPlan = form.cleaned_data planteurSearch = pacPlan['planteurSearch'] value = request.POST['planteurSearch'] planteurs = Planteur.objects.filter(pacage__contains=value) if planteurs == None: planteurs = 'Auncun planteur ne correspond au pacage renseigner. Veuillez rentrer un pacage valide' return render(request, 'blog/ajax/ajax.html', {'planteurs' : planteurs}) def ajax_query(request): if request.method == 'POST': form = PacageForm(request.POST) if form.is_valid(): pacPlan = form.cleaned_data planteurSearch = pacPlan['planteurSearch'] value = request.POST['planteurSearch'] planteurs = Planteur.objects.objects.filter(pacage__contains=value) return HttpResponseRedirect('blog/ajax_query.html', {'planteurs': planteurs}) else: form = PacageForm() return render(request, 'blog/ajax_query.html', {'form': form}) urls.py: from django.conf.urls import url from . import views app_name ='blog' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^posts/(?P<id>[0-9]+)$', views.show, name='show'), url(r'^planteur/$', views.planteur, name='planteur'), url(r'^mouvement/$', views.mouvement, name='mouvement'), url(r'^ajax/planteur/$', views.searchPlanteur, name='searchPlanteur'), url(r'^ajax_query/$', views.ajax_query, name='ajax_query'), #url(r'^ajax_query/blog/ajax_query.html/$', views.ajax_query, name='ajax_query'), url(r'^autocomplete/$', views.autocomplete, name='autocomplete'), url(r'^get_planteurs/$', views.get_planteurs, name='get_planteurs'), forms.py: class PacageForm(forms.Form): planteurSearch = forms.CharField(label='planteurSearch', max_length=100, widget=forms.TextInput(attrs={'onkeyup': 'planteur_suggestion()', 'placeholder': 'planteur_datalist', 'list': "pacageListe",})) def clean_planteurSearch(self): try: planteurSearch = int(self.cleaned_data["planteurSearch"]) except: planteurSearch = "Auncun planteur ne correspond au pacage renseigner. Veuillez … -
Retrieve all the values of one column of Dataset in Django
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) Suppose I have this dataset. I want to retrieve all the names of the cities in an array. Help me -
django serialize( data to convert the default serializer response to desired format)
I need to convert the response like this using serializers.py.Where id is from model Mymodel and Total_login_hours is from model class Mymodel(models.Model): status = models.CharField(max_length=50, choices=BIKER_STATUS_CHOICES, default='active') name = models.CharField(verbose_name=_('Biker Name'), max_length=254) classLoginModel(models.Model): biker = models.ForeignKey(Mymodel, db_index=True, on_delete=models.PROTECT) total_loginhrs = models.TimeField(null=True, blank=True) I have a response as shown below by using django serializer in django rest framework { "count": 1, "next": null, "previous": null, "results": [ { "id": 128, "totaldata": [ { "City": "abc", "Locality ": "def", "Biker_name": "xyz", "Total_login_hours": "00:28:41", "Date": "2018-01-13", "Sublocality": "qwe" }, { "City": "asd", "Locality ": "fgh", "Biker_name": "zxc", "Total_login_hours": "00:02:33", "Date": "2018-01-14", "Sublocality": "cvb" } ] } ] } ] } I need to convert the response like this using serializers.py Where id is from model Mymodel and Total_login_hours is from model { "count": 2, "next": null, "previous": null, "results": [ { "id": 128, "totaldata": [ { "City": "abc", "Locality ": "def", "Biker_name": "xyz", "Total_login_hours": "00:28:41", "Date": "2018-01-13", "Sublocality": "qwe" }], "id": 128, "totaldata": [ { "City": "asd", "Locality ": "fgh", "Biker_name": "zxc", "Total_login_hours": "00:02:33", "Date": "2018-01-14", "Sublocality": "cvb" } ] } ] } i am a fresher in python..can you please give me a solution for the same.How can we repeat id in … -
Django+uWSGI+nginx server configuration, no file .sock?
structure: /data # General directory for projects on the server -------- mysite # Directory for the website mysite -------- -------- conf # Configuration files for the web server mysite_nginx.conf mysite_uwsgi.ini -------- -------- project # Project code -------- -------- --------firstsite #Here settings wsgi -------- -------- venv # The directory for the virtual environment # mysite_nginx.conf # the upstream component nginx needs to connect to # Если будете настраивать несколько django сайтов - измените название upstream upstream django { server unix:///data/mysite/mysite.sock; # for a file socket } # configuration of the server server { listen 80; # порт на котором будет доступен ваш сайт server_name .example.com; # доменное имя сайта charset utf-8; client_max_body_size 75M; # max upload size # Django media location /media { alias /data/mysite/project/media; } location /static { alias /data/mysite/project/static; } location / { uwsgi_pass django; include uwsgi_params; } } # mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /data/mysite/project # Django's wsgi file module = project.wsgi # the virtualenv (full path) home = /data/mysite/env/virtualenv # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket socket = /data/mysite/mysite.sock # ... with appropriate permissions - … -
Multiple Bootstrap Modals to pop on demand only, in django. I tried to separate modal and <button data-target=""> into two files which is not working
I wanted to display multiple modals on demand - pop up. Problem comes when I try to put the trigger(button or anchor tag) to pop modal and modal's html code in two separate html files.I'm not sure how to do it. This is my html file, through which I need multiple modals to pop when I click <a> tag. I have a modal in another html file, main.html: {% for pk,obj in data %}<br> <div class="col-md-6 "> {{ obj }} </div> <div class="col-md-6 "> <a href="{% url 'api-predata' %}" data-target="#{{ pk }}">Launch modal</a> </div> <br> {% endfor %} modal.html: <!-- Button trigger modal --> {% load crispy_forms_tags %} {% if data %} {% else %} <button type="button" class="btn btn-success" data-toggle="modal" data-target="#first_apc"> Create one </button> {% endif %} <!-- Modal --> <div class="modal fade bd-example-modal-lg" id="{{ pk }}" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header" align="center"> Submit Form </div> <div class="modal-body"> <div class="col-md-12"> {{ form.journalname | as_crispy_field }} </div> <div class="col-md-3 col-md-offset-2"> <button class="btn btn-primary"> Submit </button> </div> </div> </div> </div> </div> -
Strange cache bug after repreating the same task in django App
i'm about to finish my current project, i was doing repeated test to see if everything was going fine. The goal of the app is pretty simple, on the index page the user can choose to create a "movement'. When he click on the creation button, he is redirected on the creation page, fill the form and send it. A new entry is created and displayed in the index tab. When he click on the creation button, the app create an empty "movement" key in redis, fill it with the basic informations, the key is then updated with the informations submited in the form. every hit on the creation button create a new key in redis and a new entry in the database, the redirected page contain a pk in the url that correspond to the "movement" ID. at the start most of the values are set to NULL so almost every input field on the page is filled with "NULL" (all the fields are set to django tags that refer to the redis values) That mean that every creation page is full of "NULL" when the user is redirected on it, or at least it should. My current problem … -
How do I pay for a one year plan Heroku
Hello I am new here i am trying to pay heroku for my django application but i want to use the one month $7 plan for a year without having to renew every month any help would be appreciated thanks. -
Tight coupling in Django models
I have django model which contains incident_type and closed fields. Based on this fields I need to return functions that render some text. Is it okay to have such get_renderer method in models or I should move this logic somewhere else? In my understanding, this method violates single responsibility principle. class Incident(models.Model): BAD_RESPONSE = 'bad_response' SLOW_RESPONSE = 'slow_response' INCIDENT_TYPE_CHOICES = ( (BAD_RESPONSE, 'Webpage is not available'), (SLOW_RESPONSE, 'Webpage is slow'), ) incident_type = models.CharField(max_length=50, choices=INCIDENT_TYPE_CHOICES) closed = models.BooleanField() def get_renderer(self): if self.incident_type == self.BAD_RESPONSE: if self.closed: return render_page_up_screen else: return render_page_down_screen -
Docker crontab: not found
Sorry for my english. I use django-crontab in my project. Localy in my project work fine. But i want use Doker, when i run Docker i have error: /bin/sh: 1: /usr/bin/crontab: not found my docker-compose version: '2.0' services: web: build: . container_name: test_api volumes: - .:/usr/django/app/ expose: - "8000" env_file: main.env command: bash django_run.sh nginx: build: ./nginx container_name: test_ng ports: - "8000:8000" volumes: - ./nginx/api.conf:/etc/nginx/conf.d/api.conf - .:/usr/django/app/ depends_on: - web links: - web:web django_run.sh #!/usr/bin/env bash set -e if [ "$ADD_CRON" == "true" ]; then python manage.py crontab show fi if [ "$ADD_CRON" == "true" ]; then python manage.py crontab add fi if [ "$ADD_CRON" == "true" ]; then python manage.py crontab show fi if [ "$ADD_CRON" == "true" ]; then python m/usr/local/bin/gunicorn ${DJANGO_APP}.wsgi:application --timeout ${GUNICORN_TIMEOUT} --keep-alive ${GUNICORN_KKEP_ALIVE} -k gevent -w ${GUNICORN_WORKERS} --threads ${GUNICORN_THREADS} -b :${GUNICORN_PORT} my logs: test_api | /bin/sh: 1: /usr/bin/crontab: not found test_api | Currently active jobs in crontab: test_api | /bin/sh: 1: /usr/bin/crontab: not found test_api | sh: 1: /usr/bin/crontab: not found test_api | adding cronjob: (649feb1a8431f09891b644aa4ba2075b) -> ('*/1 * * * *', 'cron.cron_jubs.clear_pdf_files_scheduled_job', '>> /tmp/scheduled_job.log') test_api | /bin/sh: 1: /usr/bin/crontab: not found test_api | Currently active jobs in crontab: test_api | [2018-03-15 14:23:41 +0000] [35] … -
Django, query objects BEFORE certain id
I have encountered one interesting problem Lets say I have objects in my database likt this: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Lets consider numbers as ids of these objects If I want to get two objects after 5, I need to use this query: MyObject.objects.filter(id_gt=5).order_by("id")[:2] This will return to me this result: [6, 7] Which is right result. Now I want to get two objects before object 5. I do this query: MyObject.objects.filter(id_lt=5).order_by("id")[:2] However, this returns to me this: [1, 2] instead of [3, 4] So I need to query objects starting from object of id=5 I know that there is ranged query, but it does not suit when working only with ids. Is it possible to query objects before certain id starting from this object itself? -
What do I have to do if I don't want to use basic auth on Django?
I'm new to Django. I'm working on a project, so now I'm making the login feature. And the thing I've got noticed is, when I log in, the Authorization type that I use, which is basic authentication, could be dangerous. So I thought I need to find another way to authenticate when I send a request to the server. What do I have to do if I don't want to use basic auth? -
How to propertly style login/signup forms in django-allauth?
What is actually the correct way to have my own login forms in django-allauth? 1) Should I use {{ form.as_p }} and create my own LoginForm class. Where should I insert my HTML code then? 2) Should I not use {{ form.as_p }} at all and do my own HTML markup with every form field in my signup.html template. Thanks. -
how to save QR Code number in database Sqlite
I have a number and i´d like to transforme it in qr code and save into my database SQLite. Then i have to show this qr code on the screen and i don´t know how to do that. -
Heatmaps using leaflet.js and Django
I'm working on django frame work ,can anyone help me on how to create a Heat map in django using any javascript framework and populate it custom location points. -
mod_wsgi: Exception occurred processing WSGI script (django deployment)
I'm trying to deploy a django project with the following Apache configuration: Apache virtualhost configuration <Virtualhost *:80> DocumentRoot /var/www/project/backend ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIDaemonProcess backend python-home=/var/www/project/myenv python-path=/var/www/gestor_documental/backend WSGIProcessGroup backend WSGIScriptAlias / /var/www/project/backend/backend/wsgi.py process-group=backend Alias /static/ /var/www/project/backend/static/ <Directory /var/www/project/backend> Require all granted </Directory> </Virtualhost> wsgi.load file LoadModule wsgi_module "/var/www/project/myenv/lib/python3.5/site-packages/mod_wsgi/server/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so" WSGIPythonHome "/var/www/project/myenv" The wsgi.py is the one django brings by default This is the project tree: project |- backend | |- api (django app) | |- backend | |- ... | |- settings.py | |- wsgi.py |-- myenv (virtualenv) And this is the error log I keep getting when i try to load the web: mod_wsgi (pid=38953): Failed to exec Python script file '/var/www/project/backend/backend/wsgi.py'. mod_wsgi (pid=38953): Exception occurred processing WSGI script '/var/www/project/backend/backend/wsgi.py'. Traceback (most recent call last): File "/var/www/project/backend/backend/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/var/www/project/myenv/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/var/www/project/myenv/lib/python3.5/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/var/www/project/myenv/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/var/www/project/myenv/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/var/www/project/myenv/lib/python3.5/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/var/www/project/myenv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File … -
Django: How to filter my models (by child)?
Making my university project, I've described several models for e-commerce of goods: Item, Book(Item), Stationery(Item), and ItemImage (related by ForeignKey for all Item-like models). So, I need to filter the set of item images in the following way: def home(request): goods_images = ItemImage.objects.filter(is_active=True, is_main=True) goods_images_books = ItemImage.objects.filter(is_active=True, is_main=True) goods_images_stationeries = ItemImage.objects.filter(is_active=True, is_main=True) return render(request, 'landing/home.html', locals()) The question is what the additional parameter I should add to filter() or implement another way of solving this problem. -
click a form button based on the url parameters passed
I am trying to get this working from a long time now but cannot seem to get it right- my x.html- <div class="col-lg-2 col-lg-offset-4"> <a href="#add" id="addform" role="button" class="btn btn-info pull-right" data-toggle="modal" style="margin-top:20px">Add Contract</a> </div> {% include "a_bs3.html" with form_title="Add :" form_btn="Add" form_id="add" ajax="True" %} <script> $(document).ready(function() { var check = location.hash; if (check == "trigger") { //button trigger even though you do not click on it $('#addform').click(); } }); </script> I am trying to trigger this 'Add :' form button whenever the url contains a value "trigger" but the button is not auto-clicking, what am I doing wrong? If you click 'Add :' manually- the form opens up just fine. -
Django admin shows randomly 504 Gateway Time-out
In the django admin, when openning the change_list view of one of my django models I sometimes (not always) get a "504 Gateway Time-out" after about 5 seconds. When the error appears, there's an "Ignoring EPIPE" message in the gunicorn log. It's an supervisor-gunicorn-nginx-django environment. In the supervisor configuration I tried timeout=60 In the nginx configuration I've got proxy_connect_timeout 60; proxy_read_timeout 90; proxy_send_timeout 90; If I remove most of the elements of the model, it seems the error disappears but I'm not completely sure about this. -
stringreplace on Django
I need to do the 'string replace' on all my queryset, but I receive the following error: 'QuerySet' object has no attribute 'replace' def get_profilesJson_view(self): queryset = Reports.objects.all().values('val_x','val_y').order_by('-time_end')[:1] new_queryset = queryset.replace(queryset, ';', ',') reports_list = list(new_queryset) return JsonResponse(reports_list, safe=False) How can I do? Is it possible to use the '.filter' function? I have not experience with Django -
I am working with Django, During inserting data into database i caught such error
I'm working with django, during inserting data into tables the error is generates as given below... Error: int() argument must be a string, a bytes-like object or a number, not 'Tbl_rule_category', How can we solve such error? view.py dataToRuleCtgry = Tbl_rule_category(category=category, created_by="XYZ",created_date=datetime.date.today()) dataToRuleCtgry.save() dataToRule = Tbl_rule(rule_name=rule_name, closure=closure,category_id=Tbl_rule_category.objects.latest('category_id'), created_by="XYZ",created_date=datetime.date.today(), updated_by="XYZ", updated_date=datetime.date.today(), rule_type=rule_type, fk_tbl_rule_tbl_rule_category_id=Tbl_rule_category.objects.latest('category_id')) dataToRule.save() models.py class Tbl_rule_category(models.Model): category_id = models.AutoField(primary_key=True) category = models.CharField(max_length=50) created_by = models.CharField(max_length=50) created_date = models.DateField(auto_now_add=True) def __str__(self): pass # return self.category, self.created_by class Tbl_rule(models.Model): rule_id = models.AutoField(primary_key=True) rule_name = models.CharField(max_length=50) closure = models.CharField(max_length=50) category_id = models.IntegerField() created_by = models.CharField(max_length=50) created_date = models.DateField(auto_now_add=True) updated_by = models.CharField(max_length=50) updated_date = models.DateField(auto_now=True) rule_type = models.CharField(max_length=50) fk_tbl_rule_tbl_rule_category_id = models.ForeignKey(Tbl_rule_category,on_delete=models.CASCADE, related_name='fk_tbl_rule_tbl_rule_category_id_r') def __str__(self): return self.rule_name, self.closure, self.created_by, self.updated_by, self.rule_type -
Django Hierarchy Permissions
I want to have hierarchical level permissions in my Django Applications. For eg:- Consider there are 4 levels - Admin Sub-admin(CountryLevel(CL) Admin) sub-sub-admin(StateLevel(SL) Admin) And then normal Users(U). Admins will create CL, in return CL will create SL, and SL will finally onboard the users. The end goal is to onboard the users. Admins have the access to apply CRUD operation on any user. CL should have access to those users(objects) which were onboarded(created) by the CL created SLs. In return, SL should have access to only those users(objects) onboarded(created) by him. Also, a user can get himself registered directly without any admins involved. In such case, the user shall have access to his own application. How can I achieve such tree-level like permissions? The solution that I can think of is (but not sure about it):- I've updated auth_group table and added parent_id into it. Following is the schema. id, group_name, parent_id The significance of parent_id is to create a tree-like structure of the groups. The number of groups created is equal to the height of the tree. For eg consider following structure:- id, group_name, parent_id 1 , admin, 0 2, CL, 1 3, SL, 2 Now when any … -
how can i Validate my email id already exist in database
how can i Validate my email id already exist in database. how can i Validate my email id already exist in database. how can i Validate my email id already exist in database. how can i Validate my email id already exist in database. how can i Validate my email id already exist in database. how can i Validate my email id already exist in database. how can i Validate my email id already exist in database. how can i Validate my email id already exist in database. views.py from django.shortcuts import render from django.http import * from myapp.forms import User from django.contrib import messages from myapp.models import reg def registration(request): if request.method=='POST': form = User(request.POST) if form.is_valid(): id=form.cleaned_data['email'] dbuser = reg.objects.filter(email=id) if not dbuser: form.save(commit=True) messages.success(request, 'Registraion succesfull') return HttpResponseRedirect('/registration/') else: messages.error(request,'id is already available') return HttpResponseRedirect('/registration/') else: form=User() return render(request,'registration.html',{'form':form}) models.py from django.db import models class reg(models.Model): username=models.CharField(max_length=20) fname = models.CharField(max_length=20) lname = models.CharField(max_length=50) email = models.EmailField(max_length=50,primary_key=True) password=models.CharField(max_length=20) def __str__(self): return self.username forms.py from myapp.models import reg from django import forms class User(forms.ModelForm): username=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'enter username'}), required=True,max_length=50) email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'enter email'}), required=True, max_length=50) fname = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'enter firstname'}), required=True, max_length=50) lname = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', … -
How i create diff. list_filters for superuser and staff user
In admin i want to display diff. list_filter for superuser and staff user. How it possible. When superuser is logged in: list_filter = ('is_active', 'membership_type', 'is_blocked') and for staff user with limited permission list_filters should be: list_filter = ('is_active',) -
AttributeError: 'module' object has no attribute 'home'
from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.contrib import admin from profiles import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Im doing this project with Django 1.10 in virtualenv but it keeps doing this #error. -
Django 1.11: "global name 'user' is not defined"
I have a survey app - you create a Survey and it saves the Response. It's registered in Django Admin. I can see the Survey and submit a Response. When I click Response in Admin, I get the following error: ValueError at /admin/django_survey/response/ Cannot query "response 5f895af5999c49929a522316a5108aa0": Must be "User" instance. So I checked the SQL database and for django_survey_response I can see that there is a response, but the column user_id is NULL. I suspected that there's an issue with my Views and/or Forms and I'm not saving the logged in User's details, so I've tried to address that. However, now I get NameError at /survey/1/ global name 'user' is not defined How do I resolve this? I want the form to save Response with the logged in user's ID. The Traceback: django_survey\views.py def SurveyDetail(request, id): survey = Survey.objects.get(id=id) category_items = Category.objects.filter(survey=survey) categories = [c.name for c in category_items] print 'categories for this survey:' print categories if request.method == 'POST': form = ResponseForm(request.POST, survey=survey) <......................... if form.is_valid(): response = form.save() return HttpResponseRedirect("/confirm/%s" % response.interview_uuid) else: form = ResponseForm(survey=survey) print form django_survey\forms.py def __init__(self, *args, **kwargs): # expects a survey object to be passed in initially survey = kwargs.pop('survey') self.survey …