Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Project Install error (The conflict is caused by: The user requested asgiref==3.2.5 django 3.1.14 depends on asgiref<4 and >=3.2.10)
When I try to install requirements.txt this error happened. This is requirements.txt asgiref==3.2.5 astroid==2.3.3 certifi==2019.11.28 chardet==3.0.4 colorama==0.4.3 defusedxml==0.6.0 dj-database-url==0.5.0 Django==3.1.14 django-allauth==0.41.0 django-crispy-forms==1.9.0 django-heroku==0.3.1 gunicorn==20.0.4 idna==2.9 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 oauthlib==3.1.0 Pillow==9.0.1 pylint==2.4.4 PySocks==1.7.1 python3-openid==3.1.0 pytz==2019.3 requests==2.23.0 requests-oauthlib==1.3.0 six==1.14.0 sqlparse==0.3.1 stripe==2.43.0 This error says *ERROR: Cannot install -r requirements.txt (line 8) and asgiref==3.2.5 because these package versions have conflicting dependencies. The conflict is caused by: The user requested asgiref==3.2.5 django 3.1.14 depends on asgiref<4 and >=3.2.10 To fix this you could try to: loosen the range of package versions you've specified remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts* -
Intro.JS possible to check user input before proceed
So, i want to come out with the Javascript which forced user to input / select anything before going to next step, (like forced user to press button, input their name, etc). I am working on Django Framework with mix together with Javascript and HTML together. Ignore the first part as I am trying to assign each function to the button so the button can do different tasks individually. But it wont work in the intro.js script. Code snipper are below: <script> /* var btn1=document.getElementById("button1"); var btn2=document.getElementById("button2"); var div=document.getElementById("InputName"); btn1.onclick=function(){ if (div.style.display !=="none") { div.style.display="none"; } else { div.style.display="block"; } }; // this is the crucial part btn2.onclick=function(){ var steps=[ {element:"#button1",intro:"A button", position:"right"}, {element:"#button2",intro:"This goes away sometimes"} ]; if (div.style.display==="none") { steps.splice(1,1); } introJs().setOptions({ steps:steps }).start(); } */ var steps=[ {element:"#InputName",intro:"Please fill your name", position:"right"}, {element:"#InputUsername",intro:"Please fill your username"}, {element:"#button1",intro:"Succesfully Filled, press register."} ]; introJs().setOptions({ steps:steps }).start(); -
How to use a signal to override/block a Django api request?
I've implemented a signal for my API endpoint, and I would like it to restrict access to the endpoint when the logic for the signal evaluates to false. Is there a nice way to do this? I noticed in my logs that it is properly evaluating to true or false, but it doesn't actually cause my view to send a 500 or some way of saying "access restricted". Rather, it still sends the normal API response. handlers.py from corsheaders.signals import check_request_enabled def cors_allow_mysites(sender, request, **kwargs): if ("Origin" in request.headers) and (request.headers["Origin"] == 'https://url.com'): print("Handler allowed") return True print("Handler not allowed") return False check_request_enabled.connect(cors_allow_mysites) apps.py from django.apps import AppConfig class ApiEndpointConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api_endpoint' def ready(self): # Makes sure all signal handlers are connected from . import handlers # noqa __init.py default_app_config = "api_endpoint.apps.ApiEndpointConfig" -
Is it possible to have two different lockout reset settings for django-axes lockout?
I am using a custom view django login and is currently implementing throttling for failed login attempt. Currently I am utlising Django-axes for this purpose. I have successfully implemented 'soft lockout' for my failed login attempt (lockout by username for every 10 failed login attempt within 5 minutes). I would like to check if it is also possible to implement a 'hard lockout' (verify no more than 100 failed attempt per hour is possible on a single account) along with this 'soft lockout'? This is what I have done for my 'soft lockout' settings.py INSTALLED_APPS = [ ..., 'axes' ] AUTHENTICATION_BACKENDS = ( "axes.backends.AxesBackend", ... ) # django-Axes systems # https://raw.githubusercontent.com/jazzband/django-axes/master/docs/4_configuration.rst ## basic configuration for login attempt and lockout duration AXES_FAILURE_LIMIT = 10 AXES_LOCK_OUT_AT_FAILURE = True AXES_COOLOFF_TIME = 0.083 # lockout 5 mins AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT = False AXES_ONLY_USER_FAILURES = True AXES_RESET_ON_SUCCESS = True ## custom account soft lockout message AXES_LOCKOUT_CALLABLE = 'customlogin.views.user_lockout' CUSTOM_AXES_SOFT_LOCKOUT_MESSAGE = 'Too many failed login attempts. Please try again in 5 minutes.' ## fields to use for checking AXES_USERNAME_FORM_FIELD = 'email' ## logging for db AXES_DISABLE_ACCESS_LOG = True AXES_ENABLE_ACCESS_FAILURE_LOG = True AXES_ACCESS_FAILURE_LOG_PER_USER_LIMIT = 300 views.py from axes.decorators import axes_dispatch @axes_dispatch def user_login(request): # main body of code def … -
how to upload image file from project directory in django?
I have this function which will convert any images to jpg format. While doing this it saves the file inside my project root directory but what I want is I want to upload it into my model and remove that image from the directory. def convert_image_to_jpg(image): from PIL import Image im = Image.open(image).convert("RGB").save("some.jpg", "JPEG", quality=100) # save into the model MyModel.objects.create(image=im) In my model I am getting None values for image but inside the project root directory there is a image in jpg format. -
Error Deploying Django App on Elastic Beanstalk
I'm trying to deploy my Django app on elastic beanstalk. It is saying that it is deployed, but the health immediately turns red and I see "502 Bad Gateway / Nginx" when I try to go to the site. I know there are other answers to this question on stack overflow, but I am still stuck. In my logs I see web: ModuleNotFoundError: No module named 'mysite.wsgi'. In my file repos/mydjangoproject/mysite/.ebextensions/django.config I have aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "core.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: mysite.wsgi:application And I have a file: repos/mydjangoproject/mysite/mysite/wsgi.py Which contains import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() I also am seeing these errors 2022/07/04 01:57:50 [error] 3507#3507: *536 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.22.27, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "44.241.154.93" 2022/07/04 01:57:50 [error] 3507#3507: *536 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.22.27, server: , request: "GET /blog/wp-includes/wlwmanifest.xml HTTP/1.1", upstream: "http://127.0.0.1:8000/blog/wp-includes/wlwmanifest.xml", host: "44.241.154.93" I have gunicorn installed and in my requirements.txt. Any thoughts on what I might be doing wrong would be appreciated! -
how can I import django to my python path
I started my project, it was running successfully until I returned back to continue, and encountered this problem. I typed 'python manage.py makemigrations' and this error message popped up on terminal '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?' How can I resolve this problem -
Django CORS Handler is false but not but not rejecting API requests
When I run my Django CORS framework, nothing gets filtered out. The value gets evaluated to false when I insert print statements to the handlers but it's not filtering out requests to my view endpoint. Do I need to make any changes to my view? Am I missing something that will make it reject requests that don't meet the criteria in cors_allow_mysites? handlers.py from corsheaders.signals import check_request_enabled def cors_allow_mysites(sender, request, **kwargs): return ("Origin" in request.headers) and (request.headers["Origin"] == 'url.com') check_request_enabled.connect(cors_allow_mysites) apps.py from django.apps import AppConfig class ApiEndpointConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api_endpoint' def ready(self): # Makes sure all signal handlers are connected from . import handlers # noqa __init__.py default_app_config = "api_endpoint.apps.ApiEndpointConfig" -
What unit tests could I build for a class like this?
I have several such classes in my views. And I need to test them all. class ExampleViewSet(viewsets.ModelViewSet): serializer_class = ExampleSerializer queryset = Example.objects.all() filter_backends = (filters.DjangoFilterBackend,) filterset_class = ExampleFilter All were created with the help of available Django Rest Framework libraries. -
How to maintain metrics after restart server?
I'm using Prometheus to monitor my local Django server. I successfully connected them and wrote a custom metric custom_counter in code. Unfortunately, I recognized that the custom metrics the metric custom_counter_total would always reset to 0 every time I restart my server. It sounds bad because I can only see something about it since the last time I restarted the server. Is there any method to save the metrics so we can persist the metrics even after resetting server? Thanks in advance! -
Django Cors Handler evaluating to false but not rejecting API requests
My Django Cors Framework Handler is being ran, but is not filtering anything out. When I inserted print statements to the handlers, I saw that the value was evaluating to false (meaning it had the signal to reject) but it was not actually filtering out requests to my view endpoint. I did not make any changes to my view (I was under the assumption I did not need to). Am I missing something that will make it reject requests that don't meet the criteria in cors_allow_mysites. handlers.py from corsheaders.signals import check_request_enabled def cors_allow_mysites(sender, request, **kwargs): return ("Origin" in request.headers) and (request.headers["Origin"] == 'url.com') check_request_enabled.connect(cors_allow_mysites) apps.py from django.apps import AppConfig class ApiEndpointConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api_endpoint' def ready(self): # Makes sure all signal handlers are connected from . import handlers # noqa __init__.py default_app_config = "api_endpoint.apps.ApiEndpointConfig" -
How to use job autocomplete api?
I am designing a job search website and I want to use api for job title autocomplete and skill autocomplete. I found sth on github but I don't now how to use it. Can anyone help me to use it in django? -
How to save output into single drop-down with django
I have a scraper that scraper data on cruises, I am grabbing the title of the cruise. My aim was to output these results into a single drop down menu so I can select one of these from the drop-down. However, it instead produces multiple input options and only a single title in the drop down. I.E. My script: models.py: from django.db import models class Cruises(models.Model): title = models.TextField(max_length=200) views.py: from django.shortcuts import render from .models import Cruises def basic(request): long_list = Cruises.objects.values('title') return render(request, 'cruise_control/basic.html', context = {'long_list':long_list}) basic.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Cruises</title> </head> <body> <h1> Cruise Control </h1> {% for lng_l in long_list %} <form action="/action_page.php"> <label for='destination'>Destination</label> <input type="text" list="destination" /> <datalist id="destination"> <option>{{lng_l.title}}</option> </datalist> <!label for="cruisetime">Departure date</label> <!input type="date" id="cruisetime" name="cruisetime" min={{dep_l.departureDate}}> <!input type="submit"> </form> {% endfor %} </body> </html> -
How to implement different model fields for different categories?
I have 2 models like this class Category(MPTTModel): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Product(models.Model): name = models.CharField(max_length=70) category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) slug = models.SlugField(unique=True) description = models.TextField(max_length=300) and in every category i need my Product to have +/- 10 additional fields for example processors(Category#1) and SSD drives(Category#2) Category#1-Product#1(-/-, total_cores, total_threads, ..), Product#2(-/-, total_cores, total_threads, ..), ... Category#2-Product#3(-/-, storage_capacity, connector, ..), Product#4(-/-, storage_capacity, connector, ..), ... Is there any way to add fields to Product depending on the Category it belongs to or i need to create models for each Category? -
How can I modify this script so that all changes are deployed to django GAE (Google App Engine)?
Background: I have this script called run_fabric that runs at the end of a Github action pipeline and deploys changes in my Django app. I didn't write this code but I think it must only copy the html files from repo to the nginx server and then restarts the server. Unfortunately I try to change python files and I never see my code changes deployed. I think it's because it only copies html files over (I'm trying to make changes to IPN paypal gateway in the hooks.py file so I can update the price on checkout but I don't see this change reflected) Is there a way I can modify this script below to include all python files as well as html so I can see code changes deployed to my Django app hosted on GAE? I've replace ipaddress with my static ip address of GAE for security reasons. Code is below: from fabric import Connection import os import glob x = glob.glob("./web/templates/*.html") c = Connection("ipaddress", port=22, user="fady", connect_kwargs={'look_for_keys': False,'key_filename':'priv'}) for i in x: out =i.split("/")[-1] c.put(f"{i}",f"/home/fady/soild/web/templates/{out}") res = c.run("sudo service uwsgi restart") res = c.run("sudo service nginx restart") print("Done") My project structure is like /root ./run_fabric.py (script above) ./manage.py … -
'list' object has no attribute 'startswith' with Django and scrapy integration
I am getting this peculiar error after I try to runserver once I have finished web-crawling as my web-crawler is connected to django : Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/usr/opt/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Users/usr/opt/anaconda3/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 107, in check_url_settings value = getattr(settings, name) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 93, in __getattr__ val = self._add_script_prefix(val) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 140, in _add_script_prefix if value.startswith(("http://", "https://", "/")): AttributeError: 'list' object has no attribute 'startswith' It seems to be an error located in one of the django files rather than from my script. However, I am strongly convinced something in my script is causing this. Here's my script: from django.db import models class Cruises(models.Model): title = models.CharField(max_length=200) views.py: from django.shortcuts import render from .models import Cruises def basic(request): long_list = Cruises.objects.values('title') return render(request, 'cruise_control/basic.html', context = {'long_list':long_list}) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.basic, name = 'basic') ] -
Heroku can not find generated file
I have a Django project which generates a PDF file. This below is the corresponding code: def createPDF(name): current_path = os.path.dirname(os.path.dirname(__file__)) template = get_template(f'src.tex') context = { 'content': name, } rendered_tpl = template.render(context).encode('utf-8') process = subprocess.Popen( ['pdflatex', '-output-directory', f'{current_path}/templates'], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) When I run the local server and run my function the PDF is saved in my templates directory. However, after deploying on Heroku, and generating the PDF the PDF is not found. I tried to look for it in the bash, but it is just not there. What is wrong? -
CORS headers not showing up in my request/response on Django
I've made the following CORS implementation on my Django project using django-cors-headers. CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', .... ] INSTALLED_APPS = [ ... 'corsheaders', ] For some reason, I don't see the effect of these headers (I don't have Access-Control-Allow-Origin in my headers). I print out the request and response headers in my view. This is my view: def payment(request, *args, **kwargs): print(request.headers) params_in = json.loads(request.body.decode('utf-8')) headers_in = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer key, } response = requests.post('https://url.com/v1/endpoint', headers=headers_in, data=params_in) resp_out = Response(response.json()['value']) print(resp_out.headers) return resp_out My request headers are ['Host', 'Connection', 'Content-Type', 'Origin', 'Accept-Encoding', 'Cookie', 'Accept', 'User-Agent', 'Referer', 'Accept-Language', 'X-Request-Id', 'X-Forwarded-For', 'X-Forwarded-Proto', 'X-Forwarded-Port', 'Via', 'Connect-Time', 'X-Request-Start', 'Total-Route-Time', 'Content-Length'] and my only resp_out header is 'Content-Type'. Why could this be? What am I missing? -
Changing language in Django i18n
I was working on an ecommerce website and it has two language options. I am fetching data using an sql code I found on youtube. Let me describe how it works; When a vendor adds a product, he must fill the forms on both languages. If the vendor fills only the English form, his product will be seen if a user uses English. If the user switches the language his product disappears. How can I correct this? What I want is, If the 2nd language is filled, bring that. If the English form is only filled, it should bring the English form not make it disappear. Here is the sql code in my views: defaultlang = settings.LANGUAGE_CODE[0:2] currentlang = request.LANGUAGE_CODE[0:2] if defaultlang != currentlang: setting = SettingLang.objects.get(lang=currentlang) products_lat = Product.objects.raw( 'SELECT p.id, p.price, p.is_featured, l.title, l.description,l.slug ' 'FROM product_product as p ' 'LEFT JOIN product_productlang as l ' 'ON p.id = l.product_id ' 'WHERE l.lang=%s ORDER BY p.id DESC LIMIT 50', [currentlang]) prod = Product.objects.raw( 'SELECT p.id,p.price, l.title, l.description,l.slug ' 'FROM product_product as p ' 'LEFT JOIN product_productlang as l ' 'ON p.id = l.product_id ' 'WHERE p.is_featured=%s and l.lang=%s ORDER BY p.id DESC LIMIT 20', [True, currentlang]) Thanks in … -
Requested setting LOGGING_CONFIG when using scrapy with django
I am new to scrapy and django integration, however I am trying something simple to get things going in my career with the two. Essentially, I want to grab the titles from a website, models will read this and views will upload this to a basic html template. However, I get this error when I run scrapy crawl test django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Here's my tree: ── cruise_control ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-38.pyc │ ├── admin.cpython-38.pyc │ ├── apps.cpython-38.pyc │ ├── models.cpython-38.pyc │ ├── urls.cpython-38.pyc │ └── views.cpython-38.pyc ├── admin.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-38.pyc │ └── __init__.cpython-38.pyc ├── models.py ├── templates │ └── cruise_control │ └── basic.html ├── tests.py ├── urls.py └── views.py ── cruises ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-38.pyc │ ├── settings.cpython-38.pyc │ └── urls.cpython-38.pyc ├── asgi.py ├── scraper │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ └── settings.cpython-38.pyc │ ├── items.py │ ├── middlewares.py │ ├── pipelines.py │ ├── settings.py │ └── spiders │ ├── __init__.py │ └── test.py … -
operator does not exist: bigint = uuid in django
I want to use uuid field as my id (primary key) but there is something wrong with it and i can't fix it this is my model class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE , related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() class Meta: unique_together = [['cart'], ['product']] This Is MY Serializer.py class CartItemSerializer(serializers.ModelSerializer): class Meta: model = Cart fields = ['id', 'product', 'quantity'] class CartSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) items = CartItemSerializer(many=True) class Meta: model = Cart fields = ['id', 'items'] And My Views.py is class CartViewSet(CreateModelMixin, RetrieveModelMixin, GenericViewSet): queryset = Cart.objects.prefetch_related('items__product').all() serializer_class = CartSerializer My database Is postgres Sql My Error when I browse my api my guid -
Access data from one model and use that in another model
I have a website that generates a page for each database entry. Each page generates its own form so a user can submit data for the owner of that page. I want to be able to have a value in my UserInfo class that looks at the Page class to see the PageOwner that is associated with that Page class. I want see which page (database entry) that user came from. class Page(models.Model): address = models.CharField(max_length=150) slug = models.SlugField(unique=True, ) page_owner = models.ForeignKey(Agent, on_delete=models.SET_NULL, null=True, related_name='page') class PageOwner(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=20) def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.full_name() This is my ModelForm. The page_agent_name is not shown to the user using the: (class Meta: exclude statement) class UserInfo(models.Model): user_name = models.CharField(max_length=100, default='', ) user_email = models.CharField(max_length=100, default='', ) # I want these values to get the owner name, phone, email page_owner_name = models.CharField(max_length=100, default='', ) page_owner_phone = models.CharField(max_length=100, default='', ) page_owner_email = models.CharField(max_length=100, default='', ) -
In Django, how do I get the corresponding key for a value passed in through the url?
Here is my models.py: SHOW = ( (0,"Ballers"), (1,"Silicon-Valley") ) class Show(models.Model): show = models.IntegerField(choices=SHOW, blank=True, null=True) Here is from my urls.py: urlpatterns = [ path('<str:show>/', views.ShowList.as_view(), name='show-list'), ] I want to be able to have the url look like this: https://www.mywebsite.com/ballers, but when I try to run it, I get this error: Field 'show' expected a number but got 'ballers'. I know I can fix this by calling the url https://www.mywebsite.com/0, but I don't want the url to look like that. -
why do my django forms stop working when I put them all in the same view?
I create 4 different multiple choice form in the same pages, the problem start when the forms stay togheter, the single form work but when i render all the forms in the views doesn't save and not write in the models, in the views I put messages and the code doesn't open the second if the view. form: countries = forms.ModelMultipleChoiceField(queryset=Nation.objects.filter(id__in= [1,4,8]), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model=CountriesUser fields=['countries'] Views @login_required def CountriesNordView(request): if request.method=='POST': messages.success(request, 'first If') form_nord = CountriesNordForm(request.POST) form_center = CountriesCenterForm(request.POST) form_south= CountriesSouthForm(request.POST) form_topics=TopicsForm(request.POST) if form_nord.is_valid() and form_center.is_valid() and form_south.is_valid() and form_topics.is_valid(): messages.success(request, 'Second If') instance=form_nord.save(commit=False) instance2=form_center.save(commit=False) instance3=form_south.save(commit=False) instance4=form_topics.save(commit=False) instance4.accounts=instance2.accounts=instance.accounts=instance3.accounts=request.user.id instance.save() instance2.save() instance3.save() instance4.save() else: messages.success(request, 'else') form_nord = CountriesNordForm(request.POST) form_center=CountriesCenterForm(request.POST) form_south=CountriesSouthForm(request.POST) form_topics=TopicsForm(request.POST) messages.success(request, 'out of condition ') con={'form_nord' : form_nord, 'form_center': form_center, 'form_south': form_south, 'form_topics': form_topics } return render(request, 'users/preferences.html', context= con) -
How to edit intermediate table Django?
So i'm trying to make 2 models like so class Product(models.Model): name = models.CharField(max_length=70) availability = models.ManyToManyField(Store) class Store(models.Model): name = models.CharField(max_length=150) location = models.CharField(max_length=150) and the problem is somewhere in database i need to store amount of concrete goods containing in each store. Like Product#1 - Store#1(23), Store#2(12) and etc. Is there any possibility to store it in intermediate table (from ManyToManyfield) or is there something easier.