Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django views.py Exception Value: Could not parse the remainder:
Good afternoon. Tell me, please, what could be the matter - I get an Exception Value error: Could not parse the remainder: '(column)' from 'item.get(column)' views.py : def home(request): position = DjangoEmail.objects.get(Email=request.user).Position year_filter = Q(Year=now.year) | Q(Year=now.year-1) | Q(Year=now.year+1) if position == 7: data = Employee.objects.filter(year_filter, Mlkk=request.user).order_by('Year','OblastTM').values('Year', 'OblastTM', 'Category', 'ProductGroup','NameChaine').annotate(Januaru=Sum('January')) elif position == 6: data = Employee.objects.filter(year_filter, Rmkk=request.user).order_by('Year','OblastTM').values('Year', 'OblastTM', 'Category', 'ProductGroup','NameChaine').annotate(Januaru=Sum('January')) elif position == 5: data = Employee.objects.filter(year_filter, Dmkk=request.user).order_by('Year','OblastTM').values('Year', 'OblastTM', 'Category', 'ProductGroup','NameChaine').annotate(Januaru=Sum('January')) else: data = Employee.objects.filter(year_filter).order_by('Year','OblastTM').values('Year', 'OblastTM', 'Category', 'ProductGroup','NameChaine').annotate(Januaru=Sum('January')) columns = ['Year', 'OblastTM', 'Category', 'ProductGroupe', 'NameChaine','January'] removed_columns = request.GET.getlist('remove') columns = [column for column in columns if column not in removed_columns] return render(request, "home.html", {'data': data, 'columns': columns}) home.html : <table> <thead> <tr> {% for column in columns %} <th>{{ column|title }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in data %} <tr> {% for column in columns %} <td>{{ item.get(column)}}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> error : Exception Value:Could not parse the remainder: '(column)' from 'item.get(column)' Error in the line : <td>{{ item.get(column)}}</td> I tried to replace it with {{ item[column] }} - it didn't help. -
makemigrations command doesn' work in Django Project when using sqlalchemy
I took over a django project which doesn't use the models.py under /myapp folder but a customed file Models.py under /myapp/classModel using sqlalchemy. I changed the database structure in /myapp/classModel/Models.py and imported it to /myapp/models.py, then ran python manage.py makemigrations. Only to get message No changes detected . I wonder if this is the correct way to do migration? Any help is appreciated -
Hosting Firebase Django Welcome Page
I ran all the commands need like npm install -g firebase-tools firebase login firebase init firebase deploy but it still shows me the welcome screen -
Django payload before sending
This is a code to send invoice via , but I cannot enter a " for loop " loop on it to put product name and price and quantity of it , so how to deal with this to put products and other data , I tried to add for loop but it didn't work , ###########Send Payment########### baseURL = "https://apitest.myfatoorah.com" token = 'rLtt6JWvbUHDDhsZnfpAhpYk4dxYDQkbcPTyGaKp2TYqQgG7FGZ5Th_WD53Oq8Ebz6A53njUoo1w3pjU1D4vs_ZMqFiz_j0urb_BH9Oq9VZoKFoJEDAbRZepGcQanImyYrry7Kt6MnMdgfG5jn4HngWoRdKduNNyP4kzcp3mRv7x00ahkm9LAK7ZRieg7k1PDAnBIOG3EyVSJ5kK4WLMvYr7sCwHbHcu4A5WwelxYK0GMJy37bNAarSJDFQsJ2ZvJjvMDmfWwDVFEVe_5tOomfVNt6bOg9mexbGjMrnHBnKnZR1vQbBtQieDlQepzTZMuQrSuKn-t5XZM7V6fCW7oP-uXGX-sMOajeX65JOf6XVpk29DP6ro8WTAflCDANC193yof8-f5_EYY-3hXhJj7RBXmizDpneEQDSaSz5sFk0sV5qPcARJ9zGG73vuGFyenjPPmtDtXtpx35A-BVcOSBYVIWe9kndG3nclfefjKEuZ3m4jL9Gg1h2JBvmXSMYiZtp9MR5I6pvbvylU_PP5xJFSjVTIz7IQSjcVGO41npnwIxRXNRxFOdIUHn0tjQ-7LwvEcTXyPsHXcMD8WtgBh-wxR8aKX7WPSsT1O8d8reb2aR7K3rkV3K82K_0OgawImEpwSvp9MNKynEAJQS6ZHe_J_l77652xwPNxMRTMASk1ZsJL' def send_payment(): url = baseURL + "/v2/SendPayment" payload = "{\"CustomerName\": \"Ahmed\",\"NotificationOption\": \"ALL\",\"MobileCountryCode\": \"+965\"," \ "\"CustomerMobile\": \"12345678\",\"CustomerEmail\": \"xx@yy.com\",\"InvoiceValue\": 100," \ "\"DisplayCurrencyIso\": \"KWD\",\"CallBackUrl\": \"https://google.com\",\"ErrorUrl\": " \ "\"https://google.com\",\"Language\": \"en\",\"CustomerReference\": \"ref 1\",\"CustomerCivilId\": " \ "12345678,\"UserDefinedField\": \"Custom field\",\"ExpireDate\": \"\",\"CustomerAddress\": {\"Block\": " \ "\"\",\"Street\": \"\",\"HouseBuildingNo\": \"\",\"Address\": \"\",\"AddressInstructions\": \"\"}," \ "\"InvoiceItems\": [{\"ItemName\": \"Product 01\",\"Quantity\": 1,\"UnitPrice\": 100}]} " headers = {'Content-Type': "application/json", 'Authorization': "Bearer " + token} response = requests.request("POST", url, data=payload, headers=headers) print("Send Payment Response:\n" + response.text) I tried this and made for loop but it didn't work url = baseURL + "/v2/SendPayment" sss={'ItemName': 'product 01', 'Quantity': 30, 'UnitPrice': 10,}, payload={ "CustomerName": "name", # Mandatory Field ("string") "NotificationOption": "SMS", # Mandatory Field ("LNK", "SMS", "EML", or "ALL") "InvoiceValue": 300, # Mandatory Field (Number) # Optional Fields "MobileCountryCode": "+966", "CustomerMobile": "12345678", #Mandatory if the NotificationOption = SMS or ALL # "CustomerEmail": "mail@company.com", #Mandatory if … -
django-environ and Postgres environment for docker
I am using django-environ for my Django project. I provided the DB url in the .env file, which looks like this: DATABASE_URL=psql://dbuser:dbpassword@dbhost:dbport/dbname Then, I created a docker-compose.yml where I specified that my project uses Postgres database, i.e.: version: '3.8' services: ... db image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=??? - POSTGRES_PASSWORD=??? - POSTGRES_DB=??? - "POSTGRES_HOST_AUTH_METHOD=trust" How do I provide these POSTGRES_* env. variables there? Do I need to provide them as separate variables alongside with the DATABASE_URL in my .env file? If yes, what's the best way do accomplish this? I aim to avoid duplication in my settings. -
django form commit=false after how to save many to many field data
Model.py class Branch(models.Model): # Branch Master status_type = ( ("a",'Active'), ("d",'Deactive'), ) name = models.CharField(max_length=100, unique=True) suffix = models.CharField(max_length=8, unique=True) Remark = models.CharField(max_length=200, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, choices = status_type, default = 'a') def __str__(self): return self.name class Vendor(models.Model): status_type = ( ("a",'Active'), ("d",'Deactive'), ) branch = models.ManyToManyField(Branch) company = models.CharField(max_length=200) name = models.CharField(max_length=200) phone = models.CharField(max_length=11, unique = True) email = models.EmailField(max_length=254, unique = True) gst = models.CharField(max_length=15, unique = True) pan_no = models.CharField(max_length=10, unique = True) add_1 = models.CharField(max_length=50, null=True, blank = True) add_2 = models.CharField(max_length=50, null=True, blank = True) add_3 = models.CharField(max_length=50, null=True, blank = True) Remark = models.CharField(max_length=200, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, choices = status_type, default = 'a') def __str__(self): return self.company form.py class VendorForm(ModelForm): class Meta: model = Vendor fields = 'all' exclude = ['created_by', 'branch'] widgets = { 'company':forms.TextInput(attrs={'class':'form-control'}), 'name':forms.TextInput(attrs={'class':'form-control'}), 'phone':forms.TextInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), 'gst':forms.TextInput(attrs={'class':'form-control'}), 'pan_no':forms.TextInput(attrs={'class':'form-control'}), 'add_1':forms.TextInput(attrs={'class':'form-control'}), 'add_2':forms.TextInput(attrs={'class':'form-control'}), 'add_3':forms.TextInput(attrs={'class':'form-control'}), 'Remark':forms.Textarea(attrs={'class':'form-control','rows':'2'}), 'status':forms.Select(attrs={'class':'form-control'}), } Views.py I have pass branch in session. I want to save with branch which is many to many field def Add_Vendor(request): # for vendor add msg = "" msg_type = "" … -
Django & SQLite.db - data is duplicated
I created 2 models in the Django framework. The first model is responsible to save emails and the second model to save messages. All emails and messages are saved in the SQLite.db. But when I add the same emails multiple times, the data base creates a new record and I don't have a clue how can I manage saving data to retrieve multiple emails with the same name and then pass them as a one mutual email to the HTML template with all assigned messages to them. An example: I sent 3 messages from test@test.com. Messages: ['Hi', 'Hello', 'Bonjour'] and one message from user@user.com ['Hi'] DB table: Actual result: 3 records test@test.com | 'Hi' test@test.com | 'Hello' test@test.com | 'Bonjour' user@user.com | 'Hi' Then I want to pass all data to the HTML template in order to display them: def emails(request): """Show all emails.""" emails = Email.objects.order_by('date_added') context = {'emails': emails} return render(request, 'home/emails.html', context) HTML portion: <h1>Emails</h1> <ul> {% for email in emails %} <li> <a href="{% url 'home:email' email.id %}">{{ email.text }}</a> </li> {% empty %} <li>No emails have benn added yet.</li> {% endfor %} </ul> But the final result is: test@test.com message_1: Hi test@test.com message_1: Hello test@test.com … -
Cannot correct a failed migration django
I inadvertently did this: ordering = models.IntegerField(default="Order/position") what I meant to do was this: ordering = models.IntegerField(default=0, verbose_name="Order/Position") I ran makemigrations and got no error. When I ran migrate it blew up with the error: ValueError: invalid literal for int() with base 10: 'Order/position' I updated to the correct field definition and while makemigrations is happy and noted the change migrate still keeps throwing that same error. How do I fix this? In case this matters - I am running Django with Postgres and both are in Docker containers -
The model is not displayed in the django admin panel
I don't have the advertisement module displayed in the django admin panel. Here is the model code from django.db import models class Advertisement(models.Model): title = models.CharField(max_length=1000, db_index=True) description = models.CharField(max_length=1000, default='', verbose_name='description') creates_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) price = models.FloatField(default=0, verbose_name="price") views_count = models.IntegerField(default=1, verbose_name="views count") status = models.ForeignKey('AdvertisementStatus', default=None, null=True, on_delete=models.CASCADE, related_name='advertisements') def __str__(self): return self.title class Meta: db_table = 'advertisements' ordering = ['title'] class AdvertisementStatus(models.Model): name = models.CharField(max_length=100) admins.py / from django.contrib import admin from .models import Advertisement admin.site.register(Advertisement) I was just taking a free course from YouTube. This was not the case in my other projects. Here I registered the application got the name in INSTALLED_APPS. Then I performed the creation of migrations and the migrations themselves. Then I tried to use the solution to the problem here , nothing helped. I didn't find a solution in Google search either. -
Import CSV file into model Django
I am trying to enter data using the model in the sqlite3, but I am facing a problem in determining the type of this data. Here is the dataframe: enter image description here I have written the following script: enter image description here When I run the code: .mode csv, then .import data.csv name_of_model I obtained this result: enter image description here I have tried to change the type of database but I still get the same result. -
how to integrate and generate invoices with django?
i am new in django , i would like to integrate an invoice functionality in my pharmacy app , but i have difficulties with table relations and i also lack some inspiration , i would also like to add the elements of my database how the product, the price ... in the invoice but I don't know how to do if you can not only help me solve this but you can also give me ideas for a pharmacy application. thank you in advance! I don't have an idea, I lack an idea to generate invoices for my models file and there from django.db import models class Client(models.Model): name = models.CharField(max_length = 30) date = models.DateTimeField(auto_now_add=True) class Stock (models.Model): balance = models.IntegerField(null=True) date = models.DateTimeField(auto_now_add=True ) class Produit(models.Model): name = models.CharField(max_length=100 , verbose_name= 'Nom') quantite = models.IntegerField(null=True , verbose_name= 'Quantité') price = models.IntegerField(null=True , verbose_name = 'Prix') expiration = models.DateField(null=True , verbose_name= 'Expiration') stock = models.ForeignKey(Stock , blank=True, null=True , on_delete= models.SET_NULL, verbose_name= 'Stock') date = models.DateTimeField(auto_now_add=True ,verbose_name= 'Date') description = models.CharField( blank= True , null= True, max_length=500 ) class Vente(models.Model): name = models.CharField(max_length=30) quantite = models.IntegerField(null=True) price = models.IntegerField(null=True) total = models.IntegerField(null=True) produit = models.ForeignKey(Produit, on_delete=models.CASCADE ) date = … -
How to generate credentials.json in Google Cloud Platform?
I am trying to use Google Storage for my Django application deployed in Compute Engine. To enable this I have to download a credentials.json in my console. I have made a new service account. However I do not see any download json for this credentials. How do you generate the json file? -
Both Dockerize and be able to debug a Django app using vscode
Is it possible to both Dockerize a Django app and still be able to debug it using Visual Studio Code's debugging tool? If yes, how? E.g, using docker-compose to run Django app, postgres, and a redis instance and be able to debug the Django app via Visual Studio Code. Thanks in advance -
Using Google Identity Service to create a sign up button but nothing is displayed in popup window
When I click on sign up with google button noting is displayed on the pop up window on browser. I have went through some of previous posts in SO but they didn't fix this issue: Links Visited the-given-origin-is-not-allowed-for-the-given-client-id-gsi gsi-logger-the-given-origin-is-not-allowed-for-the-given-client-id Here is the output : This the JS Authorized Origin Configuration I'm using Django as backend and here is the code to display the google sign up button : <html> <head> <script src="https://accounts.google.com/gsi/client" async defer></script> </head> <body> <div id="g_id_onload" data-client_id="client_id" data-context="signup" data-ux_mode="popup" data-login_uri="http://localhost:8000/users/register/signinWithGoogle" data-nonce="" data-auto_prompt="false"> </div> <div class="g_id_signin" data-type="standard" data-shape="rectangular" data-theme="outline" data-text="signup_with" data-size="large" data-logo_alignment="left"> </div> </body> </html> Why is sign up with google button not working am I missing something and how we can fix it? -
Update front-end when delete a row in database in React native
I am new with Django and I trying to run my first project. But i keep getting this error when trying to run python .\manage.py makemigrations enter image description here I am not sure what is the problem -
When i update my field i have to replace my upload my image file. i want my image should be attahced like other field in django
I do not want to replace my image file while updating other text and file name should be displayed in upload file choose file section so that as per my need i can modify file. as of now i am facing issues in that i have to again upload file in each update of other field. image for reference. eupdate.html <input type="text" name="institution" id="institution" placeholder="Institution Name" class="form-control w-50 form-row" value="{{pi.institution}}" required> <input type="text" name="fullname" id="fullname" placeholder="Full Name" class="form-control w-50 form-row mt-1" value="{{pi.fullname}}" required> <input type="text" name="email" id="contact" placeholder="Personal Email " class="form-control w-50 form-row mt-1" value="{{pi.email}}" required> <input type="number" name="contact" id="contact" placeholder="Contact " class="form-control w-50 form-row mt-1" value="{{pi.contact}}" required> <input type="text" name="position" id="position" placeholder="Position " class="form-control w-50 form-row mt-1" value="{{pi.position}}" required> <input class="form-control w-50 form-row mt-1" type="file" id="formFile" name="upload" value="{{pi.uploaddata.url}}" required> <img src={{pi.uploaddata.url}} class="img-fluid img-thumbnail" alt="image" style="width:100px; height: 60px"><br> <input class="form-check-input" type="checkbox" value="" id="invalidCheck" name='checkbox' required> <label class="form-check-label" for="invalidCheck"> Agree to terms and conditions </label> <br> <input class="bg-success text-white mt-1" style="margin-top: 0px;" type="submit" /> views.py def EuAdmin(request, pk): pi = EmailDb.objects.get(id=pk) if request.method == 'POST': institution = request.POST.get('institution', '') fullname = request.POST.get('fullname', '') email = request.POST.get('email', '') contact = request.POST.get('contact', '') position = request.POST.get('position', '') uploadd = request.FILES.get('upload', '') pi.institution = … -
Use and, or conditions while using Case,When
Anyone know in the following query how can I use AND condition? q = Food.objects.all().annotate(open=Case(When(days__day=today,then='blahblah'),When(start_time__lte=now and end_time__gte=now,then='blabla'))) On the second when I want to check if the now value is between start and end time but it seems like the 'and' keyword is not working there -
django_plotly_dash: div tag is messing up rendering of dashboard
I am working with django_plotly_dash to render dashboards within django template (from the doc, the dashboard can either be integrated as an iframe or in the DOM elements of the page. I chose to go the iframe road. The dashboard nevers takes the full screen on page. it is stucked on a small window. Looking at the dev tools in my browser, I found which div element is causing the issue, however, I dont know where it is come from because it is nowhere to be found on my code. here is my code: {% load plotly_dash %} <div class="{% plotly_class name='report' %}" style="position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"> <div style="position:absolute,top:0"> {% plotly_app name='report' initial_arguments=context %} </div> </div> but then now, here is what the source code look like with tools: <div class="django-plotly-dash django-plotly-dash-iframe django-plotly-dash-app-report" style="position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"> <div style="position:absolute,top:0"> <div style=" position: relative; padding-bottom: 10.0%; height: 0; overflow:hidden; "> <iframe src="/django_plotly_dash/app/report/initial/dpd-initial-args-8f2af15363304c6682112b8a6a3fc974/" style=" position: absolute; top: 0; left: 0; width: 100%; height: 100%; " frameborder="0" sandbox="allow-downloads allow-scripts allow-same-origin"></iframe> </div> </div> </div> there is a div tag with css between the declaration of my django dash … -
Django- Getting data from form to model
I am facing difficulty getting the selected size from the HTML template to my OrderItem model. I have the size model separately defined and added in as a foreign key on the OrderItem model. In the HTML template, I am looping through the available size that I have in my Size model among which one is to be selected but I am not getting that selected size added to ORderItem This is the model that I have class Size(models.Model): name = models.CharField(max_length=255, primary_key=True) def __str__(self): return self.name class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) size = models.ForeignKey(Size, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) And these are the views of that update orderItem and render sizes def store(request): sizes = Size.objects.all() c1 = ProductCollection.objects.get(name='c1') products = c1.products.all() if request.method == "POST": size = request.POST.get('size') if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} cartItems = order['get_cart_items'] context = { 'c1': c1, 'products': products, 'cartItems': cartItems, 'sizes': sizes, } return render(request, 'store.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', … -
Unable to use the value in a dictionary in one Django view in another Django view (AttributeError: module 'urllib.request' has no attribute 'session')
I am new to using Django. I have a function in views.py that computes the profit and prints it to a webpage in Django. I store the profit in a dictionary by the name of context and then store it in a session: #We want to calculate hourly profit def profitmanagement(request): #Profit has already been computed context={'TotalHourlyProfit':TotalProfit} #We will pass this dictionary to our ProfitManagement.html template. This will display our total profit. request.session['context'] = context #Save the dictionary using a session to use in another function return render(request,"ProfitManagement.html",context) Now I have another function that will be triggered every hour using APScheduler. It should set the TotalHourlyProfit to zero, and then output it to the webpage. It is as given below: #Sets the hourly profit to zero at each hour def ClearHourlyProfit(): context = request.session.get('context') #Loads the dictionary computed in profitmanagement(). This is returning an error context['TotalHourlyProfit']=0 #Set the hourly profit to zero. #print("Hourly profit function has context:",context) return render(request,"ProfitManagement.html",context) It returns the error: AttributeError: module 'urllib.request' has no attribute 'session' Is there a way by which I can pass the changed value of TotalHourlyProfit to my webpage? I will be very grateful to anyone who can point me in the … -
How to save Celery data into Django DB
I'm running a Django app on AWS, with a PostgreSQL DB, using SQS. I'm trying to offload the montecarlo simulation onto Celery, but I am unable to save the results to the DB. My view looks like: runMonteCarloAsync.delay(checkedCompaniesIDs) The task looks like: @app.task(bind=True) def runMonteCarloAsync(self,checkedCompaniesIDs): # Do some montecarlo stuff data = [] newResults = MonteCarloResultTrue(data=data) newResults.save() Here is my settings.py: CELERY_accept_content = ['application/json'] CELERY_task_serializer = 'json' CELERY_TASK_DEFAULT_QUEUE = 'django-queue-dev' CELERY_BROKER_URL = 'sqs://{0}:{1}@'.format( urllib.parse.quote(AWS_ACCESS_KEY_ID, safe=''), urllib.parse.quote(AWS_SECRET_ACCESS_KEY, safe='') ) CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "us-east-1", 'polling_interval': 20 } CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' I can see the messages hitting SQS: There are no new DB entires. I feel like I'm missing something, but I can't figure it out. -
Empty `request.user.username` while handling a GET request created
I was trying out logging all URLs accessed by user along with user id and date time when it was accessed using django middleware as explained here. For some URLs it was not logging user id. I checked and found that the request.user.username was empty string. I checked views corresponding to those URL and found that those views did not have desired decorators. For example, I changed this: def getXyz_forListView(request): # view body ... to this: @api_view(['GET']) @authentication_classes([TokenAuthentication,]) def getXyz_forListView(request): # view body ... and it started working. However some views are created from classes: class XyzView(View): def get(self, request): # view body ... I added same decorators: class XyzView(View): @api_view(['GET']) @authentication_classes([TokenAuthentication,]) def get(self, request): # view body ... But it is still not working. What I am missing? PS: It is added to urls.py as follows: urlpatterns = [ # ... url(r'^xyz/', XyzView.as_view(), name="xyz"), ] -
how to go through a list in javascript
I'm absolutely new to javascrippt and I want the background color to be green if a value is in the list, and red if it doesn't. what am I doing wrong because it doesn't work? myfunction: function myFunction1() { var infoElement1 = document.getElementById("answer1"); var answer1 = infoElement1.dataset.answer1; // in anser1 is my list var test = document.getElementById("answer1").value; // i wanna know if the test in answer1 is for(var i=0; i<answer1.length; i++) if (answer1[i] === test) { document.getElementsByClassName("option_btn")[0].style.backgroundColor = "green"; } else { document.getElementsByClassName("option_btn")[0].style.backgroundColor = "red"; } } Thank you! -
Router of React and Django could be co-existed?
I integrate React with Django. So when accessing http://localhost:8000/ my django jump to def index(request: HttpRequest) -> HttpResponse: return render(request, 'index.html', context) Rect top page and index.js, create the element where id=app import React from 'react' import ReactDOM from 'react-dom'; import App from './components/App.js' ReactDOM.render( React.createElement(App), document.getElementById('app') ); Then I set the /top under react router. const App = () => { return ( <BrowserRouter> <Routes> <Route path={`/top`} element={<TopPage />} /> </Routes> </BrowserRouter> ); }; export default App; However when using http://localhost:8000/top it goes to django url. What I want to do is using /admin for django though, pass other urls except admin to React. Is there any practice to do this?? -
Data inside request.data not visible in Django Rest Framework
I am using DRF for CRUD operations. In my Project, I have function-based view taking request as parameter. I am aware of the fact that request.data is only applicable for DRF-Specific requests. I am also aware of the fact that it is a QueryDict. I am taking input from HTML form as name, roll and city of a Student. But when I print the request.data (aka QueryDict), I only get csrfmiddlewaretoken and its value and found that other key-value pairs are missing. Where is my other data (i.e roll, name and city) e.g {"csrfmiddlewaretoken": "JSACyyvAPqNcCPXNZQsNzPcca7ah3N7arkhFM9CuqpNammk6f43wQ4GyGg5QwU6w"} It was supposed to contain other data fields as well!