Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use django-notifications to realize personal message notification and system notice?
How can I use django-notifications or another tool to realize personal message notification and system notice? We have many apps that need this function(more than 10 tables are involved), so I really need an easy way to solve it, thanks so much for any advice Our system(wrote in Django-rest-framework) has a function, that needs to push information when the relevant users' information is added or updated, the system will send relevant users information, such as "Your order is waiting for review (to the auditor)" "Your order is passed (to the auditee)" and also need some system notice, that every user can see that message: "Outage notice, this system will restart at XXXXX, please ......" -
/app/.heroku/python/bin/python: /app/.heroku/python/bin/python: cannot execute binary file
When I tried running "heroku run bash python manage.py migrate --app appName" from my terminal using the Heroku CLI, I get below error/response; "/app/.heroku/python/bin/python: /app/.heroku/python/bin/python: cannot execute binary file". -
How to show the links to the category with Django
I'm coding a bookmark project to learn django. I want to show the links belonging to the category. but when I run the for loop, the categories are shown twice and the card design is sorted one under the other instead of side by side. I think the problem is with the index.html file. I think I need to use if command but I don't know how. index.html <!-- component --> <div class="bg-gray-100"> <div class="container mx-auto"> <div role="article" class="bg-gray-100 py-12 md:px-8"> <div class="px-4 xl:px-0 py-10"> <div class="flex flex-col lg:flex-row flex-wrap"> <div class="mt-4 lg:mt-0 lg:w-3/5"> <div> <h1 class="text-3xl ml-2 lg:ml-0 lg:text-4xl font-bold text-gray-900 tracking-normal lg:w-11/12">Lorem ipsum</h1> </div> </div> <div class="lg:w-2/5 flex mt-10 ml-2 lg:ml-0 lg:mt-0 lg:justify-end"> <div class="pt-2 relative text-gray-600"> <input class="focus:ring-2 focus:ring-offset-2 focus:ring-gray-400 bg-white h-10 px-5 pr-16 rounded-lg text-sm focus:outline-none" type="search" name="search" placeholder="Search" /> <button type="submit" class="focus:ring-2 focus:ring-offset-2 text-gray-600 focus:text-indigo-700 focus:rounded-full focus:bg-gray-100 focus:ring-indigo-700 bg-white focus:outline-none absolute right-0 top-0 mt-5 mr-4"> <svg class="h-4 w-4 fill-current" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 56.966 56.966" style="enable-background: new 0 0 56.966 56.966" xml:space="preserve" width="512px" height="512px"> <path d="M55.146,51.887L41.588,37.786c3.486-4.144,5.396-9.358,5.396-14.786c0-12.682-10.318-23-23-23s-23,10.318-23,23 s10.318,23,23,23c4.761,0,9.298-1.436,13.177-4.162l13.661,14.208c0.571,0.593,1.339,0.92,2.162,0.92 c0.779,0,1.518-0.297,2.079-0.837C56.255,54.982,56.293,53.08,55.146,51.887z M23.984,6c9.374,0,17,7.626,17,17s-7.626,17-17,17 s-17-7.626-17-17S14.61,6,23.984,6z" /> </svg> </button> </div> </div> </div> </div> {% for bookmark in bookmark_list %} <div class="px-6 xl:px-0"> <div class="grid sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 … -
I keep getting an error when trying to create a database in my Django Project
I deleted my database and migration files with the exception of init on purpose, I wanted to start fresh. Using these commands: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete I then dropped the database. Commands did their job, deleted all the migrations files necessary I then went on to create the table again: python3 manage.py makemigrations I get this error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: auctions_category Things I've tried: python3 manage.py migrate --run-syncdb (same error) -
502 Error on Production Deployment Django & Nginx using a docker compose file
I am using docker-compose to build containers and to serve the frontend of my website at https:// example.com and the backend at a subdomain, https:// api.example.com. The SSL certificates for both the root and subdomain are working properly, and I can access the live site (static files served by Nginx) at https:// example.com so at least half of the configuration is working properly. The problem occurs when the frontend tries to communicate with the backend. All calls are met with a "No 'Access-Control-Allow-Origin'" 502 Error in the console logs. In the logs of the docker container, this is the error response. Docker Container Error 2022/03/09 19:01:21 [error] 30#30: *7 connect() failed (111: Connection refused) while connecting to upstream, client: xxx.xx.xxx.xxx, server: api.example.com, request: "GET /api/services/images/ HTTP/1.1", upstream: "http://127.0.0.1:8000/api/services/images/", host: "api.example.com", referrer: "https://example.com/" I think it's likely that something is wrong with my Nginx or docker-compose configuration. When setting the SECURE_SSL_REDIRECT, SECURE_HSTS_INCLUDE_SUBDOMAINS, and the SECURE_HSTS_SECONDS to False or None (in the Django settings) I am able to hit http:// api.example.com:8000/api/services/images/ and get the data I am looking for. So it is running and hooked up, just not taking requests from where I want it to be. I've attached the Nginx configuration … -
use multi database in django class based view
Im using django for a project with many database(about 500). So I can't write route for my databases, then I use "using", but the question is how can I use class based view like update or create view? what function shuld I override to change database query? -
Python Django IMG upload function based
I do not want to use class based forms. (function based) I need to be able to created my own form with a few fields and give the option to add either a photo or word doc. Any help would be awesome. def addmessage(request): if request.POST: Message.objects.create( name_of_msg = request.POST['name_of_msg'], message = request.POST['message'], photo = request.POST['photo'], file = request.POST['file'] ) return redirect('/home') def addmessage(request): if request.POST: Message.objects.create( name_of_msg = request.POST['name_of_msg'], message = request.POST['message'], photo = request.FILES['photo'], file = request.FILES['file'] ) return redirect('/home') def home(request): context={ 'photos' : Message.objects.all() } return render(request, 'home.html', context) #to access it on the front end {% for photo in photos %} {{photo.photo}} {% endfor %} <h3>Add a Message:</h3> <form action="/addmessage" method="POST"> {% csrf_token %} <input class="type=" text" name="name_of_msg" placeholder="Message Name"> <br> <input class="type=" text" name="message" placeholder="Message"> <br> <input type="file" name="photo" placeholder="Add Photo"> <br> <input type="file" name="file" placeholder="Add a Doc"> <br> <input type="submit" value="Add It!"> </form> </div> -
Create a reverse relationship to two models
I have a model User. For performance and other reasons I have to split this Model and its table into two, UserA and UserB. I decided to use materialized views (with the help of django-pgviews). Now what IS easy is to query the data of UserA which is already in the table, like the username or password. What doesn't work are reverse relationships. Let's say I have a Checkout model and in this: user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='checkouts') When I try to access user.checkouts, it of course throws an error: Cannot resolve keyword 'checkouts' into field. So how can I create a reverse relationship which is accessible from multiple models? I thought about using contenttypes but this seems a bit much for this use case, especially because UserA and UserB are just views and have the same columns. -
Django Admin Select2 failing to search with TypeError: Cannot read properties of undefined (reading 'slice') at o.e.removePlaceholder
I am using django 3.2 and trying to use the Select2 autocomplete field option in my admin page. I am a full administrator with all rights to all objects. I have followed the document and have the Select2 field showing up on my related field and i have the search_field setup on the parent model. When I click into the select2 field i can see all the options and select them. They also display fine when selected. However, if i try to type in the search box it fails with a javascript error: Query.Deferred exception: Cannot read properties of undefined (reading 'slice') TypeError: Cannot read properties of undefined (reading 'slice') at o.e.removePlaceholder (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:45012) at o.removePlaceholder (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:4435) at o.e.append (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:44816) at o.append (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:4435) at d.<anonymous> (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:10117) at d.e.invoke (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:5066) at d.e.trigger (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:4885) at d.trigger (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:65478) at https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:63778 at Object.<anonymous> (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:38274) undefined To me it looks like its not able to search the string i am entering but im using a default install of django admin. So i am not sure what i am doing wrong. My autocomplete model looks like this class TeamMember(models.Model): .... exclude_case_type = models.ManyToManyField(CaseType, blank=True, related_name="case_types", help_text="Individually Exclude a Case Type") .... class CaseType(models.Model): """Model definition for CaseType.""" … -
how to Implement add to basket in django?
Im developing an ecomerce website with django! Django+ vue js. For add to basket/cart. Shoud i use django session in backend? Vue js also have session storage ! Which one is the proper way? Whats the diffrence? -
Keep track of follow/unfollow events django
I am building a sort of social media app, where users can follow certain pages. I want the page managers to be able to visualize their followers in a chart for each day/week or so. So I am thinking about how to implement the following system. For now, I have this model: class FollowHistory(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name="follow_history") page = models.ForeignKey('Page', on_delete=models.CASCADE, related_name="follower_history") timestamp = models.DateTimeField(auto_now_add=True) followed = models.BooleanField() When a user clicks Follow, I create an instance with followed = True, and the timestamp of the event. When a user clicks Unfollow, I do the same, but with followed = False. I am struggling to figure out how to query the data in a way for a page to see how many users they had each day. So far I have tried this: FollowHistory.objects.filter(page=page, followed=True)\ .annotate(ts_day=Trunc('timestamp', 'day'))\ .values('ts_day')\ .annotate(followers=Count('id')) But that just gives me the count of events that happened in a day, so if I follow and unfollow a company 10 times, then it will count 10 times. I only need to know by the end of the day, did I follow or not? Maybe there is a better implementation of the model that you could recommend, … -
How to save contents of template html page to a list in Djano web application?
I am working on development of a web application in Django. I don't have much experience in it. In the html template page(e.g. homepage.html) after a button click, an action takes place and a relevant text is displayed. It is shown under "notes" id as: <div id="notes"></div><br> Text changes to different button clicks and different text is displayed under "notes" id. **I wanted to be able to save the contents as a list of strings/dictionaries and append the texts each time a new button is pressed. Or else update the last added entry in the list (similar to python or C++ coding) I learnt that we can carry out some codes using <script> tag but I had the assumption that such scripts are only for client-side and not server-side. I need the list on the server-side for further processes in the web app (or downloading the the list or ac**. Please suggest what should be done. I've been stuck at this problem for a long time. Thanks very much! -
Apache2 not using WSGI with HTTPS
I had been running my django app on top of a basic html website in an Apache2 webserver. mysite.com is the basic html site, while django was pointed at mysite.com/app using WSGI alias in the apache2 site config. It worked perfectly fine until I set up HTTPS with Certbot. Even after updating the site config, it no longer works. Whenever I try to go to mysite.com/app the error log states it tried to access var/www/html/app instead of var/www/mydjangoapp as it has previously done without issue. According to the log, WSGI does start successfully and runs several python processes, but if we go to the url, we get a 404. Here's my config which is located in a single file mysite.conf and enabled: <VirtualHost *:80> ServerName mysite.com Alias /static /var/www/myapp/static <Directory /var/www/myapp/static> Require all granted </Directory> <Directory /var/www/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-path=/var/www/myapp python-home=/var/www/djangoenv WSGIProcessGroup myapp WSGIScriptAlias /myapp /var/www/myapp/myapp/wsgi.py RewriteEngine on RewriteCond %{SERVER_NAME} !^443$ RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L] </VirtualHost> <VirtualHost *:443> ServerName mysite.com Alias /static /var/www/myapp/static <Directory /var/www/myapp/static> Require all granted </Directory> <Directory /var/www/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> #WSGIDaemonProcess myapp python-path=/var/www/myapp python-home=/var/www/djangoenv WSGIProcessGroup myapp WSGIScriptAlias /myapp /var/www/myapp/myapp/wsgi.py SSLEngine on SSLCertificateFile /etc/letsencrypt/live/mysite.pem SSLCertificateKeyFile /etc/letsencrypt/live/mysite.pem … -
How can I make a list of data show as a dropdown in DjangoAdmin?
I have a column in Django Admin, that is not a field on the table model. The column shows a list of data. I would like this column to be a dropdown, but it is currently just showing as text. It looks like I can use choices to force this to be a dropdown, but the options in the dropdown are dynamic, so choices doesn't seem to be a good fit here. Here is my method defining the column: def my_method: collection = list(MyModel.objects.values_list('name', flat=True)) return mark_safe(collection) How can I make a list of data show as a dropdown in DjangoAdmin? Sorry if this is too vague - I am new to Django and DjangoAdmin, so not sure what kind of information is necessary. -
Django: Setting def __str__ to a Related Model
Objective: I am trying to set the __str__ of a model to the name of a related model. The Profile model has a __str__ that returns "last name, first name" of the user. I would like the Inspector to return something similar with their inspector_number. Currently: The __str__ is returning "users.Profile.None 12345" instead of the desired "Doe, John 12345". This is one of my first times using related_name for a model and I seem to be missing something. Model.py class Profile(BaseModel): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True) inspector = models.ForeignKey(Inspector, on_delete=models.SET_NULL, null=True, blank=True, related_name="inspector_profile") def __str__(self): return self.user.last_name + ", " + self.user.first_name class Inspector(BaseModel): ... inspector_number = models.CharField(max_length=19, unique=True, editable=False, default=get_inspector_number) def __str__(self): ret = str(self.inspector_profile) + " " + str(self.inspector_number) return ret -
Django: how to make a get param or 404 function?
I want my endpoints to throw a 404 status code WITH a message like "parameter foo not found" if the request is missing a required field. Since i have too many endpoints, adding 3 lines of code (try, except, return) is not a happy solution for me. That's why i want to make a function similar to get_object_or_404 from django.shortcuts, where just using the function, the request returns 404 instead of just raising an exception and crashing the server. Taking a look to the get_object_or_404 function, i note that it does raise Http404 and this does work, but it always returns "detail": "Not Found" ignoring any parameter i pass to the exception raising code. Here's what i did: class ParamNotFound(Exception): def __init__(self, param_name): self.param_name = param_name self.status_code = 404 def __str__(self) -> str: return f"Param {self.param_name} not found" def get_body_param_or_404(params, param_name: str): param = params.get(param_name, None) if param is None: raise ParamNotFound(f"param_name {param_name} not found") return param But this does only raise a exception and crash the server if i dont explicitly catch it. Is there a clean and short way to do this? -
Users to see only their objects in Django
So I have an application where users can create their own Companies. But what I want in the view is for them to see only their entries on the view. I have seen similar questions on this platform but they don't work as expected. Below is my code. Models.Py from django.contrib.auth.models import User class Company (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) company_name = models.CharField(max_length=100, null=True) mailing_address = models.CharField(max_length=100, null=True) physical_address = models.CharField(max_length=100, null=True) class Meta: verbose_name_plural = "Companies" def __str__(self): return self.company_name views.py @login_required(login_url='login') def company (request): all_companies = Company.objects.filter(user=request.user) count= Company.objects.all().count() context = {'all_companies': all_companies, 'count': count} return render(request, 'company/company.html', context) forms.py class CompanyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CompanyForm, self).__init__(*args, **kwargs) self.fields['company_name'].widget.attrs = {'class': 'input',} self.fields['date_created'].widget.attrs = {'class': 'input',} self.fields['mailing_address'].widget.attrs = {'class': 'input',} self.fields['physical_address'].widget.attrs = {'class': 'input',} class Meta: model = Company fields = ('company_name', 'date_created', 'mailing_address', 'physical_address',) The so largely this works to ensure that every user only sees the company they have created. However, I can successfully create the companies from the admin side but a glaring issue appears. I have to manually select users from the form field = users in the admin form as shown in the picture below, to be able to create and … -
IntegrityError at /signup UNIQUE constraint failed: auth_user.username
IntegrityError at /signup UNIQUE constraint failed: auth_user.username Request Method: POST Request URL: http://127.0.0.1:8000/signup Django Version: 4.0.3 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: auth_user.username Exception Location: C:\msys64\mingw64\lib\python3.9\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute Python Executable: C:\msys64\mingw64\bin\python.exe Python Version: 3.9.10 from http.client import HTTPResponse from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.shortcuts import redirect # Create your views here. def home(request): return render(request, "authentication/index.html") return HttpResponse("Test") def signup(request): if request.method == "POST": username = request.POST.get('username') fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST.get('email') password = request.POST.get('password') password2 = request.POST.get('passowrd2') myuser = User.objects.create_user(username, email, password) myuser.first_name = fname myuser.last_name = lname myuser.save() messages.success(request, "Your Account Has Been Created.") return redirect('signin') return render(request, "authentication/signup.html") def signin(request): return render(request, "authentication/signin.html") def signout(request): pass -
Python regex specific pattern on the whole string
I wondering to know how I can find the below characters in the string. Target: Finding "1": { in the whole string The string is : "1": {"nodename": "G00L", "nodeSerial": "EZ00kksd000", "nodeIP": "100.000.000.000", "inventoryString": "{\"sh5\": {\"sl0\": \"\", \"sl1\": \"2|EZ1517A786|32EC2|8DG62635AAAA01|None\", \"sl9\": \"4|EZ1535A02880|11QPA4|8DG60349AAAC02|None\", \"sl0\": \"6|EZ170520014|WTOCM-F|8DG613788AAAB01|{~OCM~: None}\", \"sl8\": \"44|EZ1530A2788|AHPHG|8DG59245AAAB04|None\", \"sl18\": \"12|RT184905823|32EC2|8DG62635AANE05|None\", \"sl36\": \"11|LBALLU-YP15250047C|16DC65|3KC49010AAAB01|None\", \"sl37\": \"21|EZ1645A2184|16FAN2|3KC48990AAAD02|None\", \"sl40\": \"22|EZ1645A369912|16UP2|3KC48980AAAC01|None\"}}", "NodeOwner": "kk", "NodeSWVer": "0000PSSECX-00.0-00", "JiraOwner": "gggg", "LastJiraRun": "0000-00-00 00:00:00", "LastUpdated": "2022-03-08 10:29:03"}, -
Tastypie Resource post request not completing successfully
I am trying to create tastypie resurce to post the timezone and currency in DB table. I am getting this error response: error: "The 'timezone' field has no data and doesn't allow a default or null value." My Django Models: class Currency(models.Model): currency = models.CharField(max_length=200) iso = models.CharField(max_length=3, unique=True) created = models.DateTimeField(auto_now=True, db_index=True) updated = models.DateTimeField(auto_now=True, db_index=True) active = models.BooleanField(db_index=True, default=False) class Meta: db_table = 'currency' class Timezone(models.Model): timezone = models.CharField(max_length=200, unique=True) display_name = models.CharField(max_length=200) offset = models.DecimalField(max_digits=8, decimal_places=4) created = models.DateTimeField(auto_now=True, db_index=True) updated = models.DateTimeField(auto_now=True, db_index=True) class Meta: db_table = 'timezone' class Account(models.Model): timezone = models.ForeignKey(Timezone, on_delete=models.PROTECT) currency = models.ForeignKey(Currency, on_delete=models.PROTECT) country_code = models.CharField(default=120) created = models.DateTimeField(auto_now=True, db_index=True) updated = models.DateTimeField(auto_now=True, db_index=True) class Meta: db_table = 'account' And here is my Tastypie resources: lass TimezoneResource(ModelResource): class Meta(CommonMeta): queryset = Timezone.objects.all() resource_name = 'timezone' allowed_methods = ['get', 'post', 'put', 'patch', 'delete'] excludes = ['created', 'updated'] filtering = { 'timezone':ALL, } class CurrencyResource(ModelResource): class Meta(CommonMeta): queryset = Currency.objects.all() resource_name = 'currency' allowed_methods = ['get', 'post', 'put', 'patch', 'delete'] excludes = ['created', 'updated'] filtering = { 'currency':ALL, } class ManageTimezoneAndCurrency(ModelResource): timezone = fields.ForeignKey(TimezoneResource, 'timezone', full=True) currency = fields.ForeignKey(CurrencyResource, 'currency', full=True) class Meta(CommonMeta): queryset = Account.objects.all() always_return_data = True resource_name = 'manage-timezone-currency' allowed_methods … -
Moving Images and Data from Gallery 3, a php app, to a new Django web site
Just curious if anyone has ported their Gallery 3 data (images, comments, tags, etc) (https://galleryrevival.com, http://galleryproject.org/) to a Django photo gallery app. Just looking for pointers or gotcheas as I run down this rabbit hole... Gallery 3 is an old php application. I am not looking to create a Django version of Gallery 3, as I don't speak php and the code is getting a little long in the tooth at this point. I just want to import the images and metadata to a new Django photo gallery. Also, looking for recommendations for a simple Django photo gallery that has a way to import existing photos and metadata. Thanks! -
SQL Server String Data Types with Django
I am using Django with DRF to host a production API with SQL Server as our backend. We do not require Unicode data in any of our char/varchar usage, but when I capture the TSQL being compiled by Django, every string value being sent to SQL is defaulting to nvarchar. Are there any changes to settings.py for my Django project to force the use of UTF-8 when communicating with the database? I also see that Microsoft let's you set your database's collation level, but none of the UTF-8 options translate to my needs directly. -
How to obtain a list of all distinct first letters of given field
Let's say I have this Person class that consist of last_name string field. I would like to display links of all first letters of names existing in db. So for example: A B D E... when there's Adams, Brown, Douglas, Evans and no one that last_name starts with C. Of course view is not a problem here as I want to prepare all of this on backend. So the question is how to write good model's or view's function that will provide this. I would like it to be DB-independent, however tricks for any particular DB would be a bonus. Also, I would like this to be quite well optimized in terms of speed because it could be a lot of names. It should be less naive than this most simple algorithm: Get all people Create set (because of the uniqueness of elements) of the first letters Sort and return So for example (in views.py): names = Person.objects.values_list('last_name', flat=True) letters = {name[0] for name in names} letters_sorted = sorted(letters) Of course I could order_by first or assign new attribute to each objects (containing first letter) but I don't think it will speed up the process. I also think that assuming … -
Django data not being saved into the sqlite database
I am quite new to Django and I am working on this project. I am trying to save a recipe into the database and after correcting a few errors I get the "Success" message. However, when I open the database with the sqlite viewer it shows that the table is empty. Here is my views file: from django.http import HttpResponse, HttpResponseRedirect import json from django.http import StreamingHttpResponse from django.shortcuts import render from django.core.serializers import serialize from django.http import JsonResponse from django.template import RequestContext from .models import StockYeast, queryset_to_indexlist,queryset_to_array, Brew, Fermentable, Miscs, RecipeYeast, Recipes, Yeast,StockFermentables from .models import Hop,StockHop,StockMiscs from .forms import RecipeForm, RecipeFermentableForm, RecipeHopForm, RecipeMiscForm,RecipeWaterForm, RecipeYeastForm,RecipeMashForm, StockMiscForm from .forms import StockFermentableForm,StockHopForm,StockYeastForm, StockMiscForm from django.forms import formset_factory def index(request): return render(request, 'index.html') def recipes(request): if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): n = form.cleaned_data["name"] t = Recipes(name=n) t.save() return HttpResponse("Success") else: recipes = Recipes.objects.all() recipeFermentableFormset = formset_factory(RecipeFermentableForm, extra=1) recipeHopFormset = formset_factory(RecipeHopForm, extra=1) RecipeMiscFormSet= formset_factory(RecipeMiscForm, extra=1) RecipeYeastFormSet = formset_factory(RecipeYeastForm,extra=1) RecipeMashFormSet = formset_factory(RecipeMashForm,extra=1) return render(request, 'recipes.html', {'recipes':recipes,"recipe_form" :RecipeForm(auto_id="recipe_%s"), "recipe_fermentableformset":recipeFermentableFormset(prefix='fermentable'), "recipe_hopformset":recipeHopFormset(prefix='hop'), "recipe_miscformset":RecipeMiscFormSet(prefix='misc'), "recipe_yeastformset":RecipeYeastFormSet(prefix='yeast'), "recipe_mashformset" :RecipeMashFormSet(prefix='mash'), "recipeWaterForm":RecipeWaterForm()}) Here is my recipes.html: {% block content %} <!-- Modal --> <div class="card shadow-sm"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> Receptas</h5> </div> <div id="card-base" class="collapse show" aria-labelledby="headingOne" … -
How to make a post call with Django where your models are many to many?
I am trying to understand how I should be structuring my post call when I want to do a many to many relationship. class School(models.Model): name = models.CharField(unique=True, max_length=30, blank=True) teachersAtSchool = models.ManyToManyField('Teacher', blank=True) class Teacher(models.Model): account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) schoolsTeachingAt = models.ManyToManyField('School', blank=True) I send in the following JSON: { "name": "school Name", "teachersAtSchool": 0 } and get the following result: { "id": 13, "name": "school Name", "teachersAtSchool": [] } I have checked there are indeed teachers in the database that I can get with my GET call. I even tried with different id's but I get the same result. Its possible this is something super simple I just don't understand. Please help me. Regards