Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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', … -
drf serializer data not showing all fields data properly
id field and name field not showing in result. in models.py: class Group(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) admin = models.ForeignKey(User, on_delete=models.CASCADE) member = models.ManyToManyField(User, related_name='groups_user') def __str__(self): return self.name in serializers.py: class SimpleUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','first_name', 'last_name') class GroupSerializer(serializers.Serializer): admin = SimpleUserSerializer() class Meta: model = Group fields = ('id','name','admin') views.py: @api_view(['GET']) @permission_classes((IsAuthenticated,)) def getSomeGroup(request): allGroup = Group.objects.all().count() randomGroupId = random.sample(range(allGroup), 3) randomGroup = Group.objects.filter(id__in=randomGroupId) serializer = GroupSerializer(randomGroup, many=True) #print(serializer) return Response(serializer.data) the result comes like this: [{"admin":{"id":1,"first_name":"asif","last_name":""}},{"admin":{"id":3,"first_name":"Test2","last_name":"lastname"}},{"admin":{"id":3,"first_name":"Test2","last_name":"lastname"}}] why id and name field not showing? -
How to merge two id's from same model in django?
I have a Model Market class Market(models.Model): market = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) parent_market = models.ForeignKey( 'ParentIndustry', null=True, blank=True, related_name='parent_market', on_delete=models.SET_NULL, default=None) def __str__(self): return str(self.market) I want to merge two id's EX: 258 and 855 of the Market model. I tried to merge using union, update but couldn't able to do it. -
Django filtering over a tsvector column
My Django application has a backend postgres database with a tsvector column that whose values are already computed and indexed. I want to use Django's ORM to do a full text search over that column with a query that would look something like this: SELECT [fields] FROM [table] WHERE tsvector_column @@ plainto_tsquery('TEXT HERE'); The problem I am running into is, when I use annotate and SearchVector, Django seems to re-to_tsvector over the tsvector column, resulting in an error. This is what I am doing: Posts.objects.annotate(search=SearchVector('THE_TS_VECTOR_COLUMN'),).filter(search='SEARCH TEXT') How would one do this in Django? Thanks! -
How to make it such that if there are errors in the form, all the data I have keyed into the field remains and only the error pops out
How to make it such that if there are errors in the form, all the data I have keyed into the field remains and the error shows for me to edit what I need to edit. Because it is very user-unfriendly if people press submit, and everything they have previously typed has to be retyped again due to an error that caused them to need to submit the form again. just like when we post a stackoverflow question, if there are errors in our question eg time limit, whatever we have typed previously remains Let me know if you require more code. html <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %} <div class="form-group"> <label for="id_title">Title</label> <input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus> </div> <button class="submit-button btn btn-lg btn-primary btn-block" type="submit">Submit</button> </form> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} views.py def create_blog_view(request): context = {} user = request.user if request.method == 'POST': form = CreateBlogPostForm(request.POST or None, request.FILES or None) if form.is_valid(): obj.save() return redirect('HomeFeed:main') else: context['form'] = form return render(request, "HomeFeed/create_blog.html", context) -
Django Fargate. The requested resource was not found on this server
I have seem The requested resource was not found on this server, like a thousand times but none of the awnser match my problem. I made this app from statch, and add a Dockerfile for it. FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /www COPY requirements.txt /www/ RUN pip install -r requirements.txt COPY . /www/ EXPOSE 80 CMD [ "python", "manage.py", "runserver", "0.0.0.0:80" ] Then i run this: docker build -t pasquin-django-mainapp . docker run pasquin-django-mainapp I did that in my local environment, not woking. Y push this Dcokerfile to ECR and then use it in ECS + Fargate, same bada result. I dont know what else todo. Somebody, help! thanks! ps: From docker-compose works just marvelous! -
How can I run Django server on a real server?
I am using VPS ssh server and I have in it a Django project. But the problem is that the command python3 manage.py runserver runs server localy. So if I have finished my project and want to post it on internet, what is the command? -
How to serve media files in production with Django and Heroku?
I just Uploaded my Django Blog to Heroku, and in the Blog I have a members app where users can create an account and upload an profile picture. But I have a problem each time I push a change to the app, by heroku git, all the media files, and therefore the profile picture goes away. What Can I do to preserve those media files? -
django forms not showing checkboxes
this is how my forms.py is class CreateMedicalRecordForm(forms.ModelForm): class Meta: model = MedicalRecords fields = ("title", "file", "doctor", "patient", "doctor_access", "general_access") widgets = { "title": forms.Textarea(attrs={"rows": "", "class": "form-control"}), "file": forms.FileInput(attrs={"class": "form-control col-md-9"}), "doctor": forms.Select(attrs={"class": "form-control col-md-9"}), "patient": forms.Select(attrs={"class": "form-control col-md-9"}), "doctor_access": forms.CheckboxInput(attrs={"class": "checkbox-toggle"}), "general_access": forms.CheckboxInput(attrs={"class": "checkbox-toggle"}), } labels = { "title": "Description (Optional)", "patient": "Self or Relative", "general_access": "General Access For Record", "doctor_access": "Doctor Access For Record", } in template checkboxes are not showing it just get the Label and the checkbox is invisible, no matter how I'm using as form.as_p or loop through the form fields still the same result(not showing). -
How to use Explainx library in django rest framework. Can anynone please help me
I want to use explainx library from explainX.ai (ARTIFICIAL INTELLIGENCE) in django rest framework import explainx i really waant to use it in django but i didnt know how to use it in django... please help me -
Hosting multiple Django instances on a VPS
I'm moving away from WordPress and into bespoke Python apps. I've settled on Django as my Python framework, my only problems at the moment are concerning hosting. My current shared hosting environment is great for WordPress (WHM on CloudLinux), but serving Django on Apache/cPanel appears to be hit and miss, although I haven't tried it as yet with my new hosting company. - who have Python enabled in cPanel. What is the easiest way for me to set up a VPS to run a hosting environment for say, twenty websites? I develop everything in a virtualenv, but I have no experience in running Django in a production environment as yet. I would assume that venv isn't secure enough or has scalability issues? I've read some things about people using Docker to set up separate Django instances on a VPS, but I'm not sure whether they wrote their own management system. It's my understanding that each instance Python/Django needs uWSGI and Nginx residing within that virtual container? I'm looking for a simple and robust solution to host 20 Django sites on a VPS - is there an out of the box solution? I'm also happy to develop one and set up …