Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
showing shopping cart items for django?
i use python 3.7 and django 2.2.3 i'm creating ac shopping cart system for my website and i can't see my cart items in it. i use product.id in URL's Patterns, but it seems it not working. this is my website shopping cart and i want after clicking a add to cart button , it add to the cart and show me cart page. i tried this by using product.id in url pattens and update_cart() view in views.py. i use "url 'update_cart' product.id" for clicking 'ADD TO CART' in product page. i use "{% for item in cart.products_list.all %}" for showing cart items in cart page. views.py def cart_view(request): cart=Cart.objects.all()[0] return render(request,'products/cart.html',{'cart':cart}) def update_cart(request,product_id): cart=Cart.objects.all()[0] try: product=Products.objects.get(id=product_id) except Products.DoesNotExist: pass if not product in cart.products_list.all(): cart.products_list.add(product) else: cart.products_list.remove(product) return HttpResponseRedirect("cart") urls.py from django.urls import path,include from . import views urlpatterns = [ path('create/',views.create,name='create'), path('<int:product_id>/',views.detail,name='detail'), path('cart',views.cart_view,name='cart'), path('<int:product_id>/',views.update_cart,name='update_cart'),] models.py : class Cart(models.Model): products_list=models.ManyToManyField(Products,null=True,blank=True) total=models.IntegerField(default=0) date=models.DateTimeField(auto_now_add=False,auto_now=True) isPaid=models.BooleanField(default=False) def count_cart_items(self): return int(self.cart_items) class Products(models.Model): category_id=models.ForeignKey(Products_Cat,on_delete=models.CASCADE) creator=models.ForeignKey(User, on_delete=models.CASCADE) title=models.CharField(max_length=250) price=models.IntegerField(default=0) description=models.TextField() slug=models.SlugField() image=models.ImageField(upload_to='images/') isOff=models.BooleanField(default=False) i want to see my cart works correctly and showing me the cart but i see no result with no error. Can Anyone Help ? -
Django - schema_editor in migration error - Apply conditional migrations
I am trying to figure out how to use schema_migration inside Django Migrations. The main reason, is to apply a conditional migration, check if the field minimal_variant_price_amounte exists, if no, apply the migration. from django.db import migrations from django.core.exceptions import FieldDoesNotExist def populate_product_minimal_variant_amount_field_check(apps, schema_editor): Product = apps.get_model("product", "Product") try: Product._meta.get_field('minimal_variant_price_amounte') except FieldDoesNotExist: print(schema_editor) schema_editor.alter_field( Product, 'minimal_variant_price', 'minimal_variant_price_amount') print(' field change: minimal_variant_price => minimal_variant_price_amount') class Migration(migrations.Migration): dependencies = [ ('product', '0106_django_prices_2'), ] operations = [ migrations.RunPython( populate_product_minimal_variant_amount_field_check, reverse_code=migrations.RunPython.noop, ) ] -
SECRET_KEY set up with bash_profile and DJANGO 2.1 no longer working
I am not sure why but two days ago, I set up my SECRET_KEY in nano .bash_profile correctly and it was working. Today I try to launch the web application, still in development and the terminal return: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. bash configguration is export INVOICEPLUS_SECRET_KEY="xxxxDJANGOKEYxxx" (only made of numbers and letters) settings.py 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__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('INVOICEPLUS_SECRET_KEY') Does anybody know what is wrong here because i am lost. full traceback below: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/macadmin/Documents/Django_wapps/invoiceplus/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/macadmin/Documents/Django_wapps/invoiceplus/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/macadmin/Documents/Django_wapps/invoiceplus/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/macadmin/Documents/Django_wapps/invoiceplus/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Users/macadmin/Documents/Django_wapps/invoiceplus/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/macadmin/Documents/Django_wapps/invoiceplus/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Users/macadmin/Documents/Django_wapps/invoiceplus/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/Users/macadmin/Documents/Django_wapps/invoiceplus/lib/python3.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/Users/macadmin/Documents/Django_wapps/invoiceplus/lib/python3.7/site-packages/django/conf/__init__.py", line 126, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not … -
Weird ephemeral error for ManyToMany fields during Django migrations
There's this weird error that my company has been facing since the last few months. We have a ton of models in our code and a lot of them have ManyToMany fields in them. For ex - class TypeMapping(models.Model): name = models.TextField(null=True, blank=True) from_config_type = models.ManyToManyField(Type, blank=True, related_name="from_config_type") to_config_type = models.ManyToManyField(Type, blank=True, related_name="to_config_type") Sometimes, and only sometimes, after a deployment, we start getting errors like these Error :- Cannot resolve keyword 'to_config_type' into field. Choices are: <a long list of choices which does include 'to_config_type'. We use AWS and this error only crops up sometimes, and that too, only on one server instance we have. I know that related_name and field_name should not be the same, but that's for abstract base classes. The above model isn't one. I've racked my head at this and so have my teammates but we couldn't land on anything. Can anyone help us on this? Thanks! -
Get data of table between 2 dates django python
I have a table in model like this class ReviewMonthly(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='ReviewMonthly') timestamp = models.DateTimeField(auto_now_add=True) value = models.FloatField() i want to get data of value between two dates like I have saved data and the other is I am getting like datetime.datetime.now() -
Django. Rest framework. Add attribute to tag
I want to add an additional attribute to the tags offer. Will explain! There are views.py. In it, I redefined the standard REST framework tags. # views.py class KvXMLRenderer(XMLRenderer): root_tag_name = 'feed' item_tag_name = 'offer' def _to_xml(self, xml, data): super()._to_xml(xml, data) Now the structure of my XML looks like this: <feed> <offer> <offer-data></offer-data> </offer> <offer> <offer-data></offer-data> </offer> <offer> <offer-data></offer-data> </offer> </feed> I need to add to the offer, attribute internal-id=kv<object_id>. To make my xml look like this: <feed> <offer internal-id="kv1"> <offer-data></offer-data> </offer> <offer internal-id="kv2"> <offer-data></offer-data> </offer> <offer internal-id="kv3"> <offer-data></offer-data> </offer> </feed> Help advice! Thank! -
How to manually create a correct primary key for models of a database
My problem is somewhat similar to what is discussed here: Django automatically create primary keys for existing database tables But instead of simple python manage.py inspectdb I did python manage.py inspectdb --include-views. And my problem is with those classes based on views- I get Error 1054, ("Unknown column 'station_measurements_with_data.id' in 'field list'") I've tried to simply add id = models.IntegerField(primary_key=True) to the model, but no joy. The model class looks like this: class StationMeasurementsWithData(models.Model): station_id = models.IntegerField() measurement_id = models.IntegerField() time_utc = models.DateTimeField() pollution_name = models.CharField(max_length=45) measurement_value = models.FloatField(blank=True, null=True) class Meta: managed = False # Created from a view. Don't remove. db_table = 'station_measurements_with_data' And the view data int the database looks like this: # station_id, measurement_id, time_utc, pollution_name, measurement_value 955, 87318, 2012-01-01 02:00:00, pm2.5, 73 955, 87318, 2012-01-01 02:00:00, pm10, 308 956, 87319, 2012-01-01 02:00:00, pm2.5, 123 956, 87319, 2012-01-01 02:00:00, pm10, 152 957, 87320, 2012-01-01 02:00:00, pm2.5, 163 957, 87320, 2012-01-01 02:00:00, pm10, 198 If any column contained unique values I would just make it a primary key, but there isn't one. What should I do in this case? -
Django Rest Framework check_object_permissions not being called
I am trying to make sure the user has permission to view the object they are calling. Here is my permissions class: from rest_framework import permissions class IsOwner(permissions.BasePermission): """ Custom permission to only allow owners of an object to do actions. """ message = 'You must be the owner of this object.' def has_object_permission(self, request, view, obj): print("CHECK THAT I GOT HERE") return obj.user == request.user And here is my ViewSet: class TopLevelJobViewSet(ModelViewSet): permission_classes = (IsOwner,) serializer_class = TopLevelJobSerializer queryset = TopLevelJob.objects.all() filter_backends = [DjangoFilterBackend, RelatedOrderingFilter] filter_class = TopLevelJobFilter ordering_fields = '__all__' Thehas_object_permissions is not being called, anyone visiting the endpoint is able to access all the objects. Why is this? How do I get has_object_permissions to get called? -
Python Error: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3
I'm trying to run a Django application, which requires a MySql database, I have MySql installed and it works fine with other languages. I'm using a virtual environment to run the Django project, But I'm facing issues with setting up the MySql configuration with the following python libraries - pymysql and mysqlclient There seems to be a version mismatch, Following is the full error - (env) Aniruddhas-MacBook-Pro:djangocrashcourse-master aniruddhanarendraraje$ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked … -
Need to work with raster data and .netcdf files and need to integrate it with django
Creating a website using django. Need to work with raster data and netcdf files.F or that I need gdal library. Is it possible to use gdal with django. Is there any other way to do that? -
How to run the collectstatic script after deployment to amazon elastic beanstalk?
I have a django app that is deployed on aws elastic beanstalk when I want to deploy I need to run the migrate, and the collectstatic script. I have created 01_build.config in .ebextensions directory and this is its content commands: migrate: command: "python manage.py migrate" ignoreErrors: true collectstatic: command: "python manage.py collectstatic --no-input" ignoreErrors: true but still, it is not running these scripts. -
How to do an if statement in a Django template to find if a decimal value is 0
Basically, I want to find out if a decimal field value is 0.00. Then, I want to output a different value in the template. See code below. The code does not work. variable = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) #template {% for item in table %} {% if item.variable is 0.00 %} <li><strong>Total: </strong> Unknown </li> {% else %} <li><strong>Total:</strong> ${{ item.variable }}</li> {% endif %} {% endfor %} This does not work. It outputs: Total: $0.00. -
In a Django template, how do I print the value in a dictionary when the key is stored in a variable?
I'm using Django and Python 3.7. In my template, I can see the output of this {{ articlestat.article.website.id }} which is "4". I have a dictionary, passed to my context, whose keys are numbers. If I do the following {{ website_stats.4 }} I see a value printed. However if I do this {{ website_stats[articlestat.article.website.id] }} I get the error Could not parse the remainder: '[articlestat.article.website.id]' from 'website_stats[articlestat.article.website.id]' So my question is, how do I access the value of a dictionary on my template when the key is stored in a variable? I'm not in a position to hard-code the keys. -
Django - This HTTPS site requires a Referer header
I'm using Typeform to send a POST request to a Webhook on my server. I'm looking at the sample request they give and it doesn't look like they are including a Referer header, so my Django site is blocking their request. Is there a way to whitelist their domain so that they can keep sending this without the referer? I know I could use csrf_exempt but that would not be ideal. I have the domain both in CSRF_TRUSTED_ORIGINS and CORS_ORIGIN_WHITELIST. -
Long title crashes django site error500
I have setup a django website on digital ocean with gunicorn and nginx. All works great, but when a user types a long title on a post, and then submits the form, the whole site crashes with an error 500. The admin site is still accessible and i can delete that post and then the site works again. It looks like the slug cannot be created and saved with the post with a title too big because the slug itself becomes too big and this causes an error and makes any part of my page that refers to that post crash when accessed. This is my models for title and slug title = models.CharField(max_length=120, unique=True) slug = models.SlugField(unique=True, default='', editable=True) I do still want to have a limit of 120 characters but how do i enforce it without making the site crash? Can i either make a form that stops the user from writing a long title or do i cut a title that is too long before saving the post and creating the slug? -
Bootstrap Navbar seems to Crop Background Image
I'm dipping my toes into the world of web development with Django, and Stackoverflow has been really helpful (as always). However, I'm running across something the forums haven't seemed to address before... I have a background image that I've put in my static folder and called it in my homepage html template file (see code below). I've also incorporated bootstrap in my base.html file, which includes a navbar which directs to various apps on my website (again, see code below). homepage.html: {% extends "base.html" %} {% load static %} {% block page_content %} <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body, html { height: 100%; margin: 0; } .bg { /* The image used */ background-image: url({% static "mountains2.jpg" %}); /* Full height */ height: 100%; /* Center and scale the image nicely */ background-position: center; background-repeat: no-repeat; background-size: cover; } </style> </head> <body> <div class="bg"></div> </body> </html> {% endblock %} base.html <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand" href="{% url 'homepage' %}">Home</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'about' %}">About</a> </li> <li class="nav-item"> <a … -
How do I access the value of a dictionary in my context in my Django template?
I'm using DJango and Python 3.7. I want to access the value of a dictionary that I add to my context website_stats = dict() .... context = { ... 'website_stats': website_stats, } return render(request, 'articlesum/trending.html', context) in my template. I tried like this {{ website_stats[articlestat.article.website][articlestat.elapsed_time_in_seconds] }} but I'm getting the error Could not parse the remainder: '[articlestat.article.website][articlestat.elapsed_time_in_seconds]' from 'website_stats[articlestat.article.website][articlestat.elapsed_time_in_seconds]' -
How to send object from detail view to another view in Django?
I have a detail view that uses a Quiz object to display data stored in that object, like title and author. I want to have a button that links to a new page that displays different data from the same object. I don't know how to pass this data/object. I can render the view and pass it the context of a specific quiz using an id but I want the id to change to be the id of the object from the initial page. #assessement view def assessment(request): context = { 'quiz':Quiz.objects.get(id=1), } return render(request, 'quiz_app/assessment.html', context) #detailview template for quiz {% extends "quiz_app/base.html" %} {% block content %} <article class="quiz-detail"> <h1>{{ object.title }}</h1> <h2>{{ object.question_amount }} Questions</h2> <a class="btn" href="{% url 'quiz-assessment' %}">Start Quiz</a> </article> {% endblock content %} #assessment template {% extends "quiz_app/base.html" %} {% block content %} <h2>Assessment</h2> <h2>Title is {{ quiz.title }}</h2> {% endblock content %} -
Unable to get Images from AWS-S3 bucket in django-app?
I'm using AWS-S3 to store my users' profile images. I've repeated this process 7-8 times but when I open my app on local machine(I've not deployed it yet) the user profile images aren't there and it shows the alt='not found' in place of images. I've made a user in IAM and a bucket in S3 same as in this tutorial nearly 5 times but there's no way I'm getting the images. Also when I right click on any image in my app and go into the image location I'm getting this in my browser. This XML file does not appear to have any style information associated with it. The document tree is shown below. AccessDeniedAccess Denied6683BC64F8FCAB0CE2foYctY9f7GMW+VI64vr3rRfMPrXXGfscryk3Eqo7meEtenXCLSa4kGYnQBJV6qDG9AdBVVgR8= Here's my settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'myblog/media') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'blogapp.apps.BlogappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages' ] 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 = 'myblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], '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 = 'myblog.wsgi.application' DATABASES = { 'default': { … -
Problem Setting Up django-autocomplete-light v3
I am following the instructions provided here https://django-autocomplete-light.readthedocs.io/en/master/install.html I have installed dal by using the command "pip install django-autocomplete-light" - this completed successfully & I can see dal under my python site packages As soon as I follow the Configuration section & update my INSTALLED_APPS in settings with INSTALLED_APPS = [ 'dal' 'dal_select2', 'django.contrib.admin',..... I get a 500 - Internal server error. As soon as I remove 'dal','dal_select2' from my settings my server works OK again. My understanding of Django is that the INSTALLED_APPS section was referencing the various folders within my app but there is not folder for dal or dal_select2 which would cause the 500 - Internal server error. Is there another command I should be using to either move the dal folders into my application or to make my settings reference the Python27/Lib/site-packages/dal folder I am running Django 1.11.23 django-autocomplete-light 3.4.1 Many thanks for any pointers provided. -
I don't understand django's 404 display
I want to move to my 404 page when accessing a URL that is not set. We are trying to implement it in multiple applications. I tried a few, but I can't. Where is the best way to write code? #setting DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] #project url.py from django.conf import settings from django.urls import re_path from django.views.static import serve # ... the rest of your URLconf goes here ... if settings.DEBUG: urlpatterns += [ re_path(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), ] handler404 = 'person.views.handler404' handler500 = 'person.views.handler500' #application view.py def handler404(request): response = render_to_response('404.html', {}, context_instance=RequestContext(request)) response.status_code = 404 return response def handler500(request): response = render_to_response('500.html', {}, context_instance=RequestContext(request)) response.status_code = 500 return response -
How to create a date field once item is created?
Iam trying to have a date next to the item once the item is created. I did add datetimefield in the model and added the template in my home.html but somehow Once the item is created 'POST' nothing happens or appears. class List(models.Model): item = models.CharField(max_length=20) completed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.item class Meta: ordering = ['created_at'] def home(request): if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_items = List.objects.all messages.success (request, 'item has been added to the list') return render(request, "home.html", {'all_items': all_items}) else: all_items = List.objects.all return render(request, "home.html", {'all_items': all_items}) the output is nothing. date doesnt appear even tho the item is successfully added. -
How can I override delete model action in Django
I override delete_model method on my admin model, but it doesn't calling. Please some one help me. Django admin: override delete method class ManageAdmin(ImportExportActionModelAdmin): actions = ['delete_model'] def delete_model(self, request, obj): logger.info('delete model method called!'); log is none. -
Ran _git rm --cached *.pyc and now No module named 'django'
I kept getting merge conflicts when trying to git pull from github to my production server and a lot of them had to do with the .pyc files. So on my local machine, I ran _git rm --cached *.pyc git add . git commit git push -u origin dev Since I had *.pyc in my .gitignore but hadn't committed properly. Anyways, when I go to git pull on my production server, everything is pulled fine no merge conflicts. But then I kept getting server errors on my site when trying to access the admin panel and this is the error File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Obviously I have a virtual env working and this must be because the __pycache__ files were removed with the latest commit. Can anyone help me? I'm not sure what to do. -
How to make a many to many links without altering the record object
I feel like I am missing something basic here but I can't figure it out. I will give a simplified example of what I am trying to achieve. Take this typical restaurant example for instance. If I have pizza table that is populated with records of pizza names. Another table is records pizza-toppings. They have a many to many relationship. If a customer orders the "2 Topping" with "Pepperoni" and "Mushrooms", then in the backend, some script would get the "2 Topping" pizza object and get the two topping objects and then link/add/relate them. So that pizza.toppings.all() would return a QuerySet of the two topping. If a different customer at shortly after orders the exact same pizza. The previously added toppings will already be linked to that pizza object. Obviously it's not practical to clear relationships after every order has been made. ##Model class Pizza(models.Model): name = models.CharField(max_length=30) toppings = models.ManyToManyField('Topping', related_name='pizzas')) def __str__(self): return self.name class Topping(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Order(models.Model): pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) ## Logic cheese_pizza = Pizza.objects.create(name='Cheese') mozzarella = Topping.objects.create(name='mozzarella') mozzarella.pizzas.add(cheese_pizza) mozzarella.pizzas.all() -> <QuerySet [<Pizza: Cheese>]> How can I add pizza objects, with toppings linked, to an Orders table without affecting …