Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Sum float values
I have model in Django which have three fields. Float, and two CharFields. I need to sum the float fields by the other two. models.py class Hours(model.Model): hours_worked = models.FloatField() order_number = models.CharField() oper = models.CharField() What I need to do is go through all data in DB and sum hours_worked for the same order_number+oper. So let say I have in db 4 records: |hours_worked|order_number|oper| |------------|------------|----| | 4| 252| 10| | 8| 320| 20| | 8| 252| 10| | 6| 252| 20| And I need to return queryset of three objects like this: |hours_worked|order_number|oper| |------------|------------|----| | 12| 252| 10| | 8| 320| 20| | 6| 252| 20| Is there any easy way how to do it? -
Staticfiles are not working on real Django server
I am using VPS SSH server and in localhost everything works perfect while on server staticfiles are not working (css, js, images). I did the migrations and collectstatic. -
How to add custom field to django rest auth model without modifying the django auth model?
I am trying to add a phone field for Django rest user registration. I am using Django auth model. I don't want to add a custom field to Django user model. Without modifying the user model I need to add a phone field to RegisterUserSerializer -
send model form as a json response in django
I want to send a modelform to my template using through json response(I've no idea if it's possible or not). Actually in my template I have a list of objects from a model, and when i click them i send a post request to my view through ajax or axios with the object id, then in view I'm creating the model form of that object and I want to send that the model form of instance object back to template. to summarize it up how can i send an model form through json response.(If not possible how to ) -
How to check if query has select_related but no other field filtering, django queries?
Django Model Admin has default Paginator that has a count method that perform a count(*) to get number of records for a given query, which add overhead when table size grows. One of the methods to solve this uses the following override of count: from django.core.paginator import Paginator class CustomAdminPaginator(Paginator): ... @cached_property def count(self): query = self.object_list.query is_filtered = query.where if is_filtered: return super().count try: cursor = connection.cursor() cursor.execute("SELECT reltuples FROM pg_class WHERE relname = %s", [query.model._meta.db_table]) return int(cursor.fetchone()[0]) except: return super().count Basically this solution uses an estimated record count stored in one of postgres meta tables. One of the problem of this method, is that even if the query has only select_related on non-nullable field (then the number of records is equal to the number of records if the query does not have select_related) then it will call the super count i.e. it will not use the pg_class utility. The question is how to know if query only has select_related or prefetch_related but no other filed filters such as, create_date__lte..etc? -
Django: better (simpler) migration system alternative?
Is there an alternative to built-in Django migration system, which doesn't try to be intelligent? Ideally, I would like the following: Simple DSL for typical operations (add/change/remove column, add/change/remove table, add/change/remove index, etc., including raw SQL as the last resort) Auto-revert for these operations (unless raw SQL is used) Single folder with all migrations for the whole project (so when I refactor some 'app', e.g. split it into two apps, that doesn't require to change migrations). No boilerplate for specifying migration dependencies: each migration is assumed to depend on every preceding one. No 'state' management. Just run the DSL statements. -
Meaningful error message if Redirect after Post fails (Testing Django)
After successful POST a redirect should happen (PRG Pattern) response = admin_client.post(url, data) assert response.status_code == 302 If this test fails, I get a very meaningless error message. AssertionError assert 200 == 302 Is there a django-way to get the error message of the form into the exception? -
How to change the format of REST API Filter?
I'm filtering the date of REST API url by calling a string. /api/data/?date_range=Today for Today but converting it into a date /api/data/?date_range=2021-01-28 won't work. How to change this? Thanks! class DataFilter(filters.FilterSet): start_date = DateFilter(field_name='timestamp', lookup_expr='gt') end_date = DateFilter(field_name='timestamp', lookup_expr='lt') date_range = DateRangeFilter(field_name='timestamp') class Meta: model = Data fields = [] class DataView(generics.ListCreateAPIView): serializer_class = RainfallSerializer queryset = Data.objects.all() filterset_class = DataFilter def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = DataSerializer(queryset, many=True) return Response(serializer.data) -
Build SPA for WeatherMap (Similar to CACTI)
I'm currently at initial conceptual phrase for SPA development. I'm a network engineer and also a beginner in Python programming with some concepts around web development. I'm planning to build a SPA to visualise traffic volume like a weathermap between different continents. I would like to have some inputs from everyone of you about the options/toolkits that I've in my mind or any extra stuffs that can facilitate this purpose much easier as a newbie Front end weather heat map: Python Flask / Django web framework, JavaScript/CSS, not sure what plug-in to use to build the coordinates between different countries and connect the dotted point between them Backend: Any suggestion of JSON based database (thinking of TSDB like influxDB) but hopefully to have something easier to integrate with python Last but not least, if there's any good reference, either web page or books that I can read through, that would be really helpful. Hope to hear any good suggestions here. Best Regards RJ. -
How to change make changes to my 'Order' in Django after receiving payment by Stripe Checkout Session?
I am making an e-commerce website by Django and want to use Stripe Checkout Session for receiving online payments. I followed https://stripe.com/docs/api/checkout/sessions for creating checkout sessions and https://stripe.com/docs/webhooks/build for creating the webhooks. I could receive payments smoothly, but I want to change the 'order' to 'complete = True' right after payments are received. However, the request of view 'stripe_webhook' does not have attribute of user, so I can't call 'request.user' to get the corresponding 'order'. How could I solve this issue? Thanks so much. models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null = True, blank = True) date_completed = models.DateTimeField(null = True, blank = True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return f'{self.user.username} {self.date_created}' views.py @login_required def stripe_payment(request): return render(request, 'stripe_payment.html', {}) @csrf_exempt def stripe_config(request): if request.method == 'GET': stripe_config = {'publicKey': settings.STRIPE_PUBLISHABLE_KEY} return JsonResponse(stripe_config, safe=False) @csrf_exempt def stripe_create_checkout_session(request): if request.method == 'GET': domain_url = 'http://localhost:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY order = Order.objects.get(user = request.user, complete = False) total = int(order.get_cart_items_total) * 100 try: checkout_session = stripe.checkout.Session.create( success_url = domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url = domain_url + 'cancelled/', payment_method_types = ['card'], mode = 'payment', line_items = [ { 'name': ' ', 'quantity': 1, 'currency': 'usd', 'amount': … -
How can i use Django inlineformset to render multiple form rows which i can add and delete as per my choice?
Here is the code. Multiple rows gets rendered when extra=3 but when i delete a row and add a row, the data doesnt get saved or when i save data only on one row after removing other two, error occurs. ANy help would be appreciated. [this is the deployed link][https://inventoryme.herokuapp.com] admin admin is username and password views.py class SalesCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Sales template_name = "sales/sales_form.html" fields = '__all__' success_message = "New sales successfully added." def get_context_data(self, **kwargs): data = super(SalesCreateView, self).get_context_data(**kwargs) if self.request.POST: data['items'] = SaleItemFormset(self.request.POST) else: data['items'] = SaleItemFormset() return data def form_valid(self, form): context = self.get_context_data() items = context['items'] with transaction.atomic(): if items.is_valid(): items.instance = form.save(commit=False) for i in items: prod = i.cleaned_data['product'] product=prod.product print(prod) qt=i.cleaned_data['quantity'] print(qt) sold_item=Product.objects.get(product=product) if sold_item.Quantity < qt: form.errors['value']='Your entered quantity exceeds inventory quantity' return self.form_invalid(form) else: sold_item.Quantity -=qt sold_item.save() form.save() items.save() # sold_item.save() return super(SalesCreateView, self).form_valid(form) def get_initial(self): initial=super(SalesCreateView,self).get_initial() initial['customer']=Customer.objects.get(pk=self.kwargs['pk']) return initial This is the views that renders the inlineformset. forms.py class CustomerForm(ModelForm): class Meta: model=Customer fields='__all__' class SaleForm(ModelForm): class Meta: model = Sales fields = '__all__' class SaleItemForm(ModelForm): class Meta: model=SalesItem fields=['product','quantity'] ``` <strike> {% extends 'base.html' %} {% load static %} {% load widget_tweaks %} {% block title %} … -
django.db.utils.DataError: value too long for type character varying(1)
I'm trying to deploy my Django application to Heroku and I need to migrate a database to create tables, but it's giving me an error, I understand that it's an error with fields and max_length, but I don't have any fields with (1) max length: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.StringDataRightTruncation: value too long for type character varying(1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 245, in handle fake_initial=fake_initial, File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 106, in database_forwards field, File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 487, in add_field self.execute(sql, … -
If else condition error in django template
I write a simple django condition but it not working {% if request.user == "sami" %} sami {% else %} khan {% endif %} -
Change to UUID as pk triggers form "non-editable field" error
I am experimenting with moving our project over to UUID field primary keys. I've created a branch, deleted all the migrations and the database, and am trying to makemigrations when I hit new errors. Per the docs, I made id an explicit field in our site Abstract Base Class of Model: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) I was surprised that this results in a new error for ModelForms where 'id' is included in the fields property. The error says: ```django.core.exceptions.FieldError: 'id' cannot be specified for Statement model form as it is a non-editable field``` I removed 'id' from one Form, but for others it seems pretty essential to the function of the form / formsets that the primary key be returned with POST data. The Django implicit 'id' integer autofield is not editable, yet we did not get this error before, and we still don't where fields = '__all__' is set. -
Django Testing: Is it possible to test importing local_settings.py?
Like many of you, I hide some of my settings behind a local_settings.py file like so: settings.py try: from .local_settings import * except ImportError: pass However, when running Coverage.py on my project these four lines are not captured. I know this is just OCD on my part, but I want my project at 100% coverage. Is there a good way to test the importing of other files? Is this beyond the scope of the Django framework? -
how to implement search that can access complete database in Django
My views.py class SearchView(TemplateView): template_name = 'search.html' def get(self, request, *args, **kwargs): q = request.GET.get('q', '') self.results = Item.objects.filter(title__icontains=q) return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): return super().get_context_data(results=self.results, **kwargs) My urls.py url(r'^search/$', SearchView.as_view(), name='search') My search.html {% extends 'base.html' %} {% load static %} {% block content %} <body> <h1>Search Result</h1> <ul> {% for item in products %} <li> {{ q.title }}, {{ q.price }} </li> {% endfor %} </ul> </body> {% endblock%}} My nav.html <form method="GET" action="{% url 'core:search' %}"> This is the code that i used but due to some missing or error in this above code i can't get any data if i make any search in my website, Can some one please tell me what is the mistake i have done. Thank you. -
Static and media files are not working on django real server
In the result (real server) the css, js and images are not connected, but the thing is that in localhost it works perfect. I dont know what any other details do you need so write comment and I will edit this queston :) from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_ROOT = os.path.dirname(__file__) STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [STATIC_DIR] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CRISPY_TEMPLATE_PACK = 'uni_form' LOGIN_URL = '' -
Django migrations or Python or VSCode problem
i want to migrate model but terminal in VSCode just prints out 'Python' i use VSCode and terminal is powershell there is a picture enter image description here what should i do to solve this problem? -
Django concat variable in template
i have this template on my Django {% for car in cars%} <div class="form-row"> <label for="detail-{{ detail.id }}"> <b>{{ detail.rejected_field.title }}</b> : <img id="car-image" src="{{ car_manager_image_ + car.id }}"> </label> </div> {%endfor%} car_manager_image is another image url sent via extra_context['car_manager_image_'+car.id] on the backend my question is, how do i concate the data on Django Template? -
Django bulk_create with ignore_conflicts=True giving ProgrammingError
I am getting this strange error ProgrammingError at /save_hsn/ syntax error at or near "ON" LINE 1: ...021-01-28T06:17:43.784614+00:00'::timestamptz, 1) ON CONFLIC... this is my views.py part where I am getting the error user_gst_codes.objects.bulk_create(hsn_list, ignore_conflicts=True) If I remove ignore_conflicts=True, everything works. Moreover, I start getting this error after deploying my Django app on cPanel, on localhost this doesn't give any error. On localhost- Python 3.6.6, Django 3.1 On cPanel- Python 3.6.11, Django 3.1 Is this an issue with the Python version? I am inserting data in bulk and also need to keep the unique check. Any help would be appreciated. -
Node JS model/database record differential history
tldr : Dears , I come from a Python/Django background where i use a pacakge called Django Simple History and I'm looking for an equvialnt for it in NodeJS world . long version : In django I used this package to have record versioning in my tables where for example we have a course content filed : in v1 it has 3 topics but in v2 it has 7 topics I want to maintain both versions under the same course because different programs are using different versions of the course . -
Getting authentication error in quickbook web connector
Hii was integrating django with quickbooks using django-quickbooks module and after creating qwc file when i run the update selected button in quickbook web connector i get this error When i go to my terminal where i ran my webapp this is the error: Traceback (most recent call last): File "C:\Users\83ideas-design\anaconda3\lib\site-packages\spyne\application.py", line 163, in process_request ctx.out_object = self.call_wrapper(ctx) File "C:\Users\83ideas-design\anaconda3\lib\site-packages\spyne\application.py", line 232, in call_wrapper return ctx.descriptor.service_class.call_wrapper(ctx) File "C:\Users\83ideas-design\anaconda3\lib\site-packages\spyne\service.py", line 194, in call_wrapper return ctx.function(*args) File "C:\Users\83ideas-design\Downloads\DJANGO_COURSE_2.xx\djquic\django_quickbooks\views\service.py", line 30, in authenticate if session_manager.new_requests_count(realm) > 0: File "C:\Users\83ideas-design\Downloads\DJANGO_COURSE_2.xx\djquic\django_quickbooks\session_manager.py", line 59, in new_requests_count return self.queue_manager.get_message_count(queue_name) File "C:\Users\83ideas-design\Downloads\DJANGO_COURSE_2.xx\djquic\django_quickbooks\queue_manager.py", line 120, in get_message_count return self._get_channel().queue_declare( File "C:\Users\83ideas-design\Downloads\DJANGO_COURSE_2.xx\djquic\django_quickbooks\queue_manager.py", line 66, in _get_channel self._input_channel = self._get_connection().channel() File "C:\Users\83ideas-design\Downloads\DJANGO_COURSE_2.xx\djquic\django_quickbooks\queue_manager.py", line 80, in _get_connection self._connection = BlockingConnection( File "C:\Users\83ideas-design\anaconda3\lib\site-packages\pika\adapters\blocking_connection.py", line 359, in __init__ self._impl = self._create_connection(parameters, _impl_class) File "C:\Users\83ideas-design\anaconda3\lib\site-packages\pika\adapters\blocking_connection.py", line 450, in _create_connection raise self._reap_last_connection_workflow_error(error) pika.exceptions.ProbableAuthenticationError: ConnectionClosedByBroker: (403) 'ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.' -
How do I authenticate against a remote database in Django?
I'm currently working on a project where I need to develop- and run a Django project on my local computer. However, I need to use another database that is located on a remote client host. In short: Django application: Runs on my localhost. Database: Runs on a remote client host. I have tried to change the database settings in settings.py to connect to the remote client database. However, it seems like the authentication doesn't take the settings database into consideration, because I couldn't authenticate with a user registered on that database. It seems to me as if it still tried to authenticate against my local database. Some authentication code so you know how the authentication id done: import inspect import re from django.apps import apps as django_apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.middleware.csrf import rotate_token from django.utils.crypto import constant_time_compare from django.utils.module_loading import import_string from django.utils.translation import LANGUAGE_SESSION_KEY from .signals import user_logged_in, user_logged_out, user_login_failed def load_backend(path): return import_string(path)() def _get_backends(return_tuples=False): backends = [] for backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) backends.append((backend, backend_path) if return_tuples else backend) if not backends: raise ImproperlyConfigured( 'No authentication backends have been defined. Does ' 'AUTHENTICATION_BACKENDS contain anything?' ) return backends def … -
Django Migrations Error : django.db.migrations.exceptions.NodeNotFoundError
I tried to add a new app in my django project and when I tried to make migrations the following error occured: django.db.migrations.exceptions.NodeNotFoundError: Migration masters.0001_initial dependencies reference nonexistent parent node ('auth', '0011_update_proxy_permissions') Now I checked why this error occured and I found out that it's because in Masters app I have this: dependencies = [ ('auth', '0011_update_proxy_permisssions'), ] I am not sure where this file exists, also I tried checking the last deployed version of the app and it has the same dependency but I couldn't find the file in the previously deployed version too. How can I rectify it ? -
Python Anywhere website no longer serving my products images
I have a deployed e-commerce site using pythonanywhere and the product images are no longer being served: You can visit the site to see what I mean at: www.ultimatecards5.com When I run the project locally it works perfectly: The code bases for both the deployed website and the local version are exactly the same. My settings.py: import os from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = str(os.getenv('SECRET_KEY')) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'shop.apps.ShopConfig', 'search_app.apps.SearchAppConfig', 'cart.apps.CartConfig', 'stripe', 'crispy_forms', 'order.apps.OrderConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'perfectcushion.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'shop', 'templates/'), os.path.join(BASE_DIR, 'search_app', 'templates/'), os.path.join(BASE_DIR, 'cart', 'templates/'), os.path.join(BASE_DIR, 'order', 'templates/') ], #to make the apps templates available throughout the project 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'shop.context_processors.menu_links', #adding the location of our context_processor.py file 'cart.context_processors.counter', …