Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
checking if values are the same in django form
I have 2 models and am using 1 form to update both of them ,, models.py class Item(models.Model): item_category = models.ForeignKey(Category, on_delete="PROTECT") item_name = models.CharField(max_length=100, null=False) item_quantity = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True, editable=False) created_by = models.CharField(max_length=250, editable=False) def ___str__(self): return self.item_name class ItemOut(models.Model): item_name = models.CharField(max_length=100, null=False) item_quantity = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, editable=False) created_by = models.CharField(max_length=250, editable=False) def __str__(self): return self.item_name here is the form that creates a new entry into Item model and only updates 1 field in the ItemOut table which is item_name start with creating 2 forms in my forms.py class AddItemForm(forms.ModelForm): class Meta: model = Item exclude = ('created_by', 'created_at', ) labels = { 'item_category': 'إسم الفئة ', 'item_name': 'إسم الصنف', 'item_quantity': 'الكمية', } class AddItemOutForm(forms.ModelForm): class Meta: model = ItemOut fields = ('item_name',) labels = { 'item_name': 'تأكيد إسم الصنف', } then used 1 view function to render the form views.py def add_item(request): current_user = request.user if request.method == 'POST': new_item = AddItemForm(request.POST, request.FILES) new_item_out = AddItemOutForm(request.POST, request.FILES) if new_item.is_valid(): if new_item_out.is_valid(): item_out = new_item_out.save(commit=False) item_out.save() item = new_item.save(commit=False) item.created_by = current_user item.save() return redirect('cat') else: new_item = AddItemForm() new_item_out = AddItemOutForm() all_cats = Category.objects.all() cat_count = all_cats.count() item_count = Item.objects.all().count() all_units = Item.objects.aggregate(Sum('item_quantity'))['item_quantity__sum'] … -
Django load static file a jquery script
I have two Django templates, one for the detail-update view and one for the create view. I use a simple jquery script to show/hide html fields depending on the selected component_type by the user. However this jquery script is identical for the create and detail-update templates (violates DRY-principle). So I would like to save it in a seperate file. How to do this, the code below is not working? The create template is saved at MyApp/templates/MyApp/create.html and is defined as follows: {% extends 'base.html' %} {% load static %} <script src="{% static 'js/jquery_script.js' %}"></script> {% block content %} <h2>Create new component</h2> {% include 'snippets/form-snippet.html' with form=form %} {% endblock %} I have the script saved at MyApp/static/MyApp/js/jquery_script.js and is defined as follows: <script> {% block jquery %} $(document).ready(function(){ hideShow() }) $('#id_component_type').click(function(){ hideShow() }); function hideShow(){ if(document.getElementById('id_component_type').options[document.getElementById('id_component_type').selectedIndex].value == "k_v") { $('#id_length').parents('p:first').hide(); $('#id_k_v').parents('p:first').show(); }else { $('#id_length').parents('p:first').show(); $('#id_k_v').parents('p:first').hide(); } } {% endblock %} </script> My settings file should be configured correctly (with debug=True at least). Some of the applicable settings: STATIC_URL = '/static/' INSTALLED_APPS = [ 'other installed apps...', 'django.contrib.staticfiles', ] -
Add get parameter ONLY value, with existing keys?
I'm using form with python&django. I want to append get parameter, for only it's value. For example, I want to this result (%2C means %) ?order_status__in=1%2C2 So that I can receive 1 or 2 both for order_status get key. But when I submit form, my get params go like this ?order_status__in=1&order_status__in=2 How can I append only get param's value, not whole keys? Below is my form example. (using django) <form action="" method="GET" id="customForm"> {% for s in status %} <label for="{{ s.id }}" style="display: inline;"> <input type="checkbox" value="{{ s.id }}" name="order_status__in" id="{{ s.id }}"{% if s.get_str_id in request.GET.order_status__in %}checked{% endif %} > {{ s.title }}</label> {% endfor %} <input type="submit" value="search"> </form> -
no table create in db.sqlite3 after migrate and makemigrates in Django
I did this command and after that, only the db file was created without any tables. python manage.py makemigrations python manage.py migrate also I use the appname in this commands but nothing changed. after that, I saw this db file: enter image description here -
httplib2 request post file to rest api
I want to upload file in django rest framework api.But I want to get the file from request.FILES and then use httplib2 to post this file to another django rest api.What should i do? I have a look at httplib2 but not found file param to do this -
Django filtering many to many as separate records
I have such models: class Something(Model): """ fields here """ class SomethingHelper(Model): name = TextField() something = models.ManyToManyField(Something, default=None) So what I need to do is: if SomethingHelper has many related objects in something field, get all of them as separate queryset objects, for example: {id=0, name="first_one", something=something1}, {id=0, name="first_one", something=something2}, {id=0, name="first_one", something=something3} not {id=0, name="first_one", something=QuerySet([something1, something2, something3])} as is by standard filtering. Is this possible in Django ? Can you please suggest something ? Thanks -
automatically create a model object when an object of another table is created or updated in django models
I have two models in Django and I want to automatically create an object of History when an object of Food is created or updated and set the food_price attribute of History to the price attribute of the created Food object. My purpose is to have a history of food change price. How can I achieve that? My models.py is: class Food(models.Model): food_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30, null=False, blank=False) desc = models.TextField(max_length=200) price = models.IntegerField(null=False, blank=False) f_thumbnail = models.ImageField(upload_to=get_food_t_image_name) DDD_data = models.ImageField(upload_to=get_food_d_image_name) availability = models.BooleanField(default=True) discount = models.IntegerField(default=0) def __str__(self): return '%s %s %s' % (self.name, self.category_id, self.price) class History(models.Model): id = models.AutoField(primary_key=True) food_id = models.ForeignKey(Food, on_delete=models.CASCADE) food_price = models.IntegerField() history_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s %s %s' % (self.id, self.food_id.name, self.food_id.price) Thanks in advance. -
Send JSON as POST to Django using Ajax
I'm looking to send some JSON POST data to a URL in Django which enforces CSRF protection. My Ajax looks like this: $.ajax({ type: "POST", url: '/change_ref/'+hash+"/", data: {"csrfmiddlewaretoken": "{{ csrf_token }}", "new_ref": newref}, contentType: "application/json; charset=utf-8", dataType: "json", success: function(data){ $('#changeref').modal('hide'); alert('Success!'); }, failure: function(errMsg) { alert('Failure! ' +errMsg); } }); My idea is to then parse the JSON on the backend. However, when I examine the POST data passed to the server, it is empty (as seen by CSRF middleware): This happens also when I wrap the JSON data with JSON.stringify(). The only way I have POST requests working so far is with application/x-www-form-urlencoded Mimetype, but this is undesirable. My settings.py is pretty vanilla. Are there any extra steps needed in order to make JSON POSTs in Django, or is there something blatantly wrong with this code? Thanks -
Django object - where does it inherit from?
i' ve a Django model object. Is there any way to get to know (in code of course) where does it inherit from? As an example: class CDate(models.Models): class Meta: abstract = True active = models.BooleanField() class SWT(CDate): name = models.CharField(max_length=32) class RealObj(SWT): code = models.CharField(max_length=32) . In this case of a RealObj i' d like to get to know that it inhertis from SWT. How can i do that? Thanks. -
Get virtualenv or python path in views
I'm running a Django project with an virtualenv, I want to get in views the path of running python or of the virtual environment that I'm using The goal is to pass this path to subprocess to execute a script Thank you -
Celery task not working by timer
I'm study the celery and want run a task each 10 second. I added task , and add in beat_schedule, but in the console I not see a text: 'Task will run'. What doing wrong? Ex. result: I want run automatically this task and restart each 10 second. If I think wrong, explain celery from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app', broker='amqp://rabbit:5672') app.config_from_object('django.conf:settings', namespace='CELERY') @app.task(bind=True) def run(self): print('Task will run') app.conf.beat_schedule = { 'ever-10-second': { 'task': 'task.run', 'schedule': 10.0, } } app.conf.timezone = 'UTC' app.autodiscover_tasks() -
Get user followed topics in Django?
I am developing application where user can follow topics to get updates. Below are models.py from django.contrib.auth.models import User class Topic(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=300) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='topic') def __str__(self): return self.name class Follow(models.Model): topic = models.ForeignKey(Topic, related_name='follow') user = models.ForeignKey(User, related_name='follow') views.py def home(req): user_id = req.user.id follow = Follow.objects.filter(user = req.user).all() follow = [f.topic for f in follow] question = Question.objects.filter(topic__in=follow).all() answer = Answer.objects.filter(ques__in=question).all() topic = Topic.objects.all().distinct(name) return render(req,'home.html',{'topic':topic,'answer':answer,'upvote':upvote}) Template: {% for t in topic %} {% for ft in t.follow.all%} {% if ft.user == user %} <h4 id="{{t.pk}}" class="topCls"><span class="badge badge-success">{{t.name}}</span></h4> {% endif %} {% endfor %} &nbsp; {% endfor %} I need to get user followed topics in green color and other topics in red color I can get user followed topics as above, How can i differentiate followed or not ? Thanks in advance !!! -
Can't get FIltered Queryset's object id to display directly the detail page on searching a Car model from dropdown
views.py forms.py I'm trying to use django's built-in filter to search cars according to their brand and car models, Dropdowns selection for brand is working And when only brand is selected that brands car is listed, but when trying to get car model from the form the queryset : 'car_select' the actual object is filtered but when i print car_select in terminal but can't fetch the id of the object for which detail page of the filtered object from car_select queryset. highlighted 'queryset [4]' in terminal screenshot -
gunicorn memory usage increases high on AWS while a simple rest service is used
We have hosted our Web App (Angular CLI: 1.7.3, Node: 9.5.0, Django 2.0.3) on AWS free tier of Ubuntu(14.04.5 LTS) VM. We are using ELB (Elastic Load Balancers) with Nginx-1.4.6 and gunicorn-19.7.1 When we try to use access our App from a browser then suddenly gunicorn memory usage increases quite high: Normal: PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 16248 ubuntu 20 0 313.1m 94.6m 9.3m R 15.6 9.5 0:00.71 gunicorn While using App: PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 16235 ubuntu 20 0 684.9m 315.8m 11.1m R 61.4 31.8 0:04.51 gunicorn Below is our gunicorn configuration (/etc/init/gunicorn.conf): description "Gunicorn application server handling myproject" start on runlevel [2345] stop on runlevel [!2345] respawn setuid ubuntu setgid www-data chdir /home/ubuntu/project/ #--max-requests INT : will restarted worker after those many requests which can #overcome any memory leaks in code exec ./env/bin/gunicorn --max-requests 1 --workers 3 --bind unix:/home/ubuntu/project/django-ng.sock config.wsgi:application We have already set max-requests as 1 and workers as 3. Could someone please tell what is going wrong? -
Django: redirect if url was written manually by user
Is it possible to restrict user from putting url of page by hand? Let's say I have two pages - somepage.com/home and someplace.com/other and somewhere in home page is button that redirects user to /other site. I want to make sure that user won't be able to access /other by writing its url by hand. Instead it should redirect back to home page. Is there maybe some decorator like login_required that I can use? Or maybe I should use some js function? Thanks in advance for any tips, cheers. -
Django Multi-lingual Charts with FusionCharts
I am trying to use Fusion Charts in my Django web application. But i have cyrillic labels in it. this is that i get image my view: def chart(request): dataSource = {} dataSource['chart'] = { "caption": "ііііінформатика", "paletteColors": "#0075c2", "bgColor": "#ffffff", "borderAlpha": "20", "canvasBorderAlpha": "0", "usePlotGradientColor": "0", "plotBorderAlpha": "10", "showXAxisLine": "1", "xAxisLineColor": "#999999", "showValues": "0", "divlineColor": "#999999", "divLineIsDashed": "1", "showAlternateHGridColor": "0" } dataSource['data'] = [] for key in Mark.objects.all(): data = {} data['label'] = key.id_student.name.encode('utf-8').decode('utf-8') data['value'] = key.mark dataSource['data'].append(data) # Create an object for the Column 2D chart using the FusionCharts class constructor column2D = FusionCharts("column2D", "ex1", "600", "400", "chart-1", "json", dataSource) # returning complete JavaScript and HTML code, which is used to generate chart in the browsers. request.encoding = 'UTF-8' return render(request, 'main/mark/test.html', {'output': column2D.render().encode('utf-8').decode('utf-8')}) my html: {% load static %} <!DOCTYPE html> <html lang="uk"> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>{% block title %}{% endblock %}</title> <script type="text/javascript" src="{% static "js/fusioncharts.js" %}"></script> <script type="text/javascript" src="{% static "js/themes/fusioncharts.theme.fint.js" %}"></script> </head> <body> <!-- Fusion Charts will render here--> <div id="chart-1"></div> <!-- dumping JavaScript code here --> {{ output|safe }} </body> </html> i found this solution, but it don`t help, or i did something wrong. Can someone help me, with example would … -
Unable to runserver with docker-compose up
I am using Docker while development. I noticed that I can't launch dev server with docker-compose up command, but can with docker-compose run Here is my Dockerfile: FROM python:3.6 WORKDIR /opt/lib RUN pip install --upgrade pip COPY requirements.txt ./ RUN pip install -r requirements.txt WORKDIR /opt/web Here is docker-compose.yaml version: '2' services: web: build: ./web/ working_dir: /opt/web ports: - "3000:3000" volumes: - ./web:/opt/web user: 1000:1000 depends_on: - database env_file: env command: python manage.py runserver 0.0.0.0:3000 database: image: mdillon/postgis:9.6 ports: - "5432:5432" volumes: - ./database/data:/var/lib/postgresql/data Now, if I run docker-compose up, only database starts up: But with docker-compose run server starts fine: If I change docker-compose.yml > services > web > command to /usr/local/bin/gunicorn project.wsgi:application -w 4 -b :3000 it also works fine, but I need autorestart when files change I use Docker for MacOS Version 18.03.1-ce-mac65 (24312) I tried to reset it to factory settings and this did not help. Can you help me with this? -
How to shutdown celery node
My celery log is showing this error: UserWarning: A node named celery@postr is already using this process mailbox! Maybe you forgot to shutdown the other node or did not do so properly? Or if you meant to start multiple nodes on the same host please make sure you give each node a unique node name! warnings.warn(W_PIDBOX_IN_USE.format(node=self)) How can I shutdown the other node? PS: Is there a way to see all the current running nodes? -
Setup Wordpress, Django and AngularJS application on AWS
I currently have the AWS free tier and need to host the following instances in the most effective/cheap way possible. There won't be a lot of traffic on the website, so I want to maximise the free tier: 1 - Wordpress (simple installation, need a blog setup - so this will require an SQL database) 2 - Django application (will also be setting up admin front end - also requires SQL database) 3 - two AngularJS applications (different entry points) Can someone please suggest the best way of doing this? Thanks -
Chatterbot returning 405
I am following the tutorial on the official page on how to integrate chatterbot with django but I keep getting the following error: 8000/api/chatterbot/ Failed to load resource: the server responded with a status of 405 (Method Not Allowed) I have added it to the installed apps: INSTALLED_APPS = ( # ... 'chatterbot.ext.django_chatterbot', ) and defined it as: CHATTERBOT = { 'name': 'ChatterBot Example', 'logic_adapters' : [ "chatterbot.logic.BestMatch" ], 'trainer': 'chatterbot.trainers.ChatterBotCorpusTrainer', 'training_data': [ 'chatterbot.corpus' ] } I have added the api endpoint in my urls file url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')), and then i ran succesfully: python manage.py migrate django_chatterbot python manage.py train but when I try to chat with the bot, it doesn't return any reply and just returns a 405. Any idea what I might missing here? -
Unable to format text in textarea html css?
I have this small problem. I have a textarea and a user can enter text in a specific format but when the text is saved in the database and retrieved back the spaces or the formatting that has been done by the user for entering the text is lost. How do i maintain the formatting that the user entered in the textarea. I am using django python. <label style="color: lightblue; font-size: 20px;">Query Diagnosis</label> <div id ="qdiagnosis" style=" width: 80%;word-wrap:break-word;font-family:Arial,Helvetica, sans-serif; font-size: 20px; font-weight: bold;"> </div> <div class="mdl-grid full-width"> <div class="mdl-textfield mdl-js-textfield mdl-cell mdl-cell--12-col"> <textarea onkeyup="$('#query_diagnosis').val($('#query_diagnosis_').val())" class="mdl-textfield__input bordered" type="text" rows="8" id="query_diagnosis_" name="query_diagnosis_"></textarea> <label class="mdl-textfield__label" for="notes_">Query Diagnosis</label> </div> </div> Before saving image - https://ufile.io/dzjxz After saving image - https://ufile.io/fs2a9 -
django formset as columns
Im using below html for the django formsets. The javascript is working fine, but I want to display the form in column format. Tried various snippets but was not able to use the javascript on them below is the HTML code div class='col-sm-6 col-sm-offset-3'> <h1> Enter scheme of entries</h1> <form action='' method='POST'> {% csrf_token %} <div class='btn-group'> <input class='btn btn-primary' type='submit' value='Save' /> <a class='btn btn-default' href='/'>Cancel</a> <a class='btn btn-link add-new-form' href='#'>+ Add new Entry</a> </div> <br/> <div class='form-row' id='empty-row'> {{ formset.empty_form.as_p }} </div> <div class='btn-group'> <input class='btn btn-primary' type='submit' value='Save' /> <a class='btn btn-default' href='/'>Cancel</a> <a class='btn btn-link add-new-form' href='#'>+ Add new form</a> </div> </form> The above html would display form in row format +Field-1 --------- +Field-2 -- and so on How can i show the same fields in column format Field-1 Field-2 --- --- Save/Add Form JavaScript for the same is {% block jquery %} function updateEmptyFormIDs(element, totalForms){ var thisInput = element // get current form input name var currentName = element.attr('name') // replace "prefix" with actual number var newName = currentName.replace(/__prefix__/g, totalForms) // console.log(newName) // update input with new name thisInput.attr('name', newName) thisInput.attr('id', "id_" + newName) // create a new form row id var newFormRow = element.closest(".form-row"); … -
Django include jquery script
I have two Django templates, one for the detail-update view and one for the create view. I use a simple jquery script to show/hide html fields depending on the selected component_type by the user. However this jquery script is identical for the create and detail-update templates (violates DRY-principle). So I would like to save it in a seperate file, e.g. jquery.html and then include it, e.g. {% include 'jquery.html' %}. How to do this? The create template is as follows: {% extends 'base.html' %} <script> {% block jquery %} $(document).ready(function(){ hideShow() }) $('#id_component_type').click(function(){ hideShow() }); function hideShow(){ if(document.getElementById('id_component_type').options[document.getElementById('id_component_type').selectedIndex].value == "k_v") { $('#id_length').parents('p:first').hide(); $('#id_k_v').parents('p:first').show(); }else { $('#id_length').parents('p:first').show(); $('#id_k_v').parents('p:first').hide(); } } {% endblock %} </script> {% block content %} <h2>Create new component</h2> {% include 'snippets/form-snippet.html' with form=form %} {% endblock %} -
Support for url suffix in django
I use django-tenant-schemas and I need to change the way it selects the current tenant: from https:// tenant1.mydomain.com/ to https:// mydomain.com/tenant1/ The middleware is quite simple and it's working, the tenant is selected. The problem comes in the url resolution in django. It raises a 404 cause there is no url mapping that includes that suffix "tenant1". How could I tell django that the urls now have a dinamic suffix that changes deppending on the tenant? This should be used reversing and generating urls. -
Django templates: optional variable in a with
This might be a pretty simple question; but I can't seem to find the 'correct' approach. I have a template, in which I include a different template three times. I pass quite a few variables along with the include. The problem is that one of them is optional. {% with title="Add object" type="function" function_type="FUNCTION" inputs=function_create_form project_id=project.id parent_function_id=root_function.id {% if root_function.type == 'OBJECT' %} parent_function_id=root_function.id {% endif %} %} {% include "./popup-form.html" %} {% endwith %} (I'm aware that this should be on one line in the template, for some reason. But this is way more readable.) The gist of it is that I only want to pass the variable in the if statement, if it is of the correct type. It will always have a value, but not always the correct one. Sadly though, Django doesn't seem to tolerate if statements in with's. I also tried to do this, same result: {% include "./popup-form.html" with title="Add object" type="function" function_type="OBJECT" inputs=function_create_form project_id=project.id {% if root_function.type == 'OBJECT' %} parent_function_id=root_function.id {% endif %} %} Error: 'with' received an invalid token: '{%' I could perhaps make an if statement outside of the with and set the value of the variable to an empty …