Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Infinite POST request on uploading file with Django
I try to upload some files to a server through a web interface with Django. HTML : <form method="post" enctype="multipart/form-data" name="upload_file"> {% csrf_token %} <input type="file" name="uploaded_file_list" multiple> <button class="rounded-full bg-violet-200 text-violet-700 block p-2" name="upload_file" value="dummy" type="submit">Ajouter des fichiers</button> </form> views.py def media_manager(request): file_manager = MediaManager.server.FileManager(django.conf.settings.USER_FILE_ROOT) # POST utilisé pour associer les tags aux images if request.method == "POST": print(request.POST) if request.POST.get("upload_file"): for uploaded_file in request.FILES.getlist("uploaded_file_list"): file_manager.add_file(uploaded_file) context_dict = {} context_dict["filtered_file_list"] = MediaManager.filters.ImageFilter(request.GET, queryset=MediaManager.models.UserImage.objects.all()) return django.shortcuts.render(request, "MediaManager/media_manager.html", context=context_dict) FileManager.py def add_file(self, uploaded_file): file_system_storage = django.core.files.storage.FileSystemStorage(location=self._user_dir_absolute_path) file_system_storage.save(uploaded_file.name, uploaded_file) FileManager also updates context_dict["filtered_dile_list"] with the files uploaded. When I upload a file on the browser, the file is correctly uploaded and the web display also correctly add it on the page. I can see the upload POST request. But this operation is repeated infinitely. Here is the log (with a request.POST print) : <QueryDict: {'csrfmiddlewaretoken': ['vCHAoeGg3QVIZDuHAls8lmV7Y8MXHqxGeWQj16N2zJcCUfoML4pVcnsmJGk7R5Er'], 'upload_file': ['dummy']}> [02/Nov/2022 22:03:23] "POST /media_manager/ HTTP/1.1" 200 19214 1 static file copied to '/home/gautitho/workspace/MonPetitNuage/MonPetitNuage/static', 185 unmodified. <QueryDict: {'csrfmiddlewaretoken': ['vCHAoeGg3QVIZDuHAls8lmV7Y8MXHqxGeWQj16N2zJcCUfoML4pVcnsmJGk7R5Er'], 'upload_file': ['dummy']}> [02/Nov/2022 22:03:24] "POST /media_manager/ HTTP/1.1" 200 19580 [02/Nov/2022 22:03:24] "GET /static/MediaManager/user/Couleurs-logo-Overwatch.jpg HTTP/1.1" 200 63919 1 static file copied to '/home/gautitho/workspace/MonPetitNuage/MonPetitNuage/static', 186 unmodified. <QueryDict: {'csrfmiddlewaretoken': ['vCHAoeGg3QVIZDuHAls8lmV7Y8MXHqxGeWQj16N2zJcCUfoML4pVcnsmJGk7R5Er'], 'upload_file': ['dummy']}> [02/Nov/2022 22:03:25] "POST /media_manager/ HTTP/1.1" 200 19959 … -
How do I get and pass context from one form to another based on primary/foreign key fields?
I am currently building a website that will allow the sale of mixing and mastering services. As it is a small set of services, I don't need a shopping cart or any elaborate form of ordering. Instead, I would like a customer details page (which informs my 'Customer' model), an order page where the customer selects what exactly they will be purchasing and uploads any relelvent files (which also informs my 'Order' model), and finally sends the customer to a stripe checkout page. Currently, the Custome rdetails form is up and running and saving the data to the appropriate database model. Once they click continue, I am struggling to understand how to store the primary key of the Customer instance the user created upon filling out the form, and saving this data in the next form through the foreign key relationship. Similarly, before being sent to Stripe checkout, I would like to create an 'Order Review' page, reviewing the details of their order. I'm not sure how to pull the primary key of the Order intance that was just created in order to for a Model view on the subsequent page. I believe what I;m missing in order to achieve … -
How do I render a PDF in Django using FileResponse
I have a simple function to Open a PDF file, I want to render it within my Django as part of a POST function. def view_pdf(request, pdfpath): filename = pdfpath.replace('\\', '/') name = filename.split('/')[-1] if os.path.exists(filename): response = FileResponse(open(filename, 'rb'), content_type='application/pdf') response['Content-Disposition'] = f'inline; filename={name}' # user will be prompted display the PDF in the browser # response['Content-Disposition'] = f'filename={name}' # user will be prompted display the PDF in the browser return response else: return HttpResponseNotFound('Cannot find the PDF') My view calls this with return view_pdf(request, pdfpath) How do I actually get this to open as a new Tab ? The HTML has a submit button that calls some ajax functions <button type="submit" onclick="window.submitPAGE()" class="btn waves-effect waves-light btn-primary"><i class="fa fa-print"></i></button> So I cant turn it into a FORM because I cant pass the data form the function <form method="POST" target="_blank"> <button type="submit" class="btn waves-effect waves-light btn-primary"><i class="fa fa-print"></i></button> -
Update data in table which has foreign keys in Django
I have two tables where one is connected to the other with a foreign key. The model store_table already consists of three rows, for three different stores. I am now trying to update the model price_table but I am not quite sure that I understand how to utilize the foreign keys, so that it knows which price_table item to be connect to which store_table id. Any suggestions out there on how to achieve this? My two models class store_table(models.Model): store = models.CharField(max_length=100, null=True) number = models.BigIntegerField(null=True) class Meta: unique_together = ( ( "store", "number", ), ) class price_table(models.Model): price = models.CharField(max_length=100, null=True) dates = models.DateField(null=True, blank=True) store_id = models.ForeignKey( store_table, on_delete=models.CASCADE, default=None ) class Meta: unique_together = ( ( "dates", "price", ), ) My code update_models = price_table( dates=dates, price=price ) update_models.save() -
How i can get JSON list without attributes ("count": 3, "next": null, "previous": null, "results":)
I have JSON like this: {"count":3,"next":null,"previous":null,"results":[{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11-02"},{"name":"qwe","slug":"qwe","directions":["Surgery","X-Ray","Stomach"],"description":"Xray","work_experience":"6","birt_date":"2022-11-14"}]} And I want to get JSON like this [{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11-02"},{"name":"qwe","slug":"qwe","directions":["Surgery","X-Ray","Stomach"],"description":"Xray","work_experience":"6","birt_date":"2022-11-14"}] -
View is returning an HttpResponse, but says it returns None
I have a button in one of my views that triggers a function "compileUpdate" and then returns a file as a response. This was working previously but now I receive the error: "ValueError: The view didn't return an HttpResponse object. It returned None instead." The block of code below essentially: Gets the correct campaign Formats the path of the files to compile Checks if a specific directory exists, and if not creates it Calls the compileUpdate function Returns the file as a http response Non-working file creation and response if req == "Bulk Update": cmp_id = request.headers.get('cmp') campaign = Campaign.objects.get(id=cmp_id) parent_dir = os.path.normpath(os.getcwd() + os.sep + os.pardir) submittedFolder = os.path.join(parent_dir, "SubmittedReviews", "", str(cmp_id) + "-" + campaign.system.name, "") cmp_files = glob.glob(os.path.join(submittedFolder,'*')) archive = os.path.join(parent_dir, "Archive", "", str(campaign.id) + "-" + campaign.system.name, "") if os.path.exists(archive) == False: os.mkdir(archive) bulk_update = os.path.join(archive, str(campaign.id) + "-" + campaign.system.name + "_bulk_update.csv") print(bulk_update) with open(bulk_update, 'w') as bulk_out: writer = csv.writer(bulk_out) compileUpdate(cmp_files, campaign, writer) bulk_out.close() time.sleep(2) file = str(bulk_update).split("/")[-1] with open(bulk_update, 'rb') as fh: response = HttpResponse(fh.read()) response['Content-Type'] = 'application/vnd.ms-excel' response['Content-Disposition'] = 'inline; filename="{}"'.format(os.path.basename(bulk_update)) response['X-Accel-Redirect'] = f'/archive/{file}' return response As mentioned above, this errors out saying that I am returning None rather than an http … -
How to submit an update form and create form at the same time in Django?
I am trying to update a model "Stock", then create a new "StockTransaction" at the same time. I want to accomplish this using two different forms submitted together. I am able to get the stock update transaction to work, but when I try to is_valid() on the transaction form, it always returns false. I can't figure out why it is returning false. here are all of the relevant code sections that are used. Any help is appreciated. Thank you in advance! def buyStock(request, pk): stock = Stock.objects.get(id=pk) form = StockForm(instance=stock) tform = StockTransForm() if request.method == 'POST': form = StockForm(request.POST, instance=stock) form.instance.buyPrice = stock.ticker.price form.instance.dateOfPurchase = date.today() form.instance.forSale = False tform.instance.stockID = stock.stockID tform.instance.buyPrice = stock.buyPrice tform.instance.sellPrice = stock.ticker.price tform.instance.broker = form.instance.broker tform.instance.buyer = form.instance.ownerID tform.instance.seller = stock.ownerID tform.instance.ticker = stock.ticker if form.is_valid() and tform.is_valid(): form.save() tform.save() class StockTransaction(models.Model): transactionID = models.AutoField(primary_key=True) ticker = models.ForeignKey(PublicCompany, on_delete=models.CASCADE, default=None, related_name='stocktrans-ticker+') stockID = models.IntegerField() buyer = models.ForeignKey(FinancialAccount, on_delete=models.PROTECT, default=None, related_name='stocktrans-buyer+') seller = models.ForeignKey(FinancialAccount, on_delete=models.PROTECT, default=None, related_name='stocktrans-seller+') sellPrice = models.DecimalField(max_digits=7, decimal_places=2) buyPrice = models.DecimalField(max_digits=7, decimal_places=2) date = models.DateField(auto_now_add=True) broker = models.ForeignKey(Agent, on_delete=models.PROTECT, default=None, related_name='stocktrans-broker+') class Stock(models.Model): ownerID = models.ForeignKey(FinancialAccount, on_delete=models.CASCADE, default=None, related_name='stock-owner+')#on delete maybe change buyPrice = models.DecimalField(max_digits=7, decimal_places=2) broker = models.ForeignKey(Agent, on_delete=models.PROTECT, default=None, … -
Django Model: how to find list of auto-generated fields
Is there any Django built-in function that return a list of all auto-generated fields from a Django model? Something like: MyModel._meta._get_auto_generated_fields() -
Django - How can I make a list of the choices I've selected in manytomany?
I'm trying to make a list of the choices I've selected. In this case, the logged in Gestor will select the Funcionarios, and will be able to view the list of selected employees. **models.py ** class Equipe(models.Model): gestor = models.ForeignKey(Gestor, on_delete=models.PROTECT, default="") funcionario = models.ManyToManyField(User) def __str__(self): return self.nome def get_funcionario(self): return "\n".join([p.funcionario for p in self.funcionario.all()]) views.py def listaFuncionario(request): gest = Gestor.objects.get(user_id = request.user.id) equipe = Equipe.objects.filter(gestor_id = gest) equipes = gest.equipe_set.all() func = equipes.funcionario.all() context = {'func':func} return render(request, 'listaFunc.html', context) I try, but it doesn't seem to access the selected Funcionarios table I try but shows me func = equipes.funcionario.all() AttributeError: 'QuerySet' object has no attribute 'funcionario' [02/Nov/2022 15:15:06] "GET /funcionarios HTTP/1.1" 500 65882 n -
How to take elevate or run function as administrator in Django
I have a django project and I want to do operation on hosts file in windows but I am not able to do that because it is read only file so how can I do that any suggestion. So, I am expecting any solution so that I can able to make changes in the host file. I am thinking to make my django project able to run as administrator. -
Django navbar css doesn't make any changes
It's probably not about static files configuration because images work and CSS other than navbar's work, navbar's CSS doesn't make any changes it's just like it's not there, even though when I tried to make a simple h1 and color it (as a test) it worked, it's just the navbar's CSS for some reason that I really can't figure out. base.html: {% load static %} <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> </head> <body> {% block navbar %} {% include 'parts/navbar.html' %} {% endblock navbar %} {% block content %} {% endblock content %} </body> </html> homepage.html: {% extends 'base.html' %} {% load static %} {% block content %} {% endblock content %} navbar.html: <head> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}" /> </head> <div class="navContainer"> <div class="navbar"> <img src="{% static 'images/navLogo.png' %}" class="logo" /> <nav> <ul> <li><a href="">Home</a></li> <li><a href="">About</a></li> <li><a href="">Projects</a></li> </ul> </nav> </div> </div> static configuration in settings.py: STATIC_ROOT = path.join(BASE_DIR, 'static') STATIC_URL = 'static/' STATICFILES_DIRS = [ path.join(BASE_DIR, 'staticfiles') ] app's urls.py: from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ … -
suddenly datetime indexing field selection became longer
I have partition table with datetime field indexing In django orm i have 2 variant of requests First variant MyModel.objects.filter(my_datetime_field__gt=date(2022, 1 , 1)) This request is being made 3.5-5 seconds Second variant MyModel.objects.filter(my_datetime_field__date__gt=date(2022, 1 , 1)) This request is being made 0.05 seconds Question Previously, requests were completed in the same time. What could have happened? Some information django: 2.0 postgres: 12.3 index_type: btree I try next VACUUM (VERBOSE, ANALYZE) my_table REINDEX INDEX my_index -
How to find history of commands run on mysql
I sort of have a heart attack of a problem. I had a non-root utility user in mysql that used to be able to see all the databases, tables, etc. on the mysql instance. The user was able to insert records, delete records, create tables, etc. too. This user is used by scripts to edit records, or view the data as someone who's not root via phpmyadmin. I don't know how Django fits into this or if it was even the cause but a contractor needed access to the db to work on their project we asked them to work on. They said they were using Django and needed to create some auth tables in the database (auth_group, auth_user, auth_user_groups, etc.) However, after they added their tables for Django, that user can't see anything except the "information_schema" database. Luckily, I checked using the root user in mysql and can see the databases but somehow, the viewing privileges are removed from the non-root user. I want to see what commands the contractor ran to get us into this situation to tell them not to do this again. I was going to check the .mysql_history file in the unix root user directory … -
I get a 404 error when passing as a parameter to the path an int that is a foreign key
This is the url i am trying: http://localhost:8000/blog/categoria/1/ The foreign key is categoria_id that comes from relationship many to many of Post and Categoria. I am using Sqlite3. This file is the models.py from django.db import models from django.contrib.auth.models import User class Categoria(models.Model): nombre=models.CharField(max_length=50) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='categoria' verbose_name_plural='categorias' def __str__(self): return self.nombre class Post(models.Model): titulo=models.CharField(max_length=50) contenido=models.CharField(max_length=50) imagen=models.ImageField(upload_to='blog', null=True, blank=True) autor=models.ForeignKey(User, on_delete=models.CASCADE) categorias=models.ManyToManyField(Categoria) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='post' verbose_name_plural='posts' def __str__(self): return self.titulo This file is the views.py: from django.shortcuts import render from blog.models import Post, Categoria def blog(request): posts=Post.objects.all() return render(request, "blog/blog.html",{"posts":posts}) def categoria(request, categoria_id): categoria=Categoria.objects.get(id=categoria_id) posts=Post.objects.filter(categorias=categoria) return render(request, "blog/categoria.html",{'categoria': categoria, "posts":posts }) This file is the urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.blog, name='Blog'), path('categoria/<int:categoria_id>/', views.categoria, name="categoria") ] -
model inheritance authentication on several children
I would like to have opinions on how to proceed to set up my models. I have a father entity which has two sons simpleman and superman. Both can authenticate but simpleman does not have access to all pages and other limitations. To highlight simpleman I had thought of adding a method that returns true I would like to know do I have to create a Father model with its attributes and its primary key (regNumber: CharField) then with this children I would put this primary key in foreign key ? In the code i think to do this: class Superman(AbstractBaseUser): #regNumber = models.CharField(..., primary_key=True) ... # other property objects = customManagerSuper() # where user.is_admin=True and user.is_superuser=True class Simpleman(AbstractBaseUser): #regNumber = models.CharField(..., primary_key=True) ... # other property objects = customManagerSimple() # where user.is_admin=False and user.is_superuser=False def heIsSimple(self): return True How will authentication work? How could I get him to look in the right table? To limit access to certain page for the simpleman I had thought of setting up a decoration like this in my views.py @user_passes_test(lambda user: u.heIsSimple()) -
how to display defalt value radio button in django form
My form allows the user to select between two roles. I struggle to understand why I cannot display it in the template. The model role default value, and the form role initial values, are both set to 'regular_user'. The models ae migated and the om values ae displayed as needed, but without the deault value. Any input on what I'm doing wrong would be highly appreciated. models.py: ROLES = (('regular_user', 'Regular_user'), ('collaborator', 'Collaborator')) class CustomUser(AbstractUser): display_name = models.CharField(verbose_name=("Display name"), max_length=30, help_text=("Will be shown e.g. when commenting")) ... role = models.CharField(choices = ROLES, max_length = 50, default = 'regular_user', help_text =("Click below Collaborator, if you wish to join us")) ... class Meta: ordering = ['last_name'] def get_absolute_url(self): return reverse('account_profile') def __str__(self): return f"{self.username}: {self.first_name} {self.last_name}" Forms.py: class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label=_("First name")) ... role = forms.ChoiceField(choices=ROLES, widget=forms.RadioSelect(), label="Role", required=True, help_text=_("Click below 'Collaborator', if you wish to join us")) ... def signup(self, request, user, **kwargs): ... user.role = self.cleaned_data['role'] ... user.save() If I render it with all other form fields like: {% with "form-control input-field-"|add:field.name as field_class %} {% render_field field class=field_class %}{% endwith %} It renders without radio widget that cannot be checked. When I render the role field separately, … -
Django passing references to request/user django.contrib.auth.models
In this example Django code, how is request able to reference user? And user able to reference profile? p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) -
problemas con heroku
tengo un problema con heroku, ya se desplego la pagina pero al momento deentrar solo dice internal server error. ayuda, tengo 2 meses desplegando esta pagina https://watchalo.herokuapp.com/ intente desplegarla dos veces pero no pude hacer nada -
is there a way to diable django abstract base user is_staff and is_superuser fields
Is there a way to disable is_staff and is_superuser abstractbaseuser fields and instead use one user_role choice field to handle all permissions. -
Django and Celery testing issue
I use Celery in my Django (DRF) app to perform async tasks. Everything works fine, except the testing. The problem seems to be related to the APITestCase that it is executed before the Celery APITransactionTestCase deleting the database. Here a representative code: test_drf_views.py class DRFTestCase(APITestCase): @classmethod def setUpTestData(cls): ''' Init database ''' from myapp.init import init_data # this loads the database def setUp(self): self.login = reverse('login') # ... just a setup def test_foo(self): # ... just a test that works fine test_celery_task.py class CeleryTaskTestCase(APITransactionTestCase): @classmethod def setUpClass(cls): super().setUpClass() app.loader.import_module('celery.contrib.testing.tasks') cls.celery_worker = start_worker(app) cls.celery_worker.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() cls.celery_worker.__exit__(None, None, None) def setUp(self): super().setUp() self.login = reverse('login') # here I call the DB and it FAIL The error I got when running pytest is: "matching query does not exists", because when the testing procedure reaches the test_celery_task.py the DB seems to be deleted. I also tried to reload the DB in the celery test, but nothing changes. Does anybody have an idea how to approach and solve the issue? -
How instanciate table in createsuperuser
I have two tables Employee and Sector, the employee table has for foreign key the sector code (sectorCode) property of the Sector table. The Employee table inherits from the AbstractBaseUser class. I would like to create a superuser with the command python manage.py createsuperuser. I get an error: ValueError: Cannot assign "'Code1'": "Employee.sectorCode" must be a "Sector" instance. (I added in the Sector table a row NameSector1; Code1) I input these values: λ python manage.py createsuperuser registrationNumber: 001 Name: TestN1 FirstName: TestFN1 sectorCode: Code1 Password: ... Error ... How can I instantiate sector class in dialog ? from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyUserManager(BaseUserManager): def create_user(self, registrationNumber, firstName, name, sectorCode, password=None): if not firstName: raise ValueError("firstName required") if not name: raise ValueError("name required") if not registrationNumber: raise ValueError("registrationNumber required") if not sectorCode: raise ValueError("sectorCode required") user=self.model(firstName = firstName, name = name, registrationNumber = registrationNumber, sectorCode = sectorCode) user.set_password(password); user.save() return user def create_superuser(self, firstName, name, registrationNumber, sectorCode, password=None): user=self.create_user(firstName = firstName, name = name, registrationNumber = registrationNumber, sectorCode = sectorCode, password = password) user.is_admin=True; user.is_superuser=True user.save() return user class Sector(models.Model): nameSector = models.CharField(verbose_name = "nameSector", max_length=50) sectorCode = models.CharField(verbose_name = "sectorCode", max_length=3, primary_key=True) class Meta: db_table … -
Why am I getting this Django custom command error: 'datetime.timezone' has no attribute 'now'
Why am I getting the error "'datetime.timezone' has no attribute 'now'" when trying to run this custom command in Django that deletes guest accounts older than 30 days? It works elsewhere in views.py where I have imported it the same way. Do I have to import it differently since the command is in a different folder? (management/commands/) from django.core.management.base import BaseCommand from datetime import timezone, timedelta from gridsquid.models import User, Tile DEFAULT_TILE_IMG_NAME = "defaultsquid.svg" MAX_GUEST_ACCOUNT_DAYS = 30 class Command(BaseCommand): def handle(self, *args, **options): """ Deletes all guest user accounts and their media if older than MAX_GUEST_ACCOUNT_DAYS """ # Get all guest accounts created before the limit expired_guests_count = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS)).count() expired_guests = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS)) for guest in expired_guests: tiles = Tile.objects.select_related("user").filter(user=guest).all() for tile in tiles: # Delete image if not default image if DEFAULT_TILE_IMG_NAME not in tile.image.url: tile.image.delete() # Delete audio file if there is one if tile.audio is not None: tile.audio.delete() # Delete guest account guest.delete() -
Django: How do you use an image in your template and let your views.py know it was pressed like a button?
I want to show an image that the user can click on that will act like a button and return the data to my views.py. For example, <input type="submit" value="Add Selected Other Service to Included Service" class="button" name="Add Other Service"/> will create a very long button which I can "grab" in my views.py with: add_other_service = request.POST.get('Add Other Service') I can then test add_other_service and term if that was the button pressed. Hence, I can have multiple buttons on the page and determine which one as pressed. I know I can use the tag with the type="image" to click on the image, but I cannot find a way to get name of the button in the views.py. -
Django - How to encapsulate multiple values in a JSON Response?
I would like to know how I can put the following JsonResponse: return JsonResponse({ 'stuff_a': stuff_a_serializer.data, 'stuff_b': stuff_b_serializer.data, 'stuff_c': stuff_c_serializer.data, }, safe=False) to something like this: return JsonResponse({ 'stuff_a': stuff_a_serializer.data, { 'stuff_b': stuff_b_serializer.data, 'stuff_c': stuff_c_serializer.data, } }, safe=False) Using the Django REST Framework. I simply want to encapsulate the result of two serializes inside the result of another to later unpack them properly at my Angular Frontend. How can I do this? Thanks in advance and kind regards :) -
Django Integration with React router dom
I am trying to serve web static files on my backend Django framework. I am using react with router Dom on my frontend and Django with rest framework. The problem now is that I am able to serve the page with route '' on Django but for other routes defined in frontend like posts are not able to be served on Django. Frontend react: App.js import React from 'react'; //import { Switch, Redirect } from 'react-router-dom'; //import { Navigate } from 'react-router-dom'; import "../stylesheets/templatemo-style.css"; // importing components from react-router-dom package // import { // BrowserRouter as Router, // Routes, // Route, // } from "react-router-dom"; import { HashRouter as Router, Route, Routes } from "react-router-dom"; // import Home component import Home from "./Home.js"; import User from "./User.js"; // import Post component import Comment from "./Comment.js"; import Post from "./Post.js"; import Account from "./Account.js"; //import User from "./components/User"; class App extends React.Component { render(){ return ( <> <div className = "App"> {/* This is the alias of BrowserRouter i.e. Router */} <Router> <Routes> <Route exaxt path = '' element={<Account/>} /> <Route path = 'posts'element={Post}/> </Routes> </Router> </div> </> ); } } export default App; And App is rendered in index.js import …