Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How sending Context using reverse and http redirect [Django 2.0] [duplicate]
This question already has an answer here: HttpResponseRedirect reverse - passing context variable 1 answer I want to pass a variable using HttpResponseRedirect and reverse Django not as a parameter or argument but as a variable displayed later into my HTML template. To be more clear, I used this snippet without any result. error_msg = 'Wrong credentials' return HttpResponseRedirect(reverse('myapp:user_login', {'error_msg':error_msg})) {% if error_msg %} <p>{{ error_msg }}</p> {% endif %} I read these answers pass argument and passing context variable but they didn't help me a lot. -
How save Foreign relations from a Form Django
... I'm trying to save the data saved with 2 forms in 2 different models, but i don't know how save the relations. And after save the data, I need to show them as a one html form, well when the user typed the info is one html form too. with this view, I saved the info in both models, but I can't save the relation. May be the POST has a different to work in this problem .... I don't know view.py def proposeActivity(request): if request.method == "POST": form_1 = ActivityProposedForm(request.POST, prefix="form_1") form_2 = ActivityUrl_activity(request.POST, prefix="form_2") if form_1.is_valid() and form_2.is_valid(): post_1 = form_1.save(commit=False) post_2 = form_2.save(commit=False) post_1.author = request.user post_2.author = request.user post_1.save() post_2.save() return redirect('proposedActivities') else: form_1 = ActivityProposedForm(prefix="form_1") form_2 = ActivityUrl_activity(prefix="form_2") return render(request, 'registerActivity.html', {'form_1': form_1, 'form_2': form_2}) forms.py class ActivityProposedForm(forms.ModelForm): class Meta: metodologias_choices = [(metodologia.id, metodologia.methodology_name) for metodologia in Methodology.objects.all()] normas_choices = [(normas.id, normas.norm_name) for normas in Norm.objects.all()] # competencias_choices = # CHOICES = {('1', 'Activa'), ('2', 'Tradicional')} model = ActivityProposed fields = [ 'nombre_actividad', 'detalle_de_la_actividad', 'metodologia', 'nombre_de_la_norma', 'nombre_de_la_competencia', 'nombre_del_curso'] labels = { 'nombre_actividad': 'Nombre de la Actividad', 'detalle_de_la_actividad': 'Detalla de la Actividad', 'metodologia': 'Metodologia', 'nombre_de_la_norma': 'Nombre de la Norma', 'nombre_de_la_competencia': 'Nombre de la Competencia', 'nombre_del_curso': … -
Django Unkown Fields()
I've seen a lot of issues similar to mine, but none had exactly the same problem. I have my code running on another machine and it's working perfectly, it's exactly the same code since I'm using github for version control, but when I run on my machine I started to get this error, I use postgres, I already tried give drop in the database and create another but continue with this error. The error started after I imported the database from the machine that is running fine. When I tried to go back to the local database, I started to have an error, I already tried to reinstall all the packages (those installed via pip) and nothing. I'm using Django 1.10 Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace instance at 0x7f7aa3e35ef0> Traceback (most recent call last): File "/home/marco/documentos/pycharm/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 589, in __call__ return self.original_func(*self.args, **self.kwargs) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern … -
how to decode utf8 in bottle framework
I am a beginner to bottle framework. I am doing my project on the mentioned framework but on MVC structure meaning I have controller, model and view page. my project is admin panel. in part of modifying user information, after inputting new user information when i submit the new information i receive the new one in unreadable language. how I can make bottle read UTF8? -
Check values exists in another table
Sorry about my doubt, i'm a student. I have this scenario class Equipment(): id name ... class Alert(): id ... pin value equipment_id The tables (Equipment - Alert) have no relationship: I need to check if the id of the Equipment table exists in the Alerts table If there is need to return A, if there is no return B, and return th to template -
NoReverseMatch 1 pattern(s) tried: ['(?P<id>\\d+)/(?P<slug>[-\\w]+)/$']
I'm new in Django, using version 2.0. Started building a 'shop' application according to the 'Django by Example' book. But the book uses django version 1.8. The problem is, when I browse http://127.0.0.1:8000/ this error appears: "NoReverseMatch at/ Reverse for 'product_detail' with arguments '(None, 'alpina')' not found. 1 pattern(s) tried: ['(?P\d+)/(?P[-\w]+)/$']". 'alpina' is the product's name which I added from admin site. Here is urls.py of my app: from django.conf.urls import url from . import views app_name='shop' urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail'), ] Here is the models.py of my app: from django.urls import reverse from django.db import models class Category(models.Model): name = models.CharField( max_length=200, db_index=True ) slug = models.SlugField( max_length=200, db_index=True, unique=True ) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse( 'shop:product_list_by_category', args=[self.slug] ) class Product(models.Model): category = models.ForeignKey( Category, related_name='products', on_delete=models.CASCADE ) name = models.CharField( max_length=200, db_index=True ) slug = models.SlugField( max_length=200, db_index=True ) image = models.ImageField( upload_to='products/%Y/%m/%d', blank=True ) description = models.TextField( blank=True ) price = models.DecimalField( max_digits=10, decimal_places=2 ) stock = models.PositiveIntegerField() available = models.BooleanField( default=True ) created = models.DateTimeField( auto_now_add=True ) updated = models.DateTimeField( auto_now=True ) class Meta: … -
Django in listening mode on an url
I developed a web app with django: I call a soap service (using suds) and the service requires in input several parameters including a callback url and a push url. On the push url the queried service sends notifications of state change. I would need to put my app in listening mode to the push address to be able to intercept any calls made from soap service to my app on this url to communicate status changes. How can made this? -
Python Django celery periodic task in windows
I am creating a simple Django Celery app that implements periodictasks to execute a function periodically. All I have in this Django project is one app called 'app' The folder structure is sp │ db.sqlite3 │ manage.py │ ├───app │ admin.py │ apps.py │ models.py │ tasks.py │ tests.py │ views.py │ __init__.py │ └───sp celery.py settings.py urls.py wsgi.py __init__.py The celery.py contains from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sp.settings') app = Celery('sp') app.config_from_object('django.conf:settings') app.conf.timezone = 'Asia/Calcutta' app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py contains from celery.decorators import task from celery.decorators import periodic_task from sp.celery import app @app.periodic_task(run_every=(crontab(minute='*/1'))) def task_number_one(): return "1" Celery broker in settings.py is CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672/' In windows I start celery beat and celery worker seperately as celery -A sp beat -l info celery -A sp worker --pool=solo -l info Celery tasks run fine but periodic tasks that runs with celery beat are not executing. When i run them no error are shown in the command prompt Can anyone say what the problem is? Is that because of Windows operating system? or any source code error? -
Django Admin custom list_filter is not called
I've written a custom list filter for my ModelAdmin, using the tutorial at https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter. It works fine when taken out of the project into a test environment and fed directly with the filter value. In the actual project however, it shows the filter options but does not change the results when a filter is selected. What is strange is, the parameter is set to "balance" and the list of lookups defines "positive", "negative", and "settled"; but the respective URL querystring will only ever show ?e=1. Even if I input the querystring directly (e.g. ?balance=positive), I'm redirected to ?e=1 and see all objects. Here's the code: class AccountBalanceFilter(admin.SimpleListFilter): title = "Kontostand" parameter_name = "balance" def lookups(self, request, model_admin): return (("positive", "Positiv"), ("negative", "Negativ"), ("settled", "Ausgeglichen"),) def queryset(self, request, queryset): filter = self.value() if filter is None: return queryset elif filter == "positive": filtered_set = {account for account in queryset if account.get_current_balance() > 0} elif filter == "negative": filtered_set = {account for account in queryset if account.get_current_balance() < 0} elif filter == "settled": filtered_set = {account for account in queryset if account.get_current_balance() == 0} else: raise ValueError(f"The account balance filter only accepts filter values of 'positive', 'negative', or 'settled', but was given … -
Django and Angularjs - Incorrect json property name is send with post to api
I need some guidance here, still new to django and Angularjs. I have the django rest framework setup to display my departments with the below json returned. primary_locations is a foreignkey to my locations model. [ { "id": 52, "department_name": "Technical", "department_description": "Technical", "primary_locations": { "id": 1, "location_name": "ZA", "address": "ZA", "city": "ZA", "province": "ZA", "postal_code": "ZA", "country": "AG" } } ] In Angular I have a dropdown list that displays the available locations to select from. When I post the selected option I receive an error saying the following. Possibly unhandled rejection: {"data":"IntegrityError at /department\n(1048, \"Column 'primary_locations_id' cannot be null But when I scroll further down the page it shows the below was posted to the api {"department_name":"as","department_description":"as","locations":"4"}, Why is Angularjs sending the primary_locations_id name as locations and not primary_locations_id? Here is my controller system.controller('DepartmentCtrl', ['$scope', 'DepartmentsFactory', 'DepartmentFactory', 'LocationFactory', '$location', function ($scope, DepartmentsFactory, DepartmentFactory, LocationFactory, $location) { // Function to reload content on success $scope.reloadDepartments = function () { DepartmentsFactory.query( function( data ) { $scope.departments = data; }); }; // callback for ng-click 'editDepartment': $scope.editDepartment = function (id) { $location.path('/department/' + id); }; // callback for ng-click 'deleteDepartment': $scope.deleteDepartment = function (id) { DepartmentFactory.delete({ id: id }, function() { … -
Unknown command 'worker' in Celery 4.1.0
I'm not able to start celery worker in django application from the console. When I'm running celery worker --app=app1 -l info then Unknown command: 'worker' and if I'm running celery -A app1 worker -l info then Unknown command: '-A'. My celery config is following CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_BEAT_SCHEDULE = { 'supplier-update': { 'task': 'app1.tasks.task1', 'schedule': 60, } } -
How to determine wagtail Page content type within django template?
The core problem is that handling of wagtail RichTextField and StreamField is radically different in the templates. I'm trying to accomplish something similar to the following: {% with post=post.specific %} {% if post.content_type == 'streamfield' %} {% include_block post.body %} {% else %} {{ post.body|richtext }} {% endif %} {% endwith %} -
Python Django Subcategory
I want to print the subcategory names of each Main Category. The below code is now showing all subcategories for every Main category. How can I do? index.html {% for mainCatList in main_cat_list %} <li class="subMenu"><a>{{ mainCatList.main_category_name }}</a> <ul> {% for subCat in cat_list %} <li><a href="products.html"><i class="icon-chevron-right"></i>{{ subCat.category_name }}</a></li> {% endfor %} </ul> </li> {% endfor %} views.html from django.shortcuts import render from .models import Product, Category, Main_Category def homePageView(request): main_cat_list = Main_Category.objects.all() cat_list = Category.objects.all() context = {'main_cat_list': main_cat_list, 'cat_list': cat_list} return render(request, 'index.html', context) -
Table loop printing backwords & in reverse [Django Template]
<table> <tr> {% for i in "5555" %} <th> {{ forloop.revcounter }} </th> {% endfor %} </tr> <tr> {% for i in "11" %} <th> {{ forloop.revcounter }} </th> {% endfor %} </tr> <tr> {% for i in "1444" %} <th> {{ forloop.revcounter }} </th> {% endfor %} </tr> </table> {% endblock % output: I had to use forloop.revcounter so the numbers appeared in order Anyway what I'm trying to do is dynamically generate a stem-and-leaf-plot sort of graph, but encountered this weird issue I am not sure how to solve. -
In django , how to produce an another form from the obtained result?
I had scraped the data from the web , it produces a list of links . Now i wanted to seggregate the list into wanted or unwanted , by making status choices . But i am in a chaos , how to do it . I got results from web now wanted to create a form with links and the status choices and need to update them in db . -
Django and SQL. Join and group by
Sorry if you dislike my question's title. I just did not know how to name it. In short i have model. class Country(models.Model): title = models.CharField(max_length=255) class Visitor(models.Model): name = models.CharField(max_length=255) country = models.ForeignKey(Country) For example there 300 Visitors From USA 120 from France 25 From Spain. I need to get name of country and max amount how many visitors from this country? I am not good on sql and asking this question Is there way how to realize it? Thanks :) -
Additional field gets lost after validation in model serializer. Django Rest Framework
I want to be able to get list of filenames in ReporterViewset's perform_create method. However I can't do this because I can't reach files from ReportSerializer's validated_data. I want to get file names as additional and validated data from Report serializer. Here is my report serializer class ReportSerializer(serializers.ModelSerializer): files = serializers.ListField(read_only=True, child=serializers.CharField()) class Meta: model = api_models.Report fields = ("id", "reporter", "timestamp", "files", "description") And this is ReportViewset class ReportViewset(viewsets.ModelViewSet): queryset = api_models.Report.objects.all() serializer_class = api_serializers.ReportSerializer def perform_create(self, serializer): file_names = serializer.validated_data.get('files', []) instance = serializer.save() -
django+uwsgi+nginx Excessive use of memory
when I use the component of django+uwsgi+nginx, I found memory has been excessive using , have anyone have some experience or give some tips first I use reload-on-as,reload-on-rss,reload-on-rss,to handle the error So there is the logs of my running uwsgi logs of my uwsgi It's the profiles of nginx,uwsgi user nobody; worker_processes 4; worker_rlimit_nofile 65535; error_log /data/nginx/logs/error.log notice; events { use epoll; worker_connections 4096; } http { include mime.types; default_type application/octet-stream; full_log_format full '$remote_addr $request_length $body_bytes_sent $request_time[s] - - [$time_local] ' '"$request" $status $http_referer "-" "$http_user_agent" $server_name $server_addr ' '$http_x_forwarded_for $http_x_real_ip'; full_access_log /data/nginx/logs/allweb.log full; log_format combinedio '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" $request_length $request_time $upstream_response_time'; access_log off; sendfile on; gzip on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 0; client_body_timeout 10; client_header_timeout 10; client_header_buffer_size 1k; large_client_header_buffers 4 4k; output_buffers 1 32k; client_max_body_size 64m; client_body_buffer_size 256k; server { listen 80; server_name 0.0.0.0; location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8080; } location /static/{ alias xxx/server/www/static/; } } include include/*.conf; } uwsgi.ini [uwsgi] socket = 0.0.0.0:8080 master = true vhost = true no-stie = true worker-reload-mercy = 10 harakiri = 60 harakiri-verbose = true vacuum = true max-requests = 5000 reload-on-as = 512 reload-on-rss = 256 limit-as = 2048 buffer-size … -
DJANGO + REACT + WEBPACK-DEV-SERVER
I've big problem with a project I inherit without documentation. The project is build with Django and React. This is the project structure (without not important stuffs): myapp/ ├── assets │ ├── bundles │ │ ├── bar.js │ │ ├── bar.js.map │ │ ├── login.js │ │ ├── login.js.map │ │ ├── main.js │ │ ├── main.js.map │ │ ├── messages │ │ │ └── assets │ │ │ └── js │ │ │ ├── appbar.json │ │ │ [...] │ ├── css │ │ ├── bootstrap.min.css │ │ ├── [...] │ ├── js │ │ ├── appbar.js <<<--- REACT COMPONENT!!! │ │ ├── [...] <<<--- OTHER REACTS COMPONENTS!! ├── conf │ ├── default_settings.py │ ├── default_settings.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ └── wsgi.py ├── core │ ├── admin.py │ ├── admin.pyc │ ├── apps.py │ ├── color_palette.py │ ├── color_palette.pyc │ ├── constants.py │ ├── constants.pyc │ ├── decorators.py │ ├── decorators.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── models.py │ ├── models.pyc │ ├── tests.py │ ├── urls.py │ ├── urls.pyc │ ├── utils.py │ ├── utils.pyc │ ├── views.py │ └── views.pyc … -
Hide button after 1 week
I have a button that I want to hide after a week. But I can't figure out how. from datetime import datetime,timedelta now = datetime.now() weekago = now - timedelta(weeks=1) if (now - weekago > 7) { button.hide } I hope someone can help me with this, maybe with another methode. timesince ? -
I want to crate a Django field in my model to display a word after each new entry
So I want to create a field in my Django models.py, so that the user can select a number of years as integer (e.g. 3) and then after each new entry the words 'years' to be automatically displayed. I do not want to do this with CharField. class StudyProgramme(models.Model): period = models.IntegerField(2) -
join two tables in django ORM using foreign key
I am a beginner in Django. I am facing a problem the details are given below. Kindly take a look and provide me a way out. I have two models "Internalorder2" an "Position3" info mentioned below. I want to join the tables with using Django ORM mentioned below app/models.py class Internalorder2(models.Model): order_id = models.AutoField(primary_key=True) ticker = models.CharField(max_length=64) class Meta: managed = True db_table = 'internalorder2' app/models.py class Position3(models.Model): pos_id = models.AutoField(primary_key=True) parent_order = models.OneToOneField(Internalorder2, models.DO_NOTHING) action = models.CharField(max_length=4) class Meta: managed = True db_table = 'position3' python manage.py shell command from app.models.py import * new = Internalorder2.objects.all().select_related() new = Position3.objects.all().select_related("parent_order") python shell result In [102]: new[0].__dict__ Out[102]: {'_parent_order_cache': <Internalorder2: Internalorder2 object>, '_state': <django.db.models.base.ModelState at 0x13209f0>, 'action': 'B', 'parent_order_id': 1, 'pos_id': 1} But we don't get "Ticker" field please help me where am I doing wrong -
build python list from ansible list of values
I'm trying to 12-factor my django settings by passing environment variables from ansible. I'm trying to get: MYSETTING = ['host1', 'host2] I have tried various options in ansible: # settings.py MYSETTING = os.environ.get(ANSIBLE_VALUE, []) # ansible vars file ANSIBLE_VALUE: "['host1', 'host2']" or # settings.py MYSETTING = [os.environ.get(ANSIBLE_VALUE, None)] # ansible vars file ANSIBLE_VALUE: "'host1', 'host2'" but neither option seems to work. I'm sure there is something simple, but I can't figure it out. -
Adding Multiple Data in Embedded Document as a list with python?
I'm Using Mongoengine with Django, Basically, i want to add lots of additional fields, the number of fields is not predefined. models.py class ProductAdditionalDetails(EmbeddedDocument): detail_name = StringField(required=True) detail_value = StringField(required=True) class Product(Document): __tablename__ = 'product' product_code = StringField(required=True) product_title = StringField(required=True) additional_details = ListField(EmbeddedDocumentField(ProductAdditionalDetails)) views.py class ProductCreateView(APIView): def post(self, request): serializer = AddProductSerializer(data=request.data) if serializer.is_valid(): additional_details = [] for details in additional_details: j = ProductAdditionalDetails( detail_name = serializer.data["detailName"], detail_value = serializer.data["detailValue"] ) additional_details.append(j) new_product = Product( product_code = serializer.data["productCode"], product_title = serializer.data["productTitle"], additional_details = additional_details, ) new_product.save() The Code Below Works! I can pass it as an object in the API but why not in the serializers? fields1 = ProductFields(key_name="size", value="M") fields2 = ProductFields(key_name="size", value="L") fields3 = ProductFields(key_name="size", value="XL") new_product = Product( name=serializer.data["name"], description=serializer.data["description"], fields=[fields1,fields2,fields3] ) new_product.save() -
Why is my variable not defined inside a list comprehension?
I'm retrieving a 5 random filtered queryset on django, as mentioned in the title, my variables are not defined inside my comprehension list. NameError : 'address' is not define (same for 'website') To do as the description and avoid performance issues, I'm using this method: website = True address = True object_data = SomeModal.objects.filter(address=address, website=website) number_of_records = object_data.count() - 1 #count filtered records random_sample = random.sample(range(number_of_records), 5) #get 5 random samples (ex: ['2', '0', '3', '6', '7']) The error occurs at this stage: #get those 5 random samples. layouts = [SomeModal.objects.filter(address=address, website=website)[random_int] for random_int in random_sample] What could be the reason of this problem?