Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
PasswordResetView, html_email_template_name isn't updating
View: class ResetPasswordView(SuccessMessageMixin, PasswordResetView): template_name = 'accounts/reset_password.html' html_email_template_name = 'accounts/password_reset_email.html' success_message = 'Instructions to reset your password will be sent to the email you provided. Thank you.' success_url = reverse_lazy('accounts:profile') html email template: You're receiving this email because you requested a password reset for your user account at {{ site_name }}. Please go to the following page and choose a new password: {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'accounts:password_reset_confirm' uidb64=uid token=token %} {% endblock %} Your username, in case you’ve forgotten: {{ user.get_username }} The {{ site_name }} team. URLs: urlpatterns = [ path('update-password/', UpdatePasswordView.as_view(), name='update_password'), path('reset-password/', ResetPasswordView.as_view(), name='reset_password'), ] Despite setting a template path for the email, Django continues to load the default instead: \lib\site-packages\django\contrib\admin\templates\registration\password_reset_email.html Why is it not using accounts/password_reset_email.html? -
I am a beginner in programming language, after learning python which framework I should learn Django or tenserflow,?
I am a beginner in programming language,after learning python which framework I should learn as a beginner, Django or tenserflow, I am really interested in AI can anyone help? A suggestion for me to get a job as a developer. -
Can I implement separate user authentication and models for two apps in django project?
In this django project I have two separate applications that I need to keep user account information separate. For example, if a person creates an account for app A, I need them to be able to make a separate account (with the possibility of using the same unique email for account creation) for app B. At this moment in time, it seems as though there is no way for me to handle having two separate auth models for two separate users. I am wondering what the django workaround for this might be, or if I am misunderstanding the problem in some way? Here is an example user model that would work for both application A and B, but would need separate tables or models for authentication and account creation: class GenericUser(AbstractUser): """abstract user class for user authentication""" firstname = models.CharField('First Name', blank=True, max_length=100) lastname = models.CharField('Last Name', blank=True, max_length=100) email = models.CharField('Email', unique=True, max_length=100) class Meta: permissions = ( ("some-permission", "some-description"), ) First I tried creating two separate user entities in the models.py file in my django project, however when I finished doing this, there was nowhere to put the second user model in the settings.py folder. This is where … -
Tailwind's default colors are not working, only white and custom colors
I am building a web application through the django framework and installed tailwind through this tutorial "https://django-tailwind.readthedocs.io/en/latest/installation.html" and it worked fine intitially. Now everytime I reload my project after closing vscode, my colors stop working. For an example, I'll be creating a new line of html and use: <body> <div class="bg-blue-400 font-bold p-4 text-4xl"> <h1>Hello</h1> </div> </body> and the background just goes immediately to white. I have tried uninstalling and reinstalling and checking my directories and everything and still no solution. I have also found that only my custom colors work when I reload into my project. -
Firefox requests are just stopped after some time empty status code
I have Django fetch request that takes some to time to finish it works fine on chrome but fails on chrome I tried different view on Firefox and made it wait some time with time.sleep() function test_time(request): for i in range(70): print(i) time.sleep(1) return HttpResponse("done") if i made the time less than 20 the view works fine more than that in 25-36 seconds the page just stops loading and the request shows no status code - timing 0ms - response: No response data available for this request -
Correct way to add image related info wagtail
I am setting up a simple site with the main purpose of having galleries of images. Using collections to group images and display them on a specific page is how I set it up first. However I am not sure what the recommended way is to add a description. My options I have tried are: Custom page This seems as the way to handle it, however I lose the nice feature of using collections to generate pages. This would mean I separate info of a image into a page model, fragmenting the image from the data. I see that creating a custom image is recommended, but I doubt it's for this purpose. Custom image model This allows me to add a description field completely replaces the image model since you can only have 1 image model afaik. In a webshop like site this seems suitable (price, reviews, stock etc.) but since this site focuses on the image specific it seems this kind of coupling is ok. Is the first option the way to handle this? Or how can I set this up so that a designer/user can tie data to a image without losing the base image or allow the … -
Best way not to violate the DRY principle here. Django/Class-based Views
Here is a view I used to download an excel document based off data that I have: class ExcelDownloadAllView(TemplateView): def get(self, request, *args, **kwargs): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="All_of_Projects.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('All Projects Data') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Username', 'First Name', 'Last Name', 'Email Address', 'Summary'] rows = BugTracker.objects.all().values_list('project_number','assignee','priority','status','summary',) for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response It works fine, but now I want to create another CBV with a different "row=" filter. What is the best way to do this using DRY principles? I tried something like. But the rows variable will get overwritten by the previous class. class ExcelDownloadOpenView(ExcelDownloadAllView): def get(self, request, *args, **kwargs): rows = BugTracker.objects.all().values_list('project_number','assignee', 'priority') return super().get(request, *args, **kwargs) Any suggestions without copying the entire method and replacing the rows variable? -
Couldn't able to load js and images in Django
Could not able to load any javascript files and imagesenter image description here instead of using global... also tried to use app level static but nothing changes enter image description here [enter image description here](https://i.stack.imgur.com/9Mlhd.png) enter image description here -
Django, getting data from another user (schema) in an Oracle 19 DB
I am using Django 4.1, Oracle 19 with the python package oracledb. I am logged in as user djangousr and the schema I am trying to get the data from is "user123" I am able to retrieve data in a file outside of Django with the same connection information. But in Django, I keep getting the same error. I hope you have a solution for me as I was not able to find anything elsewhere. Thank you. ORA-00942: table or view does not exist Below is the SQL from the debug screen that I am able to run fine in SQL developer. ('SELECT "USER"."USER_ID" FROM "user123.USER_TABLE"') I will also provide the model and the view: class SecurityUserData(models.Model): user_id = models.IntegerField(primary_key=True) user_name = models.CharField(max_length=100) user_password = models.CharField(max_length=100) user_first_name = models.CharField(max_length=30, blank=True, null=True) user_last_name = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'SEC_USER' And the view: def display_user_data(request): user_data = SecurityUserData.user123.all() return render(request, 'all.html', {'user_data': user_data}) -
Trouble deploying Django application with Celery to Elastic Beanstalk
I have a working django application deployed to Elastic Beanstalk. I am trying to add some asynchronous commands to it so am adding Celery. Currently I am running container commands through python.config in my .ebextensions. I have added the command: 06startworker: command: "source /var/app/venv/*/bin/activate && celery -A project worker --loglevel INFO -B &" to my python.config. When I add this command and try to deploy my elasticbeanstalk instance timesout and deployment fails. I have confirmed that connection to my redis server is working and my application can connect to it. Checking my logs in my cfn-init.log I see: Command 01wsgipass succeeded Test failed with code 1 ... Command 06startworker succeeded So I think that when adding the 06startworker command it is somehow interfering with my 01wsgipass command which runs fine when I dont have the start worker command. For reference my wsgi command is: 01wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' I'm at a bit of a loss on how to troubleshoot this from here. I'm finding the logs that I am getting are not very helpful. -
how to resolve error of Access to external web links been blocked by CORS policy in react
How do i resolve this issue that i am getting when trying to send a request to an enpoint that would then redirect to a payment popup page. THis is the full error that i am getting Access to XMLHttpRequest at 'https://ravemodal- dev.herokuapp.com/v3/hosted/pay/6f77ffaf62ea8eb1c3a5' (redirected from 'http://127.0.0.1:8000/api/payment/sam/152.00/desphixs@gmail.com/') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. and this also GET https://ravemodal-dev.herokuapp.com/v3/hosted/pay/6f77ffaf62ea8eb1c3a5 net::ERR_FAILED 200 (OK) NOTE: i have CORS header Configured in my backend application as that is what have been allowing me to send request to the backend api. Django Settings.py CORS_ALLOW_ALL_ORIGINS = True Django Traceback [03/Feb/2023 22:37:02] "GET /api/payment/Nell/152.00/jopimo@mailinator.com/ HTTP/1.1" 302 0 what is going on, and how can i go about fixing this? -
Return a render to a view from another function in django
I am making a simple web page. I have to ask for an input, define its type, make some processing and return a few values. I have two views, one that has a simple form asking for an input, and the other one: def processedframe(request): frame = request.POST['frame'] try: if frame.startswith('>RUS08'): try: # Frame procesing(a lot) return render(request, 'frame.html', {'values': values) except: return HttpResponse("Processing error") else: return HttpResponse("Invalid frame") except: return HttpResponse("Invalid input") The problem is that i have +30 frame types with diferent things to process. I want to make one extern function in other folder for each frame type, and return a render from the function. I have already tried to make a separate folder with the functions and import it into the views.py That worked fine, because it was able to enter to the frame processing for the function, but when i tried to return the render from the function, i got an error, because the views.py was not returning anything. I have also tried to render from the views.py but i was not able to acces to the values from the function. I have also tried putting the code to process the frame inside the processedframe … -
How can I revive the website in Google Cloud Services?
Our lab had a web-based tool that was running on Google Cloud services, specifically in "Cloud Run". When our accounting did not pay the bills, service was shut down. Now it is paid, and it seems that are 2 services running in cloud run, one for Django and other for login backend service. I have the source code for both backend and frontend, but I have no idea how to make the application online again in its previous link. In "Cloud Storage" we also seem to have multiple buckets, where I don't know if they do anything or not. I have 0 web development experience. If you have developed a web platform by using Typescript on front-end and django on backend, a help to how to deploy these source codes on Google Cloud that was already previously running would be really appreciated. I paid the bills and 2 services on the "Cloud Run" seems to be working. They have their own link where when I click them one directs me our login page (but when I login successfully it does not render any frontend), and other just directs me to Django Rest Framework Api Root. I want to understand how …