Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ManyToMany Creating Duplicate Relationship for Self Referential Attribute
I've got a model that looks something like this: class Session(models.Model): sub_sessions = models.ManyToManyField("self") Now when I do something like: session_1 = Session.objecte.get(id=1) session_2 = Session.objects.get(id=2) session_1.sub_sessions.add(session_2) What happens is that a relationship is created such that session_2 is in session_1's sub_sessions field, but session_1 is also in session_2's sub_sessions field. I imagine this makes sense at some level being a ManyToManyField relationship, but it's really not what I want. I only want session_2 to be in session_1's sub_sessions field, but not the other way around. I suppose I can instead create a ForeignKey relationship, but it'll just break a few of my current coding implementations and I'd really love to have some sort of a way to make this work. Thanks! -
Django export mutiple model in one csv
Guys i want to know if with django you can export multiple models in one csv files and how! i use django import-export now but i don't find a method for want a i want. Thanks! how export in one csv this 2 related models: class Planteur(models.Model): pacage = models.CharField("Numéro pacage", max_length=9, primary_key=True, help_text="Un nombre de 9 chiffres") civilite = models.CharField( "Civilité", max_length=20, choices=CIVILITE_CHOICE, default='', blank=True) nom = models.CharField("Nom", max_length=200, help_text="200 caractères maximum.") prenom = models.CharField("Prénom", max_length=100, help_text="200 caractères maximum.") siret = models.CharField("SIRET", max_length=14, blank=True, help_text = "code Insee permettant l'identification d'un établissement ou d'une entreprise française.", null=True) LPG = models.CharField("Numéro LPG", max_length=100, blank=True, help_text = "Identifiant LPG du planteur.", null=True) contre_marque = models.CharField("Contremarque", max_length=100, blank=True, null=True) denomination = models.TextField("Dénomination", help_text = "Texte d'aide", null=True, max_length=100, blank=True) gerant = models.TextField("Gérant", help_text = "Texte d'aide", null=True, blank=True) adresse = models.CharField("Adresse", help_text = "Adresse du planteur", max_length=255, null=True, blank=True) adresse_complementaire = models.CharField(max_length=255, null=True, blank=True) code_postal = models.CharField("Code postal", help_text="Code postal planteur", null=True, max_length=10, blank=True) commune = models.CharField("Commune", max_length=100, help_text = "Commune du planteur", blank=True, null=True) telephone_principale = models.CharField("Numéro de téléphone", null=True, help_text='Téléphone de contact', max_length=50, blank=True) telephone_secondaire = models.CharField("Autre téléphone", help_text='téléphone de contact', max_length=50, null=True, blank=True) courriel = models.EmailField("Courriel", help_text = "Adresse … -
Django-postman not working
I tried to implement Django-postman for the user to user messaging system. I cloned the repo and did this in my settings.py and URLs.py file too: In URLs.py of main file i have included : re_path(r'^messages/', include('postman.urls', namespace='postman')), In Settings.py file I have included: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'postman', 'account', 'landingpage', ] POSTMAN_I18N_URLS = True # default is False POSTMAN_DISALLOW_ANONYMOUS = True # default is False POSTMAN_DISALLOW_MULTIRECIPIENTS = True # default is False POSTMAN_DISALLOW_COPIES_ON_REPLY = True # default is False POSTMAN_DISABLE_USER_EMAILING = True # default is False POSTMAN_FROM_EMAIL = 'from@host.tld' # default is DEFAULT_FROM_EMAIL #POSTMAN_PARAMS_EMAIL = get_params_email # default is None POSTMAN_AUTO_MODERATE_AS = True # default is None POSTMAN_SHOW_USER_AS = 'get_full_name' # default is None POSTMAN_NAME_USER_AS = 'last_name' # default is None POSTMAN_QUICKREPLY_QUOTE_BODY = True # default is False POSTMAN_NOTIFIER_APP = None # default is 'notification' POSTMAN_MAILER_APP = None # default is 'mailer' URLs of postman: urlpatterns = [ # Translators: keep consistency of the <option> parameter with the translation for 'm' url(pgettext_lazy('postman_url', r'^inbox/(?:(?P<option>m)/)?$'), InboxView.as_view(), name='inbox'), # Translators: keep consistency of the <option> parameter with the translation for 'm' url(pgettext_lazy('postman_url', r'^sent/(?:(?P<option>m)/)?$'), SentView.as_view(), name='sent'), # Translators: keep consistency of the <option> parameter with the translation for … -
How To use multiple url with the same template file in django.?
URLS.PY url(r'^shop.html$', views.alldress, name='alldress'), url(r'^shop.html$', views.cart ,name='cart'), url(r'^shop.html$', views.cartdata, name='cartdata'), I want to use three process with the same time so How To use multiple url with the same template file in django.? -
How to combine two views in django?
I want to insert another view into a view. Basically I'm using Django filter package and value output directly populates template without my need to writing any view class. I want to insert another html into the current template. Something like this: {% include 'countsnippet' %}, but this gives me error template doesn't exists. Alternatively I've tried using {% include 'countsnippet.html' %} but this doesn't calls the views and fields remains empty. What approach I can use to include another view? This is my countsnippet html. {% block content %} <p> INFT : {{ inft }} </p> {% endblock %} I've already made view for countsnippet and its url looks like this: url(r'countsnippet/$', countsnippet, name='countsnippet') I've though about quite a number of times and I feel It would be really interesting to find out how to combine multiple pages into one and make something complex. Although I wasn't ever able to figure out any solution for that. -
Increase the prod_price during querying process
I have such a table of product with fields of prod_id, prod_name, prod_price... MySQL [distributor]> select * from products; +---------+---------+---------------------+------------+-----------------------------------------------------------------------+ | prod_id | vend_id | prod_name | prod_price | prod_desc | +---------+---------+---------------------+------------+-----------------------------------------------------------------------+ | BNBG01 | DLL01 | Fish bean bag toy | 3.49 | Fish bean bag toy, complete with bean bag worms with which to feed it | | BNBG02 | DLL01 | Bird bean bag toy | 3.49 | Bird bean bag toy, eggs are not included | | BNBG03 | DLL01 | Rabbit bean bag toy | 3.49 | Rabbit bean bag toy, comes with bean bag carrots | | BR01 | BRS01 | 8 inch teddy bear | 5.99 | 8 inch teddy bear, comes with cap and jacket | | BR02 | BRS01 | 12 inch teddy bear | 8.99 | 12 inch teddy bear, comes with cap and jacket | | BR03 | BRS01 | 18 inch teddy bear | 11.99 | 18 inch teddy bear, comes with cap and jacket | | RGAN01 | DLL01 | Raggedy Ann | 4.99 | 18 inch Raggedy Ann doll | | RYL01 | FNG01 | King doll | 9.49 | 12 inch king doll with royal … -
ModuleNotFoundError: No module named '*.apps'
I can`t run my django project on PythonAnywhere, because I have a problem with WSGI. I attach files with which there are problems. Does anyone know the solution to this problem? Error log: 2018-08-14 12:50:34,868: Error running WSGI application 2018-08-14 12:50:34,868: ModuleNotFoundError: No module named 'test.apps' 2018-08-14 12:50:34,868: File "/var/www/medhub_pythonanywhere_com_wsgi.py", line 11, in <module> 2018-08-14 12:50:34,869: application = DjangoWhiteNoise(get_wsgi_application()) 2018-08-14 12:50:34,869: 2018-08-14 12:50:34,869: File "/home/medhub/MedHub/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2018-08-14 12:50:34,869: django.setup(set_prefix=False) 2018-08-14 12:50:34,869: 2018-08-14 12:50:34,869: File "/home/medhub/MedHub/venv/lib/python3.6/site-packages/django/__init__.py", line 27, in setup 2018-08-14 12:50:34,869: apps.populate(settings.INSTALLED_APPS) 2018-08-14 12:50:34,869: 2018-08-14 12:50:34,869: File "/home/medhub/MedHub/venv/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate 2018-08-14 12:50:34,869: app_config = AppConfig.create(entry) 2018-08-14 12:50:34,869: 2018-08-14 12:50:34,869: File "/home/medhub/MedHub/venv/lib/python3.6/site-packages/django/apps/config.py", line 116, in create 2018-08-14 12:50:34,870: mod = import_module(mod_path) Django version: 1.10.8 WhiteNoise version: 3.0 settings.py path: /home/medhub/MedHub/MedHub/settings.py settings.py file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/') MEDIA_URL = 'static/media/' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '123' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
Django ForeignKey to choose from several models objects
I need to make choise field of object from several models. Is i readed in this question, i tryed to use genericForeignKeys. But unfortuanally thats not what i need. Right now i have this admin interface: But i want to make it simple choicefield like: On last pic its foreignkey with one model, i want to make choise from three, in the same format, is it possible somehow? Models have the same structure. Right now i have: Models.py from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation from django.contrib.contenttypes import fields from django.db import models # Create your models here. class Index(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='Projects') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Advertising(models.Model): year = models.CharField(max_length=50, blank=True, verbose_name='Год') payer = models.CharField(max_length=50, blank=True, verbose_name='Заказчик') name = models.CharField(max_length=50, blank=True, verbose_name='Название проекта') image = models.ImageField(upload_to='media/Advertising/', blank=True, verbose_name='Превью картинка') vimeo_link = models.CharField(max_length=100, blank=True, verbose_name='Ссылка Вимео') video_name = models.CharField(max_length=50, blank=True, verbose_name='Название видео') left_desc = models.TextField(max_length=500, blank=True, verbose_name='Описание (левая колонка)') right_desc = models.TextField(max_length=500, blank=True, verbose_name='Описание (правая колонка)') backstage_video = models.CharField(max_length=100, blank=True, verbose_name='Видео backstage') fkey = fields.GenericRelation(Index) class Meta: verbose_name = 'Реклама' verbose_name_plural = 'Реклама' def __str__(self): return self.name class Films(models.Model): year = models.CharField(max_length=50, blank=True, verbose_name='Год') payer = models.CharField(max_length=50, blank=True, verbose_name='Заказчик') … -
Getting a count per hour for the past week
I have a model of Photos taken. I am building a heatmap with Javascript of when photos were taken of the last7 days. I am showing it per hour. My Photo Model has a timestamp DateTime field. How would I make a list like this showing total photos per hour per day for the past week? The javascript expects an array like this: const heatmapDataSource = [ [0, 0, 3], [6, 23, 3], .... ]; heatmapDataSource[0][0] is the day of the week (Today (Tuesday) 0, last week Wednesday (6) - Today is always 0 heatmapDataSource[0][1] is hour (0 == 24:00 and 23 == 23:00 etc) heatmapDataSource[0][2] is the count value for that hour Hope this makes sense! -
Django view: get the count of rows in all tables in a MySQL database
I can get the count of rows in all tables in a MySQL database with this sql query: SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '<database>'; Is there a way to get the same with the model query API in a django view? One way would probably be using the raw() manager method, but I wonder if there is a more elegant solution. -
Does Django have multi-level authorization?
For an instance, if a form is submitted to the database. The higher level authorized user shouldn't see it until the lower level user accepts to do so. And is this possible by using "Groups" in the /admin site? -
Update method on viewset
When I'm trying to update instance with not unique data I'm getting an 500 error. Viewset is using UpdateModelMixin which has the following code in it's update method: serializer = self.get_serializer(instance, data=request.data, partial=partial) I've tried to remove instance param and I started to get an 400 error which was expected, but in this case it will be impossible to figure out which instance should be updated. How can I prevent an 500 error? -
Wagtail page context in Streamfield template
I have StructBlock with it's own template, within a StreamField. I'm trying to access the page object from said template. {% load wagtailcore_tags article_tags %} {% article_constants as constants %} <div id="interactions__combo__addition" class="col-md-6"> <h3> {% include_block page.translated_title %} + <span id="interactions-combo-addition-temp">?</span> = </h3> <div alt="dangerous to synergy bar" style="height:10px; width:100%"> </div> </div> <div class="interactions__combo__result col-md-5"> <h3 class="interactions__combo__result__title"> {{ constants.select_element }} </h3> <p class="interactions__combo__result__description"> {{ constants.none_selected_text }} {% include_block page.colour %}. </p> </div> {% include_block page.colour %} and {% include_block page.translated_title %} render nothing. Thank you in advance for your help. -
Django QuerySet Limit hits database too many times?
I've recently stumbled upon a massive bottleneck on a production website only after updating from Django 1.11 > 2.1 Here is my simple slice of code; pages = Page.objects.filter(cat="news_item").order_by('-created')[:2] This in turn, creates around ~30 queries, around the number of pages under that specific filter. I have now implemented a somewhat hacky way to resolve the 32 queries which i'm not satisfied with. pages = [Page.objects.filter(cat='news_item').order_by('-created')[i] for i in range(0,2)] Speed is notably effected, a few other chunks of code used this method which caused >400 queries per page load - I have since adapted these to use a combination of the above code & Model.objects.raw Did something change in Django 2.0/2.1 that I missed or does the [:2] limit not work correctly? -
django and atom editor
I wanted to have live server with django in atom editor. Is it possible? If it is I'd appreciate if you tell me how? By the way I installed atom-live-server package but it was not helpful! I mean I couldn't load my website with live server. -
make: *** [port-target] Error 2 When trying to install GDAL for GeoDjango using Ubuntu 18.04
I am trying to install GeoDjango to use in my project I am using Ubuntu 18.04 through VirtualBox I am using the GeoDjango installlation Guide to install Gdal. I have GEOS and PROJ.4 installled I have successfully run the below commands $ wget http://download.osgeo.org/gdal/1.11.2/gdal-1.11.2.tar.gz #success $ tar xzf gdal-1.11.2.tar.gz #success $ cd gdal-1.11.2 #success Later I am supposed to do the below according to the documentation $ ./configure $ make # Go get some coffee, this takes a while. $ sudo make install $ cd .. However $ ./configure #success $ make # Go get some coffee, this takes a while. #ERROR SEE BELOW I get the below error when I run the above code samir@samir-VirtualBox:~/gdal-1.11.2$ make # Go get some coffee, this takes a while. (cd port; make) make[1]: Entering directory '/home/samir/gdal-1.11.2/port' /bin/bash /home/samir/gdal-1.11.2/libtool --mode=compile --tag=CXX g++ -std=c++98 -g -O2 -DHAVE_SSE_AT_COMPILE_TIME -Wall -DOGR_ENABLED -I/home/samir/gdal-1.11.2/port -I../frmts/zlib -DHAVE_LIBZ -c -o cpl_error.lo cpl_error.cpp libtool: compile: g++ -std=c++98 -g -O2 -DHAVE_SSE_AT_COMPILE_TIME -Wall -DOGR_ENABLED -I/home/samir/gdal-1.11.2/port -I../frmts/zlib -DHAVE_LIBZ -c cpl_error.cpp -fPIC -DPIC -o .libs/cpl_error.o cpl_error.cpp: In function 'void CPLErrorV(CPLErr, int, const char*, __va_list_tag*)': cpl_error.cpp:190:20: error: incompatible types in assignment of '__va_list_tag*' to 'va_list {aka __va_list_tag [1]}' wrk_args = args; ^~~~ cpl_error.cpp:226:24: error: incompatible types in … -
Converting from a Model Type to string in python django
Following is a snapshot of one of my models in django application: class Device(models.Model): device_type = models.ForeignKey(DeviceType,to_field='device_type') serial_number = models.CharField(max_length=200,unique=True) in_use_by = models.ForeignKey(User,to_field='username') brand = models.CharField(max_length=200,default="-", null=False) model = models.CharField(max_length=200,default="-", null=False) type_number = models.CharField(max_length=200,blank=True,null=True, default = None) mac_address = models.CharField(max_length=200,blank=True,null=True, default = None) invoice = models.FileField(upload_to='router_specifications', null=True) Now, I have a function in my views.py that validates the data that is submitted through the django rendered form. Now, I have a situation, I want to print the data sent through the form by concatinating it with a particular string. Whenever I got to do so. I get the following error: TypeError: coercing to Unicode: need string or buffer, DeviceType found How should I overcome this problem? -
Django: Create a CSV file to test an upload endpoint and remove it after finishing the test
I'm writing a test case for a /upload endpoint using Django. For that, I created a method that creates a csv file with my given dataset. When I run the testcase, sometimes the test database failed to remove. How to overcome this problem? Here is my test code: import csv import os from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient def create_csv(data): with open('some.csv', 'w') as map_file: writer = csv.writer(map_file) writer.writerows(data) map_file.close() class CSVUploadTest(TestCase): def setUp(self): self._map_data = [ [3, "05, Banagram Road, Hatkhola, Ray Shaheb Bazar, 1203", 23.72054135, 90.4141324, "Ghulsan 1"], [1, "#04, Dhaka-Chittagong Highway, Hatkhola, Lakshmi Bazar, 1203", 23.7210324, 90.4174495033668, "Ghulsan 2"], [2, "04, Road 4, Mirpur 10, 1216", 23.8093795, 90.3731244], ] create_csv(self._map_data) self._csv_filename = "some.csv" self._client = APIClient() def test_location_csv_upload(self): url = reverse('upload') csv_file = open(self._csv_filename, "r") resp = self._client.post(url, {"file": csv_file}) csv_file.close() os.remove("bangladesh.csv") self.assertEqual(resp.status_code, 200) Here is the error I get: django.db.utils.OperationalError: database "test_postgres" is being accessed by other users DETAIL: There is 1 other session using the database. -
After upgrading to Adwords 13.0 I am facing the following some issue in my application.
After upgrading to Adwords 13.0 I am facing the following problem in my application. [error] self._db_path, detect_types=sqlite3.PARSE _DECLTYPES) [error] OperationalError: unable to open database file It appears that the system is not able to open the cache file. I have tried changing the file access and owner permissions and still no change. Kindly help. -
set password automatically in shell script to restart apache2
I am integrating django project with jenkins. successfully integrated it through shell script on remote host using ssh. but i cant restart apache2 because it require to enter password. how to automatically input password on shell script? -
How can I customize url output?
I'm building a site using Django for equipment management. I am currently using this tutorial to help me get started. I would like for the url displaying in the url bar in a browser to show something such as: 127.0.0.1:8000/catalog/model/model_number But at the moment it just shows a single integer like 1, 2, 3, etc. when I click on each individual model. Here is my urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('models/', views.ModelListView.as_view(), name='models'), path('model/<int:pk>', views.ModelDetailView.as_view(), name='model-detail'), ] I know that path('model/<int:pk>'... is the part that should be changed. I've tried path('model/model.model_number>'... but this outputs the below error: Reverse for 'model-detail' with arguments '('2',)' not found. 1 pattern(s) tried: ['catalog\\/model\\/\\<model\\.model_number\\>$'] Here is my models.py: from django.db import models from django.urls import reverse #Used to generate URLs by reversing the URL patterns import uuid import datetime # Create your models here. class Genre(models.Model): """Model representing book genre""" name = models.CharField(max_length = 200, help_text = 'Enter book genre') def __str__(self): """String for represnting model object.""" return self.name class Book(models.Model): """Model representing a book (but not a specific copy of a book)""" title = models.CharField(max_length = 200) author … -
Django - Where should I place calculation method to design a proper and maintainable project?
I have some classes like these; class RawMaterial(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) raw_materials = models.ManyToManyField(RawMaterial, through='MaterialProduct', related_name='products') class MaterialProduct(models.Model): raw_material = models.ForeignKey(RawMaterial, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) material_price = models.FloatField() material_rate = models.FloatField() I want to write a method which name is calculate_total_price, to design a proper/beautiful/maintainable project, where should I write my method? To models.py or views.py ? Thanks in advance. -
pip install myclient error - on Windows 7 using Python 3.7.0
I'm currently working through a Django tutorial and after trying to install mysqlclient I have had the following error message on my CMD. Many thanks in advance Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command c:\users\o\envs\py1\scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\O\\AppData\\Local\\T emp\\pip-install-kej8gk5_\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', op en)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, _ _file__, 'exec'))" install --record C:\Users\O\AppData\Local\Temp\pip-reco rd-_27hw8hl\install-record.txt --single-version-externally-managed -- compile --install-headers c:\users\o\envs\py1\include\site\python3.7\mysqlclient: running install running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32- 3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32- 3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32- 3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32 3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building '_mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools -
Django ecommerce: Adding Products with one to many relationship to Services into a Cart
I am trying to allow customers the chance to add products & services to a cart at the same time. Customers will add Products and then add a few Services related to each Product before checking out. It will be better if customers could add a few products in the cart at the same time. For example, a customer purchases flight tickets (Product) for a few routes and adds to that flight ticket a few other Services related to each route such as meal types, baggage allowance, etc. My question would be is it possible to use the following views.py code: views.py from cart.cart import Cart from shop.models import Product def add_to_cart(request, product_id, quantity): product = Product.objects.get(id=product_id) cart = Cart(request) cart.add(product, product.unit_price, quantity) def remove_from_cart(request, product_id): product = Product.objects.get(id=product_id) cart = Cart(request) cart.remove(product) def get_cart(request): return render_to_response('cart.html', dict(cart=Cart(request))) and modify it to work something like this: from cart.cart import Cart from shop.models import Product, Service def add_to_cart(request, product_id, quantity, service_id): product = Product.objects.get(id=product_id) service = Service.objects.get(id=service_id) cart = Cart(request) cart.add(product, product.unit_price, quantity, service, service.unit_price) I am a beginner and am unsure how to go about solving this problem of adding products with one to many relationship to services to a … -
User Profile additional fields django
I am trying to register users with UserCreationForm fields ( username , password, password ) and I would like additional input fields on the register form such as location and gender. With the below code, on the register page its giving me a select id drop down of all user and location and gender input fields. Is there any way I can get all the fields on the same page.( username , password, password2 , location, gender ) models..py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) location = models.CharField(max_length=140) gender = models.CharField(max_length=140) def __str__(self): return 'Profile of user: {}'.format(self.user.username) view.py class register_user(CreateView): model = UserProfile template_name = 'Mel/register.html' success_url = 'list' fields = '__all__'