Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add 2 models at once in Django Admin?
In Django v1.11.10 I have 2 models: Article and Files. In one article there can be many files attached. With scheme below I can create Article in admin panel, and then create File with <select> options to choose what Article it is related. But I want to create Article and at the same page add many File objects pressing "plus" button. Like dynamically. Is it possible? class Article(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) class File(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) name = models.CharField(max_length=100) path = models.FileField(upload_to=file_upload_folder) admin.py: from django.contrib import admin from .models import * admin.site.register(Article) admin.site.register(File) -
how to execute python script in django framework?
I just wanted to execute python script in django 2. The python script will communicates with R305 fingerprint scanner. If i pressed a button in webpage, which executes the python script and initiates the sensor. Need help! -
Inserting hyperlinks into pdf generated with pisa
Currently I am generating a pdf from a html template in django/python. Here is a relevant snipit from my view result = StringIO.StringIO() html = render_to_string(template='some_ref/pdf.html', { dictionary passed to template},) pdf = pisa.pisaDocument(StringIO.StringIO(html), dest=result) return HttpResponse(result.getvalue(), content_type='application/pdf') And my template is an html file that I would like to insert a hyperlink into. Something like <td style="padding-left: 5px;"> <a href="/something_here/?referral_type={{ template_variable }}">{{ referral_all.1 }}</a> </td> Actually, the pdf generates fine and the template variables are passed correctly and show in the pdf. What is inside the a tag is highlighted in blue as if you could click on it, but when I try to click on it, the link is not followed. I have seen pdfs before with clickable links, so I believe it can be done. Is there a way I can do this to make clickable hyperlinks on my pdf using pisa? -
Transfer users between Django servers
I have two types of Django servers. One is a central server that contains a master database. There's only one of these. Then there's an arbitrary number of client servers that contain their own databases. These client databases act as a cache for the master database. This is used for users. I a user tries to log in on client server 1, that server looks for the user in its database. If it's not there, it goes out to the central server and asks that server if the user exists in the master database. If so, the central server returns the users info so that the client server can store/cache it in its own database and then log the user in. Each successive time that user tries to log in, the user is found in the client database and it no longer has to go out to the central server. The central server returns the users information as JSON like so: { "username": "joe.bag.o.doughnuts", "id": 143, "password": "fksdfjfldskjf", } My issue here is the password. when I put the value in there as just user.password, it uses the encrypted version of that password. This is good because I don't want … -
How do I run migrations in Dockerized Django?
I followed a Docker + Django tutorial which was great, in that I could successfully build and run the website following the instructions. However, I can't for the life of me figure out how to successfully run a database migration after changing a model. Here are the steps I've taken: Clone the associated git repo Set up a virtual machine called dev with docker-machine create -d virtualbox dev and point to it with eval $(docker-machine env dev) Built and started it up with docker-compose build and docker-compose up -d Run initial migration with docker-compose run web python manage.py migrate. (This is the only time I'm able to run a migration that appears successful) Checked that the website works by navigating to the IP address returned by docker-machine ip dev Make a change to a model. I just added name = models.CharField(default='Unnamed', max_length=50, null=False) to the Item model in web/docker_django/apps/todo/models.py file. Update the image and restart the containers with docker-compose down --volumes, then docker-compose build, then docker-compose up --force-recreate -d Migration attempt number 1: docker-compose run web python manage.py makemigrations todo then docker-compose run web python manage.py migrate. After the makemigrations command it said Migrations for 'todo': 0001_initial.py: - Create model … -
Django Cart and Item Model - getting quantity to update
I am working on a Django cart application. I have two models Cart and Item. I am trying to get the quantity to update when an Item is added to the basket but cant get the views to work properly. I am having problems getting item_obj assignment to work - do I need to do anything with the model manager here? Any help is really appreciated. Models.py class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) class Item(models.Model): item = models.ForeignKey(Product, null=True) cart = models.ForeignKey(Cart, null=True) quantity = models.PositiveIntegerField() Views.py extract def cart_update(request): product_id = request.POST.get('product_id') product_obj = Item.objects.get(id=product_id) print(item_id) item_obj = Item.objects.get(id=product_id) cart_obj, new_obj = Cart.objects.new_or_get(request) if item_obj in cart_obj.products.all(): cart_obj.products.add(product_obj) item_obj.quantity += 1 item_obj.save() else: cart_obj.products.add(product_obj) return redirect("cart:home") -
Keras/TF trained model works as web app once, then value errors
TF community -- So I have trained a TensorFlow model using simple MNIST data. I'm using Keras' load_model in a Python script to pull it up and model.predict() to feed images to the model (once the data is properly transformed) so it can make predictions. This works well when running predict.py from the command line with various examples. But my goal is to web app-ify this prediction script so I can ping it from other apps. It was fairly easy to spin up a Django app and cause predict.py to run whenever a certain URL endpoint was hit. Given a random MNIST image sent in a POST request, the app will (usually correctly) make a prediction the first time, which I can see in the server logs in square brackets: 2018-02-09 17:49:40.639847: I C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:1195] Creating TensorFlow d evice (/device:GPU:0) -> (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1) [5] [09/Feb/2018 17:49:43] "POST /predict/ HTTP/1.1" 200 1 Then, without fail, all subsequent posts generate errors until I restart the server with python manage.py runserver. I usually get several overlapping exceptions to this where it doesn't like various some placeholder values - but to my knowledge … -
Highlight keyword in Django project
I have a django project which has a 'detail.html' file extended from 'base.html' file.This detail.html contains a search filter form.Here is my question in short "How to highlight the keyword specified in the search filter using jQuery" PS:I have already tried parsing the content of the detail.html and appending <span style="background-color: #FFFF00">Yellow text.</span> using javascript. But what I need is to highlight automatically without submitting the form or reloading the page (similar to command like onKeyUp) base.html {% load staticfiles %} <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> {% block head %} My Blog {% endblock head %} </title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link href='{% static "css/bootstrap.min.css" %}' rel="stylesheet"> {% comment %} <link href='{% static "css/bootstrap1.min.css" %}' rel="stylesheet"> {% endcomment %} <link rel="stylesheet" href='{% static "css/base.css" %}' /> {% block head_extra %} {% endblock head_extra %} </head> <body style="background-color:white"> {% block navbar %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="#"> Start Bootstrap </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'post:home' %}">Home <span class="sr-only">(current)</span> </a> </li> <li … -
Java Script on Internet information server not working
I have written a django app and am trying to run it through iis on a windows 10 client. The app runs just fine as expected except the java scripts will not execute. I have a parallel installation running on the same machine and the java scripts run just fine using the django web server Any suggestions as to how to get the scripts to run would be appreciated -
gunicorn + django + nginx -- recv() not ready (11: Resource temporarily unavailable)
I am getting this issue. I am trying to setup a server and cannot get it running. I am using django, gunicorn and nginx. here are the logs nginx log 2018/02/09 22:22:32 [debug] 1421#1421: *9 http write filter: l:1 f:0 s:765 2018/02/09 22:22:32 [debug] 1421#1421: *9 http write filter limit 0 2018/02/09 22:22:32 [debug] 1421#1421: *9 writev: 765 of 765 2018/02/09 22:22:32 [debug] 1421#1421: *9 http write filter 0000000000000000 2018/02/09 22:22:32 [debug] 1421#1421: *9 http copy filter: 0 "/?" 2018/02/09 22:22:32 [debug] 1421#1421: *9 http finalize request: 0, "/?" a:1, c:1 2018/02/09 22:22:32 [debug] 1421#1421: *9 set http keepalive handler 2018/02/09 22:22:32 [debug] 1421#1421: *9 http close request 2018/02/09 22:22:32 [debug] 1421#1421: *9 http log handler 2018/02/09 22:22:32 [debug] 1421#1421: *9 free: 000055D4A01ACBE0 2018/02/09 22:22:32 [debug] 1421#1421: *9 free: 000055D4A01C6FB0, unused: 0 2018/02/09 22:22:32 [debug] 1421#1421: *9 free: 000055D4A01B9F80, unused: 214 2018/02/09 22:22:32 [debug] 1421#1421: *9 free: 000055D4A01C9460 2018/02/09 22:22:32 [debug] 1421#1421: *9 hc free: 0000000000000000 0 2018/02/09 22:22:32 [debug] 1421#1421: *9 hc busy: 0000000000000000 0 2018/02/09 22:22:32 [debug] 1421#1421: *9 reusable connection: 1 2018/02/09 22:22:32 [debug] 1421#1421: *9 event timer add: 3: 70000:1518215022208 2018/02/09 22:22:32 [debug] 1421#1421: *9 post event 000055D4A01D8BD0 2018/02/09 22:22:32 [debug] 1421#1421: *9 delete posted event … -
Images in my create view not working django
This is my view and it is saving the data but not the image. How to resolve it? def DoubtCreate(request): if request.method == 'POST': if not request.user.is_authenticated: print(user) return redirect('students:login') else: form = CreateDoubt(request.POST) if form.is_valid(): topic = form.cleaned_data.get("topic") desc = form.cleaned_data.get("desc") links = form.cleaned_data.get("links") Tags = form.cleaned_data.get("Tags") image = form.cleaned_data.get('image') question = form.cleaned_data.get("question") user = request.user Doubt.objects.create( User = request.user, topic=topic, image= image, Tags = Tags, links = links, desc = desc, question = question, ) return redirect('community:allask') else: if not request.user.is_authenticated: return redirect('students:login') else: form = CreateDoubt() return render(request, 'community/AskQuestion.html', {'form': form}) class CreateDoubt(forms.ModelForm): class Meta: model = Doubt fields = [ 'topic','question', 'desc', 'image', 'Tags', 'links'] I have tried most of ways but images stills not saved. Is the image saving not possible or something else. -
Host not found in upstream "web" in /etc/nginx/sites-enabled/django_project:12
I am using Docker Compose to build a multi-container Docker Django app. I have a docker-compose.yml file that sets up 4 containers: web, nginx, postgres, and redis. When I perform docker-compose build it works without error and gives me a key for my image, but when I try to run it, I get this error nginx: [emerg] host not found in upstream "web" in /etc/nginx/sites-enabled/django_project:12 I'm new to Docker and configuration with yml at that so I'm not sure where the problem lies. docker-compose.yml version: '3' services: web: restart: always build: . expose: - "8005" links: - postgres:postgres - redis:redis volumes: - /usr/src/app - /usr/src/app/static env_file: .env command: /usr/local/bin/gunicorn docker_app.wsgi:application -w 2 -b :8005 nginx: restart: always build: ./nginx/ ports: - "80:80" volumes: - /www/static links: - web:web postgres: restart: always image: postgres:latest ports: - "5432:5432" volumes: - ./pgdata:/var/lib/postgresql/data/ redis: restart: always image: redis:latest ports: - "6379:6379" volumes: - ./redisdata:/data - ./redisdata:/data:rw Project Tree ├── Dockerfile ├── Makefile ├── Procfile ├── README.md ├── celerybeat-schedule ├── circle.yml ├── devops ├── docker-compose.yml ├── jwtAuth.py ├── manage.py ├── newrelic.ini ├── nginx │ ├── Dockerfile │ └── sites-enabled │ └── django_project ├── requirements.txt ├── start.sh └── docker_app ├── __init__.py ├── admin.py ├── api ├── … -
Django AJAX make a Quiz with questions and user answers. I have no idea how get value=" " in AJAX template
I have a task to make a quiz. My models: from django.db import models from django.conf import settings class Metrix(models.Model): title = models.CharField(max_length=256, verbose_name='Question') metrix_category = models.ForeignKey( 'category', related_name='Question_category', on_delete=models.CASCADE, verbose_name='Category', ) is_published = models.BooleanField(default=False) def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=256, verbose_name='Question_category') is_published = models.BooleanField(default=False) def __str__(self): return self.title class Month(models.Model): title = models.CharField(max_length=256, verbose_name='Month') is_published = models.BooleanField(default=False) def __str__(self): return self.title class Year(models.Model): title = models.CharField(max_length=256, verbose_name='Year') is_published = models.BooleanField(default=False) def __str__(self): return self.title class User_metrix(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_metrix", verbose_name='User') metrix = models.ForeignKey('Metrix', on_delete=models.CASCADE, verbose_name='Question') year = models.ForeignKey('Year', on_delete=models.CASCADE, verbose_name='Year') month = models.ForeignKey('Month', on_delete=models.CASCADE, verbose_name='Month') value = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='Value') add_datetime = models.DateTimeField(auto_now_add=True, verbose_name='Time') My view: from django.shortcuts import render, HttpResponseRedirect, get_object_or_404 from django.contrib.auth.decorators import login_required from metrix.models import Metrix, Month, Year, User_metrix from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import JsonResponse from django.template.loader import render_to_string #main view I got questions: @login_required def metrix_view(request, pk=None, page=1): # pk = 4 if request.is_ajax(): metrix_list = Metrix.objects.filter(is_published=True, metrix_category__pk=pk) return JsonResponse({'result': result}) else: metrix_year = Year.objects.get(pk='3') metrix_month = Month.objects.get(pk='6') metrix_category = { 'pk': 4 } user_metrix_value = User_metrix.objects.filter( user=request.user, year=metrix_year, month=metrix_month) metrix_list = Metrix.objects.filter( is_published=True, metrix_category__pk=pk) year_list = Year.objects.filter(is_published=True) month_list = Month.objects.filter(is_published=True) user_metrix_list = User_metrix.objects.filter(user = … -
How to install koalixcrm docker on synology DS918+, How to run docker compose on synology
I purchased a Synology DS918+ because I would like to install and run the docker file of koalixcrm https://github.com/scaphilo/koalixcrm. (This is a django based crm which requires postgresql docker as well Through the GUI i can only upload a docker file and install it but I need to run docker compose to set up the full application with the database. Does anyone known how to do this on the Synology? Thanks a lot for your help. -
Deploy readthedocs on production (nginx + gunicorn)
I am trying to deploy to a production server the project Read The Docs (http://docs.readthedocs.io/en/latest/install.html) for internal use at the company I work. I followed the install steps at the above url, it worked when I run with 'python manage.py 0.0.0.0:8000', but when I tried to deploy with Nginx + Gunicorn + Supervisord, the builds doesn't start, it keep showing 'Triggered version latest (html)' On the serve I got the error below, but I have no idea what I did wrong. Is the Read The Docs able to run with Nginx + Gunicorn + Supervisord? Do I have to install or configure celery? Thanks in advance! [09/Feb/2018 15:29:59] "GET /api/v2/project/2/ HTTP/1.1" 403 39 [09/Feb/2018 15:29:59] readthedocs.projects.tasks:159[15266]: ERROR An unhandled exception was raised during build setup Traceback (most recent call last): File "/webapps/readthedocs/src/readthedocs/projects/tasks.py", line 144, in run self.project = self.get_project(pk) File "/webapps/readthedocs/src/readthedocs/projects/tasks.py", line 299, in get_project project_data = api_v2.project(project_pk).get() File "/webapps/readthedocs/rtd_env/local/lib/python2.7/site-packages/slumber/__init__.py", line 155, in get resp = self._request("GET", params=kwargs) File "/webapps/readthedocs/rtd_env/local/lib/python2.7/site-packages/slumber/__init__.py", line 101, in _request raise exception_class("Client Error %s: %s" % (resp.status_code, url), response=resp, content=resp.content) HttpClientError: Client Error 403: http://localhost:8000/api/v2/project/2/ [09/Feb/2018 15:29:59] celery.app.trace:248[15266]: ERROR Task readthedocs.projects.tasks.update_docs[1cf185cd-57dd-478b-8689-bb795f26543c] raised unexpected: AttributeError("'UpdateDocsTask' object has no attribute 'setup_env'",) Traceback (most recent call last): File "/webapps/readthedocs/rtd_env/local/lib/python2.7/site-packages/celery/app/trace.py", … -
Django Celery Timezone setting not working
I have the following settings in my settings.py: TIME_ZONE = 'America/New_York' CELERY_TIMEZONE = 'America/New_York' USE_TZ = True But my tasks seem to be running in London time: 'add-every-minute': { 'task': 'api.tasks.add', 'schedule': crontab(minute='*/1', hour='8-17', day_of_week='1-5'), }, I tried following the steps here http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html to reset the time zone but I get this error instead: Model class djcelery.models.TaskMeta doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I'm using: python==3.6.2 Django==2.0.1 django-celery==3.2.2 sqlite3 -
Adding to cart quantity Django
I am trying to update the quantity on my cart but it doesn't actually update the quantity. My cart is model based but I think the problem line is here: product_obj['quantity'] += 1 I get an error: 'Product' object is not subscriptable My views.py def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.add(product_obj) product_obj['quantity'] += 1 return redirect("cart:home") -
Preserve local time zone in serializer
I have a Django Rest Framework Serializer: class LocalTZDateTimeField(serializers.DateTimeField): def __init__(self, *args, **kwargs): local_timezone = pytz.timezone(getattr(settings, 'LOCAL_TIMEZONE', None)) kwargs['default_timezone'] = local_timezone super(LocalTZDateTimeField, self).__init__(*args, **kwargs)**strong text** which displays dates like this: "create_dt": "2016-01-04T09:06:17.344952-05:00" # Eastern time, as desired I don't want to show the fractional seconds, so the docs suggest specify a datetime format, which I did: 'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S%Z%z", which mostly works, except now the dates are converted to UTC. "create_dt": "2016-01-04T14:06:17UTC+0000", I can't find anything that will allow me to show them in Eastern. (open to a better solution to supressing the fractional seconds, if I'm off the mark) -
Pull url from string
I have the string below I'm trying to pull the url out of out with python django. Thoughts on how I can get to it? I've tried treating it like a list but didn't have any luck. [(u'https://api.twilio.com/2010-04-01/Accounts/ACae738c5e6aaf12ffa887440a3143e55b/Messages/MM673cd77ab21b37ae435c1d1d5e767366/Media/ME33be4a0ae88358aaef2aa0ea25f31339', u'image/jpeg')] -
Django UpdateView with multiple models and multiple forms don't work
I am working with two different forms that loads info from two different models. One form is disabled to edit and the second form is enabled. Everything is right until I use UpdateView, when I try to make changes on the enable to edit form nothing happens. I am new in Django and found the code on a tutorial and adapted it to my project. Why UpdateView is not saving changes? models.py: class Sitioproyecto(models.Model): . . def __str__(self): return self.nombre_del_sitio class Sitiocontratado(models.Model): sitioproyecto = models.ForeignKey(Sitioproyecto, on_delete=models.CASCADE) . . def __str__(self): return self.sitioproyecto.nombre_del_sitio forms.py: class SitioContratadoForm(forms.ModelForm): class Meta: model = Sitiocontratado exclude = ['slug',] widgets = { 'fecha_de_contratacion' : forms.DateInput(attrs={ 'type' : 'date', 'class' : "form-control pull-right", 'id' : "fechadecon", }), 'sitioproyecto' : forms.Select(attrs={ 'type' : 'text', 'class' : "form-control", 'id' : 'nombresitio', }), . . } views.py: class CrearSitiosContratadosView(CreateView): model = Sitiocontratado template_name = 'sitios/contratados/editar_contratado.html' form_class = SitioContratadoForm success_url = reverse_lazy('pagina:tabla_contratados') class UpdateSitiosContratadosView(UpdateView): model = Sitiocontratado second_model = Sitioproyecto template_name = 'sitios/contratados/editar_contratado.html' form_class = SitioContratadoForm second_form_class = SitioProyectoForm success_url = reverse_lazy('pagina:tabla_contratados') def get_context_data(self, **kwargs): context = super(UpdateSitiosContratadosView, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) sitiocontratado = self.model.objects.get(id=pk) sitioproyecto = self.second_model.objects.get(id=sitiocontratado.sitioproyecto_id) if 'form' not in context: context['form'] = self.form_class() if 'form2' not in … -
How to serve static media with Daphne 2.0 on django
I'm new on daphne and I would like to know how to deploy a django app running on daphne, on ubuntu server. I already configured the app like the documentation said, and works fine, except that the static-files (js,css,imgs,etc) doesn't load. What I need to do? -
Can't get correct django form from template
please help to understand which one fomr model I should use on my case. I have the next form in HTML template : <div class="col-md-12"> <form id="developersform" action="#" method="post"> <select multiple="multiple" size="10" name="duallistbox_developers[]"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3" selected="selected">Option 3</option> <option value="option4">Option 4</option> <option value="option5">Option 5</option> <option value="option6" selected="selected">Option 6</option> <option value="option7">Option 7</option> <option value="option8">Option 8</option> <option value="option9">Option 9</option> <option value="option0">Option 10</option> </select> <button type="submit" class="btn btn-default btn-block">Submit data</button> </form> </div> It's looks like View is not working due form issue: if request.user.is_authenticated: if request.method == 'POST': form = ManagmentUsersForm(request.POST) if form.is_valid(): picked = form.cleaned_data.get('duallistbox_guests') print(picked) else: form = ManagmentUsersForm() print(form.errors) How I should specify form on Django? Could someone help with example Thanks -
django migrating from sqlite3 to oracle causes ora-2000 error
I hava a Django app on a windows server 2012 which was set up with sqlite3 as the db, but it's going to production so I'm migrating the tables to oracle 12c on the server, i don't care about the data just the tables so when I run python manage.py migrate I get ORA-2000 Error: missing ALWAYS keyword I'm new to django and websites in general, what am i missing? -
can't connect django 1.10 to mysql 5.7, mysqlclient installed but still get ImportError: No module named 'MySQLdb'
I created a virtual environment with python 3.5 then used pip to install mysqlclient. When I activate the venv and go into the python shell I can type import MySQLdb and then proceed to query my db without any trouble. However, in django 1.10.5 when I use this virtual environment I get ImportError: No module named 'MySQLdb' as soon as I start the local/dev server. For what it's worth, I also tried this process outside of a virtual environment but no success. I'm on windows and Pycharm and created the venv in CMD with administrator privileges. I know there are similar questions on SO but nothing is on point here. Thanks for whatever help you can give! My settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db_name', 'USER': 'my_user_name', 'PASSWORD': 'my_password', 'HOST': '127.0.0.1', 'PORT': '3306' } } -
Using Django to create sessions and buttons connecting Products to a shopping cart through templates and views.py
Sorry for the length (Thought the info was relevant), and thank you for helping understand how this works. I'm trying to use sessions and Django templates to add items to shopping cart. I'm fairly new to learning Django and have painstakingly read through a bunch of documentation and Stack Overflow problems that were similar. My data is saved to MySQL database(subject to change) like this: sql_entry = { 'model': 'App.Product', 'pk': 1, # unique for each item 'fields': { 'Name': 'name', 'Price': 1.0, 'Quantity': 1 } and my Model: class Product(models.Model): Name = models.CharField(max_length=200, default='') Price = models.FloatField() Quantity = models.IntegerField() def __str__(self): return self.Name class Meta: ordering = ['Name'] Because the actual products will change daily, I want to avoid hardcoding categories, and thought it would be better to only have data pertaining to what products are available. So I use Django's template to create a basic table view of each product with a button that would add it to the cart. I want to avoid any type of login for now. I read that sessions was the best way for unique customers to add items to the cart and save there data to my database. I believe my …