Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display card picture to the right side of the text?
I've started writing my first website project using django (recipe storage website). I've imported a template for the whole project and it came with its own stylesheet and other bits and bobs. Now, I am writing a page where I want to display all the recipes that are in the database. For that, I also borrowed a recipe display card template (it came with its own HTML and CSS). So, I looked up how to merge them and for the most part it works and displays properly. However, whatever I do, for the life of me I can't seem to make the image of the card to display to the right of the text (within the card), even though I've pasted my stylesheet and the cards style and HTML into jsfiddle.net and it displays perfectly. It only ever displays below the text. I assume it's not a conflict with my existing stylesheet, because none of the class names in the imported card stylesheet are the same as ones in my existing one, but I've been banging my head at this problem for like 8 hours now, and I can't seem to get it to work. I feel like I am … -
How to convert calculated properties (that involve calling other methods) into Django generated fields?
Let's say I have this following model: class Product(models.Model): price = models.DecimalField( max_digits=19, decimal_places=4, validators=[MinValueValidator(0)], blank=False, null=False, ) expiry_date = models.DateTimeField( blank=True, null=True, ) @property def price_in_cents(self): return round(self.price * 100) @property def has_expired(self): if self.expiry_date: return date.today() > self.expiry_date.date() else: return False So two fields, and two other properties that rely on these two fields to generate an output. I'm trying to convert these fields into generated fields (for Django 5). My first understanding was simply just putting in the property function in the expression, so something like this: class Product(models.Model): price = models.DecimalField( max_digits=19, decimal_places=4, validators=[MinValueValidator(0)], blank=False, null=False, ) price_in_cents = models.GeneratedField( expression=round(F("price") * 100), output_field=models.BigIntegerField(), db_persist=True, ) expiry_date = models.DateTimeField( blank=True, null=True, ) @property def has_expired(self): if self.expiry_date: return date.today() > self.expiry_date.date() else: return False Unfortunately, this does not seem to work, and I get the following error: TypeError: type CombinedExpression doesn't define round method Going by this, I assume I won't be able to simply convert the second property either. So how would this actually work? Is there a resource to help me convert these Python functions (properties) into valid expressions? -
Apache mod_wsgi macOS Error: Cannot load mod_wsgi.so - Library not loaded: @rpath/libpython3.9.dylib
I'm setting up a Django project with Apache and mod_wsgi on macOS using Homebrew. When I restart the Apache server, I encounter the following error: httpd: Syntax error on line 67 of /usr/local/etc/httpd/httpd.conf: Cannot load /usr/local/lib/httpd/modules/mod_wsgi.so into server: dlopen(/usr/local/lib/httpd/modules/mod_wsgi.so, 0x000A): Library not loaded: @rpath/libpython3.9.dylib Referenced from: /usr/local/Cellar/httpd/2.4.58/lib/httpd/modules/mod_wsgi.so Reason: no LC_RPATH's found context: Installed Apache using Homebrew. Installed mod_wsgi using pip. Apache configuration file (httpd.conf) includes the following block: <VirtualHost *:8080> ServerName webmaster@localhost DocumentRoot /var/www/html Alias /static /Users/abbasahmed/Desktop/AWD/topic9/bioweb/static <Directory /Users/abbasahmed/Desktop/AWD/topic9/bioweb/static> Require all granted </Directory> <Directory /Users/abbasahmed/Desktop/AWD/topic9/bioweb/bioweb> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess bioweb python-path=/Users/abbasahmed/Desktop/AWD/topic9/bioweb python-home=/Users/abbasahmed/Desktop/AWD/topic9/envs/bioweb_install WSGIProcessGroup bioweb WSGIScriptAlias / /Users/abbasahmed/Desktop/AWD/topic9/bioweb/bioweb/wsgi.py </VirtualHost> I also include this with the other module loading code in the config file LoadModule wsgi_module /usr/local/lib/httpd/modules/mod_wsgi.so I'm facing an issue with Apache and mod_wsgi on macOS. The error suggests a problem with the library path (@rpath/libpython3.9.dylib). How can I resolve this issue and successfully load mod_wsgi.so into the Apache server? I uninstalled and installed mod_wsgi with the correct python version but I still get an error -
Setting up pytest django database
I need to run this SQL after the test database is created but before creating any tables: `CREATE EXTENSION pg_trgm; CREATE EXTENSION btree_gin; I know that I can somehow use django_db_setup fixture to do this but I can't figure out how. I use addopts = --no-migrations in my pytest.ini file so this can't be done using migrations It should be something like this: @pytest.fixture(scope='session') def django_db_setup(): # Some code to create database with connection.cursor() as cursor: cursor.execute('CREATE EXTENSION IF NOT EXISTS pg_trgm;') cursor.execute('CREATE EXTENSION IF NOT EXISTS btree_gin;') # Code for creating tables -
AJAX call to Django View returns None
I trying to get data which I send with AJAX base.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script> function getAjaxResponse() { console.log('myAjax'); $.getJSON('/ajax', { get_param: 'data' }, function(data) { $.each(data, function(key, val) { console.log(key); console.log(val); }); }); } $(function(){ $("input[name='barcode']").change(function() { var barcode = document.getElementById("id_barcode").value; $.ajax({ type:'GET', url:`ajax/?variable=${barcode}`, headers: {'X-CSRFToken': '{{ csrf_token }}'}, success: function(response){ console.log('success'); console.log(barcode); setTimeout(getAjaxResponse, 3000); }, error: function (response){ console.log('error'); } }); }); }); </script> urls.py path('ajax/', views.ajaxBarcode, name='ajaxBarcode'), views.py def ajaxBarcode(request): barcode = request.GET.get('variable') dict = {} if len(str(barcode)): dict['hint1'] = str(barcode) return JsonResponse(dict) When I retrieve data in browser I always had hint1 and None. But when I type in address line /ajax/?variable=115 I have response {"hint1": "115"} -
How to create a form that updates multiple field for multiple user simultaneously in Django?
I want to create a form that able to take multiple respond and update the database for multiple instances. Here is my case: I have 2 models, Members and Cash class Members(models.Model): nim = models.IntegerField(default=0) name = models.CharField(max_length=40) position = models.CharField( max_length=30, choices=POSITION_OPTION, ) year = models.IntegerField() program = models.CharField(max_length=30) potrait = models.CharField(max_length=100, default='NO PHOTO') class Cash(models.Model): name = models.ForeignKey(Members, on_delete=models.CASCADE) jan = models.BooleanField(default=False) feb = models.BooleanField(default=False) mar = models.BooleanField(default=False) apr = models.BooleanField(default=False) may = models.BooleanField(default=False) jun = models.BooleanField(default=False) jul = models.BooleanField(default=False) aug = models.BooleanField(default=False) sep = models.BooleanField(default=False) The logic behind this model is, each Member has their record of Cash. So my end goal is to sum the number of True in each Member and determine how much cash they have deposited to the organization. Back to the topic, I want to create a form page that is formed like tables, NIM January February So on... 010456 [ ] (checkbox) [ ] (checkbox) So on... ----------- --------------------------- --------------------------- ------------------ 010457 [ ] (checkbox) [ ] (checkbox) So on... <button>UPDATE RECORD</button> But I'm stuck at figuring out how to connect this multiple form to multiple user at once. The alternative way I can achieve my end goal is to create … -
Test (selenium) Google Oauth login on my Django website
On our login screen we have a Google login. But when I try to test it with Selenium I get an error at Google saying: "device_id and device_name are required for private IP: http://..../accounts/google/login/callback/" Error 400: invalid_request. Now I have (I think) 2 options: Make it so the request is valid. Check the request we send to Google to see if it is valid Oauth and fake a response that back. But I have no idea how to do them and which one is better then the other one. The request we send to google has this payload: "client_id": "redirect_uri": "scope": "response_type": "state": "access_type": <!--begin::Google link--> <a href="{% provider_login_url "google" %}" class="btn btn-flex flex-center btn-light btn-lg w-100 mb-5"> <img alt="Logo" width="28" height="28" src="{% manifest "media/svg/brand-logos/google-icon.svg" %}" class="h-20px me-3" /> {% trans "Continue with Google" %} </a> <!--end::Google link--> When I tried clicking in the Selenium browser on the google I Expected for it to show the normal google login. Instead of the normal google login I got an error. -
Page not found (404) No Profile matches the given query. using django multi tenants
I am encountering a 404 error with the message "No Profile matches the given query" when trying to access the crm_details view with profile IDs higher than 4 in a multi-tenancy Django application views.py def crm_details(request, profile_id): if request.user.is_authenticated: tenant = Tenant.objects.get(schema_name=request.tenant) # Fetch the current tenant profile = get_object_or_404(Profile, id=profile_id, tenant=tenant) # Filter by tenant crm_instance = crm.objects.filter(person_detail=profile, tenant=tenant).first() # Filter by tenant properties = AddProperty.objects.filter(tenant=tenant) if request.method == 'POST': form = crmForm(request.POST, instance=crm_instance) if form.is_valid(): crm_entry = form.save(commit=False) crm_entry.person_detail = profile crm_entry.save() else: form = crmForm(instance=crm_instance) context = { 'profile': profile, 'crm_form': form, 'properties': properties } return render(request, 'crm_details.html', context) return redirect("blog:user_login") def create_profile(request): if request.user.is_authenticated: tenant = Tenant.objects.get(schema_name=request.tenant) # Fetch the current tenant if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.tenant = tenant # Associate the profile with the current tenant profile.save() return redirect('blog:profile_list') else: form = ProfileForm() return render(request, 'create_profile.html', {'form': form}) return redirect("blog:user_login") def add_property(request): if request.user.is_authenticated: tenant = Tenant.objects.get(schema_name=request.tenant) # Fetch the current tenant if request.method == 'POST': form = AddPropertyForm(request.POST, request.FILES) if form.is_valid(): property_instance = form.save(commit=False) property_instance.tenant = tenant # Associate the property with the current tenant property_instance.created_by = request.user property_instance.save() return redirect('blog:property_list') else: form = AddPropertyForm() else: … -
how to make a Clickmap on a Django application?
`Hello! I'm building an application with django and I need to make a clickmap/heatmap to get some statistics from my site. My problem: almost all the forms are out of date and I don't want to use Google Analytics or anything like that. I need a visual map that shows me where users are clicking, the most accessed pages, etc. Things i tried: https://django-analytical.readthedocs.io/en/latest/ clickmap.js https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-setup` -
I cant add Products to admin
Im having some errors updating products in my Django adminthe error that shows up whenever I try to add a new product it keeps telling me to return to my django root file and make some changes{Error that comes up} I was expecting a successful operation that says product added successfully OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Python\Python37\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\Admin\Desktop\Afresh', 'C:\Python\Python37\python37.zip', 'C:\Python\Python37\DLLs', 'C:\Python\Python37\lib', 'C:\Python\Python37', 'C:\Python\Python37\lib\site-packages'] Server time: Thu, 25 Jan 2024 11:31:08 +0000 -
Django-Python easy way to convert PPTX to PDF?
I have tried several libraries for convert a PPTX file to PDF and all of them gives me error. For example I am trying to use an API of SDK python of GroupDocs, this is my method: def generate_and_save_pptx(self): pptx_template_path = ‘panel/templates/originals/Prueba.pptx pdf_filename = f’{self.client.name} - {self.type_submission.name}_tutorial.pdf’ pdf_path = submission_directory_path(self,pdf_filename) api_instance = groupdocs_conversion_cloud.ConvertApi.from_keys(app_sid, app_key) convert_request = groupdocs_conversion_cloud.ConvertDocumentDirectRequest( "pdf", pptx_template_path, # Reemplaza con la ruta correcta a tu archivo None, None, None ) try: response = api_instance.convert_document_direct(convert_request) with open(pdf_path, "wb") as pdf_file: pdf_file.write(response) Debugging it looks like I cant even enter into response. On the other hand it says folder doesnt exist but it exists, I save other files there without problem. Any other libraries I have tried always have similar problemas, not enter into the response, save data corrupted, etc. I just would like to find and easy and free way to convert pptx files to pdf -
logout in drf api browsable it shows HTTP ERROR 405
I perform logout and login operations in Djnago Rest Framework. I logout using drf api browsable it shows HTTP ERROR 405 my version is Django==5.0.1 when i decrease version Django==3.2.10 it works perfect Is there any solution in Django==5.0.1 to resolve this issue ? -
Fire & Forget Asyncio
I've been scouring the web to an answer to this question but I can't seem to find an actual answer or maybe i'm just missing it. I'm trying to fire off a post request to start another microservice and I don't care what response comes back as that goes to a different part of my architecture Once the request is sent I want to essentially continue the code a return this random json to where the function is called. For some reason whenever I use asyncio.run() it starts the send_requests() function but waits for it to respond before continuing. Which is how async works i this case I think. But i'm unsure how to continue and exit the function before waiting for a response Here's the pseudo code Class DummyClass: def do_something(): "doing something...." asyncio.run(send_requests) return "random string" async def send_request(): try: requests.post("send to url") except: raise Issue I can use a decorator def fire_and_forget(f): @wraps(f) def wrapped(*args, **kwargs): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) if callable(f): return loop.run_in_executor(None, f, *args, **kwargs) else: raise TypeError("Task must be a callable") return wrapped which works fine but just wondering if we can do it without the decorator! I think I might be slightly misunderstanding … -
Django use F() to the jsonField and there is json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
this is the code class Helo(models.Model): id = models.IntegerField(primary_key=True) aa = models.JSONField(null=True) bb = models.JSONField(null=True) one example data is this: id aa bb 1 {"p1":11 "p2": 22} {"p1": 33, "p2": 44} and i run this code test=Helo.filter(aa__p1__gte = F('bb__p1')) test.count() get these error message json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) i also tried the test=Helo.filter(aa__p1__gte = F('bb')) test.count() and there is no error, i wonder why i cant use the F('bb__p1') -
Django DATE and DATETIME settings have no effect since USE_L10N was deprecated
Since 5.0 USE_L10N settings was DEPRECATED and is always True. Now settings like DATE_FORMAT, DATETIME_FORMAT, DATE_FORMAT_INPUTS etc.. don't work because as per documentation: Note that the locale-dictated format has higher precedence and will be applied instead. But now locale-dictated formats are always enabled. A fix I've found is to copy the formats.py file you want to in your app's directory. The path should look like <your_project>/<your_app>/formats/ro/formats.py then in settings.py you can set: LANGUAGE_CODE = 'ro-RO' FORMAT_MODULE_PATH = ['yourapp.formats',] But why have those settings anymore? Is there any way in which you can still use those settings? -
How to add an accordion in djnago admin in the change_list.html template?
I want to change the default table in the django admin, which is displayed in the template change_list.html. While retaining all the functionality that django provides. The idea is to make the table in the form of an accordion, where there will be a button "Collapse" and "Expand". In the case of clicking the button "Expand" will expand the column with the associated record and all its data Can you tell me how to implement such functionality, I will be glad to receive any suggestions? In simpler words, how to add the action "view_data" and when you click "Open" button the accordion will open and show all the data related to the record table -
how to solve CORS error in react and django
i am trying to creat log in app using Django and react . my js : const client = axios.create({ baseURL: "http://127.0.0.1:8000"}); //my submitRegistration function function submitRegistration(e) { e.preventDefault(); client.post( //every time I got cors error here// "/api/register", { email: email, username: username, password: password } ).then(function(res) { client.post( "/api/login", { email: email, password: password } ).then(function(res) { setCurrentUser(true); }); });} django cors setup: CORS_ALLOWED_ORIGINS = [ 'http://localhost', 'http://127.0.0.1', 'http://0.0.0.0', ] CORS_ALLOW_CREDENTIALS = True I dont know why I got cors error here.any suggestion please! -
What is this little note below DateField that is displayed in Django Admin?
Hi I have defined a CD Model in my models.py file in my app and linked it to the admin page. However, I noticed this little note below the Date field. 'You are 8 hours ahead of server time'. What does it mean? I tried finding information about it but still couldn't get a good understanding of it. -
python dict weird assign of a key value (multiple keys are created)
I run the following code (django framework, but it doesn't seem relevant) def asignador(self) -> dict: try: a_asignar = deepcopy(list(self.materias)) dict_mezclado = deepcopy(Biotcher.mezclador(self.dict_de_asignaciones)) divisiones_mezcladas = deepcopy(Biotcher.mezclador(self.divisiones_habilitadas_por_materia)) shuffle(a_asignar) nueva_grilla = deepcopy(self.grillas) for materia_a_asignar in a_asignar: materia_a_asignar = a_asignar[0] division_asignada = divisiones_mezcladas[materia_a_asignar.materia.pk][-1] ##### horas_div = materia_a_asignar.materia.horas_por_semana for _ in range(horas_div): dia, hora = dict_mezclado[division_asignada][-1] print(nueva_grilla[division_asignada]) nueva_grilla[division_asignada][dia][hora]['mat'] = materia_a_asignar.materia.nombre print(nueva_grilla[division_asignada]) dict_mezclado[division_asignada].pop(-1) divisiones_mezcladas[materia_a_asignar.materia.pk].pop(-1) return nueva_grilla except Exception: print('EXCEPCION') print(nueva_grilla) The first print I obtain {1: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 2: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 3: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 4: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 5: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}} and in the second one {1: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 2: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 3: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 4: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, … -
I am tying to create .exe for my django I used python freeze_script.py build but I'm getting error
# freeze_script.py import os import sys from cx_Freeze import setup, Executable from django.core.management import call_command from django.core.wsgi import get_wsgi_application # Manually configure Django settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DVE.settings') # Replace 'your_project_name.settings' with your actual settings module application = get_wsgi_application() # Your Django project name (replace 'your_project_name' with your actual project name) project_name = 'DVE' base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable("manage.py", base=base) ] # Call the 'migrate' command before freezing call_command("migrate") # Freeze the application build_options = { 'packages': ['DVE','TOOL', 'django', 'gunicorn'], 'includes': ['django.template.backends', 'django.templatetags.i18n'], } setup( name="TOOL", version="1.0", description="TOOL", options={"build_exe": build_options}, executables=executables ) Traceback (most recent call last): "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\cx_Freeze\initscripts_start up_.py", line 124, in run File module_init.run(name + "main_") File "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\cx_Freeze\initscripts\consol e.py", line 16, in run exec(code, module_main.dict_) File "manage.py", line 22, in <module> File "manage.py", line 18, in main File "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\django\core\management\ init_.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\django\core\management\ init_.py", line 424, in execute sys.stdout.write(self.main_help_text() + "\n") AttributeError: "NoneType' object has no attribute 'write' this is the error your text -
How to save information in two different tables in Django?
I have a django application where I can open a form with fields (client and services) rendered (form) and save it in a single table. I decided to separate the customer data in another table, so as not to have the same customer saved more than once in the services table. It turns out that I don't know how to apply this reasoning in practice. Below is the view responsible for the n ew registration. @login_required def NovaOS(request): if request.method == 'POST': form = OrdemServicoForm(request.POST) if form.is_valid(): OS = form.save(commit=False) OS.user = request.user OS.save() return redirect('/os/list/') else: form = OrdemServicoForm() return render(request, 'serviceorders/addos.html', {'form': form}) I have already created the necessary information in forms.py and models.py. forms.py class ClienteForm(forms.ModelForm): class Meta: model = Clientes fields = '__all__' widgets = { #Dados do cliente 'STATUSCliente': forms.Select(attrs={'class': 'form-control', 'placeholder': 'Status'}), 'cliente_razaosocial': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Razão Social', 'autofocus': True}), 'cliente_cpfcnpj': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'CPF/CNPJ'}), 'cliente_rgie': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'RG/I.E.'}), 'cliente_email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'E-mail'}), 'cliente_telefone_fixo': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tel. fixo', 'data-mask':"(00)0000-0000"}), 'cliente_telefone_celular': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tel. celular', 'data-mask':"(00)00000-0000"}), 'cliente_endereco': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Endereço'}), 'cliente_endereco_num': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Número'}), 'cliente_endereco_CEP': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'CEP'}), 'cliente_endereco_Bairro': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Bairro'}), 'cliente_endereco_Cidade': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Cidade'}), … -
What do I need to do to fix a 404 error in django
I'm new to studying Django and I'm doing a task and I have to display a message with the url "http://127.0.0.1:8000/blog/". But when I search with this url, the error "Page not found (404) is displayed Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Using the URLconf defined in project1.urls, Django tried these URL patterns, in this order: admin/ The current path, blog/, didn’t match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.", Could anyone offer me help? A message chosen by the teacher would have to appear, but I only have the error as a response. -
django rest framework serializer.data throws error about attribute in manytomany relationship
I have the following models: class MenuItem(models.Model): class Category(models.TextChoices): PIZZA = "pizza" SIDE = "side" OTHER = "other" name = models.CharField(max_length=40) description = models.TextField(max_length=150) price = models.FloatField(default=0.0) category = models.CharField(max_length=50, choices=Category.choices, default=Category.OTHER) class Order(models.Model): class OrderStatus(models.TextChoices): NEW = "new" READY = "ready" DELIVERED = "delivered" customer = models.CharField(max_length=50) order_time = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField(MenuItem, through='OrderItem') status = models.CharField(max_length=50, choices=OrderStatus.choices, default=OrderStatus.NEW) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() And the following serializers: class MenuItemSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=40) description = serializers.CharField(max_length=150) price = serializers.FloatField(default=0.0) category = serializers.CharField(max_length=50) def create(self, validated_data): return MenuItem.objects.create(**validated_data) class OrderItemSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) menu_item_id = serializers.PrimaryKeyRelatedField(queryset=MenuItem.objects.all(), source='menu_item', read_only=False) quantity = serializers.IntegerField(min_value=0) class OrderSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) customer = serializers.CharField(max_length=50) order_time = serializers.DateTimeField(read_only=True) items = OrderItemSerializer(many=True) def create(self, validated_data): order_items_data = validated_data.pop('items') order = Order.objects.create(**validated_data) for order_item_data in order_items_data: quantity = order_item_data.pop('quantity') menu_item = order_item_data.pop('menu_item') OrderItem.objects.create(order=order, quantity=quantity, menu_item=menu_item) return order And then in views: @csrf_exempt def order(request): if request.method == 'POST': data = JSONParser().parse(request) serializer = OrderSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) print(serializer.errors) return JsonResponse(serializer.errors, status=400) An example request looks like: echo -n '{"customer": "John Doe", "items": [{"menu_item_id": 1, "quantity": 2}, {"menu_item_id": 2, "quantity": 1}]}' | http POST http://127.0.0.1:8000/order … -
How to quickly revert a Django migration?
I wrote a trivial new app in Django and after I ran ./manage.py migrate myapp, I realized I wanted to add some new fields. Since it's a new app, I want to update my original migration and not create a second migration, so I ran .manage.py migrate myapp zero to completely revert all migrations for the app. However, even though it took Django about 5 seconds to initial apply my single migration, after 30 minutes of processing, it still hasn't been able to revert the migration. I've killed all other connections to my local database, so I don't think it's waiting for anything. Yet top says Django's manage.py is hogging about 75% of my CPU. My app only has three simple models, with a FK relation between them in a Parent<-Child<-Grandchild relationship, and there are no records in any of the tables. I'm using a PostgreSQL backend. Why is Django so inefficient at removing a migration for tables with no records? -
UserAdmin save_model not triggering on password change
I want to end the users session when ever the password is changed through the admin site (see screenshot). I did a research and it suggests to override the save_model and write the custom logic to end the session @admin.register(User) class UserAdmin(UserAdmin): def save_model(self, request, obj, form, change): print("HERE") ... The problem is that for some reason save_model never triggers (tried debugging as well). Both User and UserAdmin are properly registered, otherwise I wouldn't even be able to access the Change Password page. Version: Django 4