Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django DetailView how to show the details page
I want to show the details of a product added. I followed this link and i could create an add product page https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html once the product is added, i want to show the details of the product added in a new page. So i tried the following: class ProductDetailView(DetailView): model = Product context_object_name = 'product' queryset = Product.objects.filter(pk) I really don't know what to put in the filter, or using filter is correct. i had tried using latest and order by instead of filter but they did not work. my urls.py is as follows: urlpatterns = [ path('', views.ProductDetailView.as_view(), name='product_changelist'), #path('', views.ProductListView.as_view(), name='product_changelist'), path('add/', views.ProductCreateView.as_view(), name='product_add'), path('<int:pk>/', views.ProductUpdateView.as_view(), name='product_change'), path('ajax/load-subcategory/', views.load_subcategory, name='ajax_load_subcategory'), #path('<int:product_id>', views.detail, name='detail'), ] Currently i am getting error as AttributeError at /product/ Generic detail view ProductDetailView must be called with either an object pk or a slug. I read that we have to provide the pk in urls.py so i tried providing pk as follows: path('<int:pk>', views.ProductDetailView.as_view(), name='product_changelist'), but then i get an error as follows: NoReverseMatch at /product/add/ Reverse for 'product_changelist' with no arguments not found. 1 pattern(s) tried: ['product\\/(?P<pk>[0-9]+)$'] Any help in solving this problem is highly appreciated. I am new to django so may … -
How to create models directly for OneToOne Relationships in Django
As far as I read, I can create Items in the Django Shell and in the admin panel after some configuration. But what I want is a "Subitem" of an "Item" that is created directly every time I create an "Item". How it is: Item is created via admin, needs "Upvote" and "Downvote" subitems to be created too manually. How do I change Django to directly create Upvote and Downvote for me? Thank you! -
Django - error after deploying to Heroku
I have build my react to assets folder using the Production Setup mentioned in this article. Now, these are my files: settings.py (only showing the relevant code) import os from datetime import timedelta BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ './redditapp/templates/', os.path.join(BASE_DIR, "templates"), ], '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', ], }, }, ] WSGI_APPLICATION = 'reddit.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'redditdb', 'HOST': 'localhost', 'USER':'root', 'PASSWORD': 'root' } } STATIC_URL = '/static/' WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.dev.json'), } } PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' production_settings.py from .settings import * import dj_database_url STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets"), ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.prod.json'), } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) wsgi.py import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reddit.production_settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) I have deployed this app to heroku and I am getting this error: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_7222952d88771595dbd4ffb2924e986c/reddit/static' Traceback remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): … -
is it better to load content in table rows dinamically with jquery or statically with django loop
Lets say i have table of 20k rows and each row has dropdown button. Is it better to load data-content of that dropdown button via jquery when user clicks on the button (i mean all divs and buttons, inputs, etc..) or is it better to just statically put it there with for loop using django template language, which means that i will have html document with a lot more similar rows. I am asking about performance, because in my small brain i think that many rows in html document can cause laggs. -
Integrity Error with Django 2.1
I try to update one of my projects to Django 2.1. It is perfectly working with Django 2.0.7 and after the update to Django 2.1 I obtain the following error while trying to launch the unittests: python manage.py test Creating test database for alias 'default'... Destroying old test database for alias 'default'... Traceback (most recent call last): File "c:\gitpro~1\feedcr~1.io\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "c:\gitpro~1\feedcr~1.io\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: auth_permission.content_type_id, auth_permission.codename Any idea on what could be the cause, I tried to give a look to the Changelog and it didn't really help... Changelog: https://docs.djangoproject.com/en/2.1/releases/2.1/ -
Django: Formset & unnecessary input fields
I want to update the model_field cancelled with a model_formset. To 'inform' the user, I also want to show the values first_name, last_name & ticket_reference. However, that makes it mandatory to include {{ form.ticket_reference }} etc. just to hide it in __init__. Is there a better approach? views.py formset = RefundFormSet( request.POST, queryset=order.attendees.all(), ) if formset.is_valid(): # do something with the formset.cleaned_data print("FORMSET SUCCESS") instances = formset.save(commit=False) for instance in instances: instance.save(update_fields=['canceled']) print(instance, "SAVED...") else: form = RefundForm() formset = RefundFormSet( queryset=order.attendees.all(), ) forms.py class CancelTicketForm(forms.ModelForm): class Meta: model = Attendee fields = ['canceled', 'first_name', 'last_name', 'ticket_reference', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ticket_reference'].widget = forms.HiddenInput() self.fields['first_name'].widget = forms.HiddenInput() self.fields['last_name'].widget = forms.HiddenInput() template.html <form method="post"> {{ formset.management_form }} {% csrf_token %} {% for form in formset %} {{ form.id }} {{ form.canceled }} {{ form.first_name.value }} {{ form.first_name }} {{ form.last_name.value }} {{ form.last_name }} {{ form.ticket_reference.value }} {{ form.ticket_reference }} {% endfor %} <button class="btn btn-primary" type="submit"> {% trans "Refund" %} </button> </form> -
Get data from a model based on a list from another model object
I have two models as follow : class Books(models.Model): poster = models.CharField(max_length=2000) bookid = models.CharField(max_length=10) title = models.CharField(max_length=150) year = models.IntegerField() def __str__(self): return self.title class UserRating(models.Model): userid = models.CharField(max_length=20) rating = models.CharField(max_length=5) bookid = models.CharField(max_length=10) In the views.py I get all the current logged in user rates and put it in bookid list : def rated(request): rate = UserRating.objects.filter(userid=request.user.id)[:5] bookid = [] for i in rates: bookid.append(i.bookid) What I want to do is getting every book poster by its bookid.diplaying all books that the user rated with its poster and the rate. How can I do that? -
Why is my view context not displaying in this case?
Just as it sounds, I cannot display a context variable "{{ var }}" provided in a view. I've tried cbv and function based views. In this project I am using Django 2.1 and Python alias is set as 3.6 This is the first sort of view I used, simply to display a number: class NotificationView(DetailView): template_name = "base.html" def get_context_data(self, **kwargs): message_count = Message.objects.filter(recipient=self.request.user).count() safeTrans_count = SafeTransaction.objects.filter(trans_recipient=self.request.user).count() context = super().get_context_data(**kwargs) context["Notify"] = message_count + safeTrans_count return context This is the second sort of view, I tried to make the simplest possible function that would display a context: def NotifyView(request): title="Notification View %s" %(request.user) context={def NotifyView(request): title="Notification View %s" %(request.user) context={ "Notification_Count":10, "Notification_Title":title, } return render(request,"base.html", context) "Notification_Count":10, "Notification_Title":title, } return render(request,"base.html", context) This is a snippet of the template used to display : {% if user.is_authenticated %} <a class="active-2" href="#">Notifications{{Notification_Title}} <i class="fas fa-exclamation-circle"> </i> </a> {% else %} Any ideas as to what I could be overlooking would be very much appreciated. -
How to configure EXPLORER_CONNECTION_NAME using django-sql-explorer
I am using django-sql-explorer and i have three db connection in setting.py i want to run query in there playground but i got exception while i am running query . I did following configuration in setting.py INSTALLED_APPS = ( ..., 'explorer', ... ) url(r'^explorer/', include('explorer.urls')), EXPLORER_CONNECTIONS = { 'Default': 'readonly' } EXPLORER_DEFAULT_CONNECTION = 'readonly' I just want to understand how can i pass EXPLORER_CONNECTION_NAME values. I have multiple database in my setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django2', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, 'USER': 'root', 'PASSWORD': 'bazaar360', 'HOST': 'demodb.birdeye.com', 'PORT': '3306' }, 'integrationdb2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django1', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, 'USER': 'root', 'PASSWORD': 'bazaar360', 'HOST': 'demodb.birdeye.com', 'PORT': '3306' }, 'integrationdb3': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, 'USER': 'root', 'PASSWORD': 'bazaar360', 'HOST': 'demodb.birdeye.com', 'PORT': '3306' } } -
Django migrate app expected fields are not created
I´m trying to update an outdated database of an Django project. The project uses an app called 'people'. When running python manage.py migrate people --fake-initial OR python manage.py migrate people I would expect that a missing columns called people.language will be created, which does not happen. This is strange as when checking the migrations file python manage.py sqlmigrate people 0026 One can see the alter of the table for people.language and a default inserted value of 'en' CREATE TABLE "people_profilenew" (... "language" ... INSERT INTO "people_profilenew" ("... SELECT "profile"... 'en', It seems I´m missing something really stupid and easy but cannot see the forest because of trees. Thanks for your help! -
Using Django's app model in scrapy pipeline gives 'Apps aren't loaded yet' exception
I want to use Django's(version-2.2) Model in scrapy's pipeline.py. I followed these links, https://medium.com/@ali_oguzhan/how-to-use-scrapy-with-django-application-c16fabd0e62e Use Django's models in a Scrapy project (in the pipeline) and added line 'django.setup()' in settings.py of scrpay project. It gives me following error, File "D:\Technologies\Python_Code\django_develops\django_development\kumo_soft\findchipsData\..\inventory\models.py", line 7, in <module> class Product(models.Model): File "c:\program files (x86)\lib\site-packages\django-2.2-py3.6.egg\django\db\models\base.py", line 101, in _new_ new_class.add_to_class('_meta', Options(meta, app_label)) File "c:\program files (x86)\lib\site-packages\django-2.2-py3.6.egg\django\db\models\base.py", line 304, in add_to_class value.contribute_to_class(cls, name) File "c:\program files (x86)\lib\site-packages\django-2.2-py3.6.egg\django\db\models\options.py", line 203, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "c:\program files (x86)\lib\site-packages\django-2.2-py3.6.egg\django\db\__init_.py", line 33, in _getattr_ return getattr(connections[DEFAULT_DB_ALIAS], item) File "c:\program files (x86)\lib\site-packages\django-2.2-py3.6.egg\django\db\utils.py", line 202, in _getitem_ backend = load_backend(db['ENGINE']) File "c:\program files (x86)\lib\site-packages\django-2.2-py3.6.egg\django\db\utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "c:\program files (x86)\lib\importlib\__init_.py", line 126, in import_module return bootstrap.gcd_import(name[level:], package, level) File "c:\program files (x86)\lib\site-packages\django-2.2-py3.6.egg\django\db\backends\mysql\base.py", line 20, in <module> ) from err django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Please help to resolve this. -
Django- ModuleNotFoundError: No module named 'django.urls'
I am new to python and Django. I am learning using the MDN text guide. This is what I followed to setup my computer-https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/development_environment#Using_a_virtual_environment This is what my command prompt shows me when I try to test my development webserver (my_django_environment2) C:\Users\user\Desktop\django_gopal\mytestsite>py -3 manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001FEB45AD8C8> Traceback (most recent call last): File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\core\management\commands\runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\core\management\base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\core\checks\registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\core\checks\urls.py", line 10, in check_url_config return check_resolver(resolver) File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\core\checks\urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\utils\functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\core\urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\utils\functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python36\lib\site-packages\django-1.9-py3.6.egg\django\core\urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "C:\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen … -
Why can't I Interact with a Django Form Element Via Jquery
I have the following search form rendered into an HTML template. <form id="resource-search-form" action="{% url 'stock:resource_search_view' %}" method="POST"> {% csrf_token %} <input type="text" name="query" id="id_query" maxlength="50"> <button class="btn btn-success" style='position:relative;top:-10px;left:-72px;'>Search</button> </form> The issue is whenever I try to interact with the element via some sort of JavaScript, the command is basically "ignored". To illustrate, I've added another input just below the form, and attempted to interact with it the same way and it works as expected. <input id="test" type="text" name="test" maxlength="50"> I can confirm this because I used the following to demonstrate: $(document).ready(function() { $('#id_query').val("This doesn't work"); $('#test').val("This does work"); }); And whoa and behold, the input with id test had the value "This does work" inside it, while id_query was blank... Can someone please enlighten me as to why this is occurring, and provide a solution to the problem? -
Run Django-Viewflow Update node?
I'm using django-viewflow to create a workflow programatically. This is my flow class. class APLWorkflow(Flow): start = ( flow.StartFunction(function1) .Next(this.shipment_create) ) shipment_create = ( flow.Function(function3) .Next(this.delivery_mode) ) delivery_mode = ( flow.If(cond=lambda x: 1 > 2) .Then(this.check_insurance) .Else(this.request_quotes) ) request_quotes = ( flow.Handler(function3) .Next(this.join_clerk_warehouse) ) check_insurance = ( flow.Handler(function3) .Next(this.fill_post_label) ) fill_post_label = ( flow.Handler(function3) .Next(this.join_on_insurance) ) join_on_insurance = ( flow.Join() .Next(this.join_clerk_warehouse) ) # Warehouse worker package_goods = ( flow.Handler(function3) .Next(this.join_clerk_warehouse) ) join_clerk_warehouse = ( flow.Join() .Next(this.move_package) ) move_package = ( flow.Function(function3) .Next(this.end) ) end = flow.End() What I do is, I start the flow programatically, when a POST request is made onto an endpoint E1, I run APLWorkFLow.start.run(**some_kwargs) It starts correctly, and after the processing of the start is completed, then the response is returned back to the client. Now, shipment_create is run when a POST request is made on endpoint E2, and I again run it programmatically via, activation.flow_task.run(**some_kwargs) It runs correctly and completes the flow upto move_package. THE PROBLEM I update the details of shipment, via PUT request on endpoint E3, and I want to rerun the complete flow after node shipment_create. How can I do that? 1) How can I re-run the flow after a specific node? … -
Dropdown list html code
I want to display dropdown choices for certain fields. I have a model workorder and i created a model form. I created a file choices.py and defined the created choices in the model and also at forms.py but I don't know the html code to display the choices. I'm a beginner so would appreciate any help. This is my code: The field I'm trying to make dropdowns is WO_Type_ID. models.py from __future__ import unicode_literals from django.db import models from django.contrib.gis.db import models from multiselectfield import MultiSelectField from MMS.choices import * class Workorder(models.Model): WO_ID = models.BigIntegerField(primary_key=True) WO_DateDefWO = models.DateField() WO_DateSched = models.DateField(blank=True, null=True) WO_DateFinished = models.DateField(blank=True, null=True) WO_ST_ID_Sign = models.BigIntegerField(blank=True, null=True) WO_Status_ID = models.BigIntegerField(blank=True, null=True) WO_Type_ID = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES) WO_Comments = models.CharField(max_length=254, blank=True, null=True) WO_Nav_ID = models.BigIntegerField(blank=True, null=True) WO_Nav_Kons_ID = models.CharField(max_length=12, blank=True, null=True) WO_Nav_Name = models.CharField(max_length=254, blank=True, null=True) WO_Nav_CustAdr = models.CharField(max_length=254, blank=True, null=True) WO_Nav_Debt = models.FloatField(blank=True, null=True) WO_Nav_PropCode = models.CharField(max_length=254, blank=True, null=True) WO_Nav_DepCode = models.CharField(max_length=254, blank=True, null=True) WO_Nav_PhoneNo = models.CharField(max_length=254, blank=True, null=True) WO_Nav_ReasonCompl = models.CharField(max_length=254, blank=True, null=True) WO_NightShift = models.BooleanField(default=False) WO_Priority = models.BigIntegerField(blank=True, null=True) WO_RE_ID = models.BigIntegerField(blank=True, null=True) WO_MapUrl = models.CharField(max_length=254, blank=True, null=True) def __unicode__(self): return self.WO_ID views.py from django.shortcuts import render, get_object_or_404, redirect from django import forms from … -
How do I set enable SSL on my server?
When changing my settings to environment variables I started getting the error "server does not support SSL, but SSL was required." I thought I had done this, and if not I'm not sure what I still have to do. I've 'djangosecure' and 'sslserver' in installed apps. ssslmode is 'on' in my postgres.conf: #authentication_timeout = 1min # 1s-600s #ssl = on # (change requires restart) #ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers # (change requires restart) #ssl_prefer_server_ciphers = on # (change requires restart) #ssl_ecdh_curve = 'prime256v1' # (change requires restart) #ssl_cert_file = 'server.crt' # (change requires restart) #ssl_key_file = 'server.key' # (change requires restart) #ssl_ca_file = '' # (change requires restart) #ssl_crl_file = '' # (change requires restart) #password_encryption = on #db_user_namespace = off #row_security = on The interesting thing to me is that throughout the entire time of development I didn't get this error; only now that I've tried to change my settings to environment variables for production. What is the setting or configuration that I'm missing? -
How does view process data with HTML form?
I am looking at this example. This is search_form.html <html> <head> <title>Search</title> </head> <body> <form action="/search/" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> </body> <html> Urls.py urlpatterns = [ # ... url(r'^search-form/$', views.search_form), url(r'^search/$', views.search), # ... ] And views from django.http import HttpResponse from django.shortcuts import render from books.models import Book def search(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] books = Book.objects.filter(title__icontains=q) return render(request, 'search_results.html',{'books':books,'query':q}) else: return HttpResponse('Please submit a search term.') When GET data is passed into the query string, /search/?q=paris what really happens? The form in HTML is bound or unbound at this point? I am newbie to Django, it would be nice if someone can explain. -
openid connect provider and client example in django
I need to build a Django web-app. My web-app needs to support authentication and authorization using OpenID Connect. It is my first time doing this. Is there a free Identity Provider to test my application or do I need to write the provider and the client? My task is to write only the client that connects to the provider. An example would be great or some course/tutorial I can use to learn how to do this. Maybe there are no good examples in Django but I know ASN.NET and Java so those examples could inspire me as well. -
Attach a generator to a django model instance
I have a model instance, which I want to attach a generator instance to. I tried doing so through the init function, but as it reruns every time I call it, it always re-defines it and, therefore, always yields the very first element: class MyModel(models.Model): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.gen = self.my_gen() def use_generator(self): print(next(self.gen)) # always prints the first yielded element def my_view(request, id): my_model = get_object_or_404(MyModel, id=id) my_model.use_generator() How can I make it work? Thanks! -
Using django-cas-ng to authenticate on admin site
I'm using django-cas-ng framework to authenticate users. The main problem is that the admin page still uses the default login view. Methods used this far: 1.- Using env var From docs: CAS_ADMIN_PREFIX: The URL prefix of the Django administration site. If undefined, the CAS middleware will check the view being rendered to see if it lives in django.contrib.admin.views. 2.- Redirecting url on app/urls.py: url(r'^arta/admin/login$', django_cas_ng.views.login, name='cas_ng_logint') Everything is just ignored and the admin login form is shown. The goal of this is to only authenticate with CAS and redirect the current /app/admin/login to CAS -
models in Django
i have created 2 models in Django event and education defined respectively by id_event and id_education,a user is registered either on an event or education ,there's nothing like creating an account for a user .i wanna create the model for user such either id_event ot id_education should not be null .my user model look right now like this: class user(models.Model): id_user=models.IntegerField(unique=True) email=models.EmailField(max_length=45) first name=models.CharField(max_length=30) last name=models.CharField(max_length=30) -
display only a certain word in a string
I'm making an API call that fetches me something like Session #1 - ABC Session #2 - DEF Session #3 - PQR and so on I want to render only the values after the hyphen (ABC, DEF, PQR) on a page. Logically, remove all the characters upto the nth character(hyphen, in this case). How do I do that, though? -
Immutable Django models
I want to save a new object whenever any model change is done instead of updating the current version. For example, let's take a basic scenario where I have two model class Question(models.Model): version = models.PositiveIntegerField(blank=False) title = models.CharField(max_length=250, blank=False) answers = models.ManyToManyField('Answer') def __str__(self): return self.title class Answer(models.Model): version = models.PositiveIntegerField(blank=False) text = models.CharField(max_length=100) def __str__(self): return self.text I have created a new Question object. Let call it Q1(pk=1) which have 3 answers attached to it A1(pk=1), A2(pk=2) and A3(pk=3). Now when add a new answer A4(pk=4) to Q1(pk=1). It creates a new version of Q1(pk=2) and appends A4(pk=4) to it. So that I can still access the previous version of Q1. -
Pass the List from Script to View via AJAX
{% for s in cart_final %} <tr class="hidethis"> <td>{{s.prodimage}}</td> <td>{{s.prodname}}</td> <td>{{s.price}}</td> <td ><input onchange=valuechange(this,{{s.shopid}},{{s.prodid}},{{s.custid}}) value="{{s.quantity}}"></td> <td>{{s.companyname}}</td> <td>{{s.prodsize}}</td> <td>{{s.shopname}}</td> <td>{{s.storeprice}}</td> <td><button class="btn btn-sm btn-danger">X</button></td> </tr> {% endfor %} var cart_product = [] var carta = '' function valuechange(val,shopid,prodid,custid){ productexist=false ; if(cart_product.length!=0){ for(var i=0; i<cart_product.length;i++){ if(cart_product[i].prodid == prodid){ cart_product[i].quantity=val.value; productexist=true; } } } if(productexist==false){ add_product = { "shopid": shopid, "custid": custid, "prodid": prodid, "quantity": val.value, } cart_product.push(add_product) } carta=JSON.stringify(cart_product); } function submitcart(){ var resu=carta; $.ajax({ headers: { "X-CSRFToken": '{{csrf_token}}' }, type: "POST", url: "/cart_update/", data:{"content": resu}, success:function(){ } }); } I am recieving the context 'cart_final' from views and now i need to update the list and send it back again to view. I am going to update few things in list, and keep some unchanged. Also,how can I pass the 'cart_final' inside this script? -
Deploying Django project, running on Python 3.6, on AWS using ElasticBeanstalk
I have done this before too using Python2.7 using this resource But, this error is new to me Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 This following is the detailed traceback (ElasticBeanstalk::ExternalInvocationError) caused by: Traceback (most recent call last): File "/opt/python/run/venv/bin/pip", line 7, in <module> from pip import main File "/opt/python/run/venv/local/lib/python3.6/site-packages/pip/__init__.py", line 28, in <module> from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/opt/python/run/venv/local/lib/python3.6/site-packages/pip/vcs/subversion.py", line 9, in <module> from pip.index import Link File "/opt/python/run/venv/local/lib/python3.6/site-packages/pip/index.py", line 31, in <module> from pip.wheel import Wheel, wheel_ext File "/opt/python/run/venv/local/lib/python3.6/site-packages/pip/wheel.py", line 6, in <module> import compileall File "/usr/lib64/python3.6/compileall.py", line 20, in <module> from concurrent.futures import ProcessPoolExecutor File "/opt/python/run/venv/local/lib/python3.6/site-packages/concurrent/futures/__init__.py", line 8, in <module> from concurrent.futures._base import (FIRST_COMPLETED, File "/opt/python/run/venv/local/lib/python3.6/site-packages/concurrent/futures/_base.py", line 381 raise exception_type, self._exception, self._traceback ^ SyntaxError: invalid syntax 2018-08-02 09:33:29,231 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True) File "/usr/lib64/python2.7/subprocess.py", line 186, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (Executor::NonZeroExitStatus) I don't understand what …