Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to render vue js build in Django
Trying to render vue js build (index.html) in Django its working fine but the problem is that when i give any route to that url than i get page not found from vue. This working fine url(r'^$', TemplateView.as_view(template_name="index.html"), name='whatever'), And this is not, giving page not found error of vue url(r'^website/', TemplateView.as_view(template_name="index.html"), name='whatever'), https://i.stack.imgur.com/WsmOK.png -
How to convert sql mod to django orm?
The sql is: select id from tableA where MOD(id,10)=1 database is mysql. How to covert this sql to django orm filter? -
Django project on cpanel, www.example.com is working but www.example.com/admin or www.example.com/aboutus gives 404
I have created Django project on godaddy cpanel shared hosting , www.example.com is working and everything working fine with images and html templates, but when I hit www.example.com/about or www.example.com/admin or any other url it gives 404. here is my passenger_wsgi.py file import website.wsgi SCRIPT_NAME = '/home/udpo***j0so4/website' class PassengerPathInfoFix(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urllib.parse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) application = website.wsgi.application application = PassengerPathInfoFix(application) here is my settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '****************' DEBUG = True ALLOWED_HOSTS = ['www.example.com','example.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'django_user_agents', 'django_filters', 'django.contrib.sites',#django-allauth 'allauth', #django-allauth 'allauth.account', #django-allauth 'allauth.socialaccount',#django-allauth 'allauth.socialaccount.providers.google', #django-allauth ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'website.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'database', # Or path to database file if using sqlite3. 'USER': 'user', … -
how to update an instance related to a foreignkey django signls
hi i want to update an instance related to a foreignkey value for example i have these two models class Collection(models.Model): model = models.ForeignKey(Product, on_delete=models.CASCADE) company_name = models.ForeignKey(Company,on_delete=models.SET_NULL,null=True) price = models.IntegerField() cash = models.IntegerField() qnt = models.IntegerField() @property def product_loan(self): return (self.price * self.qnt ) - self.cash class Company(models.Model): name = models.CharField(max_length=40) balance= models.IntegerField() i want to whenever an instance from Collection been created then update balance in Company i tried this django signal but doesnt seem to work def post_save_collection(sender,instance,created,*args,**kwargs): if created: instance.company_name.balance = (instance.price * instance.qnt) - instance.cash #and also tried this but not worked #instance.company_name.balance = instance.product_loan post_save.connect(post_save_collection,sender=Collection) is there something i've missed please? or should i change something else ? -
Which libraries or technologies could help to create multiform (Django)
Hello! I want to create booking multiform with simple step-logic: Select date, available in database (DateField "date"); Select time for the date, selected at first step (CharField "time", just 4 times a day available); Contact form (name, phone, etc). But I have no idea how to get available time (step 2) exactly for selected date at step one without refresh page. My form should save some data ("date" from step one) and use it for the second step. I'm self-taught and don't know people to help in questions like this + google don't make fit. Please, tell me things which I could study and use for my purpose. Thanks! -
How to get modal form in the same page with updateview?
I have set an update view function as following: class Load_paper(UpdateView): model = Materiale form_class = MaterialeForm template_name = "magazzino/edit_paper_modal.html" Setting the url.py as: path('magazzino_edit/<int:pk>', views.Load_paper.as_view(), name='load_paper') And finally in my template table a column with the following code: <td><a href="{% url 'load_paper' element.id %}">Edit</a> </td> All works perfectly, but when a click on edit button, django redirect me on another page to edit the single objects. is there a way to open a modal form on the same page when I press on the edit button?? This is my actual edit_paper_modal.html {% load crispy_forms_tags %} <div class="modal-dialog modal-lg" role="document"> <form action="{% url 'load_paper' pk=object.pk %}" method="post" class="form" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Edit Paper</h4> </div> <div class="modal-body"> {% csrf_token %} {{form|crispy}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <input type="submit" class="btn btn-primary" value="Save changes" /> </div> </div><!-- /.modal-content --> </form> </div> -
How can i update username without logout in django
Django model :- Public_username = models.CharField(max_length=200, unique=True , null=False) ... USERNAME_FIELD = 'Public_username' after Update or change Public_username by using react and GraphQL mutation the user will be look like Not log in. how can i fixed this issue? -
How to create meeting using Zoom SDK
I am using the following code and I receive the success message but no meeting is shown to be created in my Zoom meetings. How can I succesfully create it ? <script type="text/javascript"> ZoomMtg.setZoomJSLib('https://source.zoom.us/1.7.10/lib', '/av'); ZoomMtg.preLoadWasm(); ZoomMtg.prepareJssdk(); console.log("checkSystemRequirements"); console.log(JSON.stringify(ZoomMtg.checkSystemRequirements())); ZoomMtg.init({ //debug: true, leaveUrl: 'http://127.0.0.1:8000/', isSupportAV: false, success() { console.log("success"); //resolve(); }, error(res) { reject(res); } }); </script> -
Django AJAX call url not found
I want to pass data from an AJAX call to my django view. My html: <a href="javascript:" class="word_known btn btn-warning btn-sm" data-songpk="{{song_pk}}" data-userpk="{{user_pk}}">Yes</a> My jquery: $(document).ready(function() { var known_words = 0; $(".word_known").click(function() { known_words++; var reference = this; var songpk = $(this).data('songpk'); var userpk = $(this).data('userpk'); $.ajax({ url: "/videos/songs/vocab/"+songpk+"/"+userpk+"/", data: {known_words: known_words}, success: function(result) { $(reference).removeClass("btn-warning"); $(reference).addClass("btn-success"); $(reference).text("Known"); }, failure: function(data) { alert("There is an error!") } }) }); }) My view: def word_known(request): if request.method =='POST': pass elif request.method == 'GET': request.POST.get('known_words') known_words = request.session.get('known_words') return known_words My url for my videos app: path('songs/vocab/<int:pk_song>/<int:pk_user>/known_words=<int:count>', views.word_known, name='song-known'), The known_words variable seems to be working (when I click the count goes up), but I get a 404 error. The following url is displayed: GET http://dev-lr:8000/videos/songs/vocab/1/3/?known_words=1 404 (Not Found). Can anybody please tell me what I am doing wrong? -
How do I get the right information from the model? [python]
The code I wrote on line I **. I tried to print {{ order.name }} When I click the data button shown in the popup, it shows all the data1's data, even though I clicked the data2,3 button. Every button I press will show the information of the first button, i.e. repeatedly shows the information even if each button is different. This is all of my code. models.py class Order(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField() def get_absolute_url(self): return reverse("order", kwargs={"slug": self.slug}) def __str__(self): return self.name views.py class HomeView(ListView): model = models.order template_name = "home.html" urls.py urlpatterns = [ path("", views.HomeView.as_view(), name="home"), ] template home.html {% extends "base.html" %} {% load static %} {% block content %} {% for order in object_list %} {% include "template/order.html" %} {% endfor %} {% endblock %} order.html {% load cropping %} <div> <p>{{ order.name }}<p> <button class="myBtn">ORDER</button> </div> <div id="myModal"> <div class="show-content"> <span class="close">&times;</span> <p> ***{{ order.name }}#This will show the data of the data that I clicked on.*** </p> </div> </div> <script> var modal = document.getElementById("myModal"); var btns = document.getElementsByClassName("myBtn"); var span = document.getElementsByClassName("close")[0]; Array.from(btns).forEach((btn) => { btn.addEventListener('click', () => { modal.style.display = 'block'; }); }); span.onclick = function() … -
What are these warning for cross-site cookie in my console?
I'm using python 3.7.4, django 3.06, javascript and jquery on windows 7. I'm not sure when it happens but now my console (F12 on firefox) gives me these warning: Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/lists/list-name/” because the scheme does not match. list-name Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/lists/list-name/” because the scheme does not match. list-name Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/lists/list-name/” because the scheme does not match. list-name Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/lists/list-name/” because the scheme does not match. list-name Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/static/js/common.js” because the scheme does not match. common.js Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/static/js/common.js” because the scheme does not match. common.js Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/static/lists/js/lists.js” because the scheme does not match. lists.js Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/static/lists/js/lists.js” because the scheme does not match. lists.js Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http://127.0.0.1:8000/jsi18n/” because the scheme does not match. jsi18n Cookie “PGADMIN_LANGUAGE” will be soon treated as cross-site cookie … -
How to determine user's timezone based on email address django
I'm sending email invites to user's with start and end time of different events. However I would like for these times to be based on that user's timezone. I currently don't have the user's timezones stored in my database. I their a way in django or python that I can determine their timezones based on their emails. -
Django Internalization gives Internal Error when Debug is False Only when 500.html is present
Please I am in need of your Help here. I enable Django Internalization in my app, and it works fine even when debug is False. But recently i tried providing 500.html and 404.html for my server error and page not found errors. Now the app gives "Internal Error: /" when you visit homepage. example localhost:8000 would give you Server Error. But If i manually Enter the Url like localhost:8000/en/ it works fine. Can Anyone shine more light for me on this. Below are the errors it provides on traceback. [10/Jul/2020 09:49:40] DEBUG [django.template:872] Exception while resolving variable 'LANGUAGES' in template '500.html'. Traceback (most recent call last): File "/home/trans/Documents/my_app/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/trans/Documents/my_app/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "/home/trans/Documents/my_app/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 558, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) 'admin/'>], [<URLResolver <module 'accounts.urls' from '/home/trans/Documents/my_app/freight_app/accounts/urls.py'> (None:None) '^profile-accounts/admin/'>], [<URLResolver <URLPattern list> (None:None) 'en/'>]], 'path': ''} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/trans/Documents/my_app/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 108, in get_exception_response response = callback(request, **{**param_dict, 'exception': exception}) File "/home/trans/Documents/my_app/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/trans/Documents/my_app/venv/lib/python3.6/site-packages/django/views/defaults.py", line 49, in page_not_found body … -
Create student accounts using django admin
I want to be able to create student user accounts using django admin interface which can be used by students to log in on my website? How can this be done using django 3, python 3.8 and html? Any sort of help would be really appreciated. -
GetStream.io returning activities in wrong order
I'm running across an extremely strange bug while using GetStream: i'm running a script to migrate over 200k activities (previously used an internal stream-framework fork) and I'm running across a really bizarre issue. The problem is this: I'm setting the 'time' field to a custom value (usually in the past). Now: these activities are being ordered wrong by the API. Although the activities being added have correct, ISO8601 UTC times in the past, the oldest ones are coming back on top of the feed (mixed with only a couple of new activities). This is really odd and I'm at the end of my wits -- this seems like an issue on Stream's end. Thoughts? Below is a screenshot of the issue. -
How to control Raspberry Pi with a web application deployed on AWS?
I have a Raspberry Pi with sensors, relays and actuators at home. I have no public IP address and to get access to my raspberry I should use, for example, a service like ngrok. But I'd like to create a web-application and deploy it on AWS (VPS linux server). It should be secure and support authentication. I imagine it as a dashboard. Data must change dynamically (like with AJAX). I don't need a stunning look, CSS support will be enough. Which technology stack should I use? 1. To connect the raspberry to VPS. Should it be VPN or SSH? How to organize access to data? Should UNIX-sockets or something similar be used? What if I have several boards on the network? 2. To implement a web-application. Although here it's overhead, I intend to use Django, because anyway I need to acquire this framework. But how to organize data exchange using WSGI? I want to add, I'm new to web development. Therefore, the solution should be as simple as possible. And the solution should be implemented with Python. I’m also going to learn JavaScript to use it in my full-stack pet projects. -
Django all-auth: How to disable automatic login via Google
I'm using the django-allauth package to log in users to my Django app via the Google API. My problem is that when a user successfully logs in via the external Google log in page, then everytime he logs out and wants to log in again, django-allauth automatically logs him in without redirecting him to the Google sign in page. How can I disable this functionality, and instead have the user redirect to the Google log in page each time he wants to sign in? (Ι have already tried ACCOUNT_SESSION_REMEMBER = False). Thanks! -
Create a ZOOM meeting with JWT account/credentials
Can I create a meeting with JWT account/credential ? I have already managed to initialize and join a meeting using Python and Javascript ( see bellow code ) but with the meeting created privously from Zoom portal web interface. ZoomMtg.init({ debug: true, leaveUrl: ‘http://127.0.0.1:8000/’, isSupportAV: false, success() { ZoomMtg.join({ meetingNumber: 71323503324, userName: ‘John’, passWord: ‘5mFKL7’, signature: ‘{{ signiture }}’, apiKey: ‘’, userEmail: ‘@yahoo.com’, success: function(res){console.log(res)}, error: function(res){console.log(res)} }); }, error(res) { reject(res); } }); There is a way to create it with JWT account programmatically ? Or I need OAuth for that ? -
Which Django testing strategy should be used
I'm in the process of writing tests for my Django website and I'd like to understand what's the actually difference (and what is better, more suitable) way of testing views.py files. From documentation there are two ways: let's call it simple - described here https://docs.djangoproject.com/en/3.0/topics/testing/tools/ advanced testing - https://docs.djangoproject.com/en/3.0/topics/testing/advanced/ Approach #1 is working ok and I can do e.g. request that will return everything I'll see on the page. Approach #2 appears to be more precise in the way I can ask for exact function within class-based view. Also I see this approach dominating in Django's internal tests. Which way is preferred when it comes to Django testing? -
How could I recognize private pages and public pages from QuerySets of Wagtail page?
when I make a API from wagtail, I have get QuerySets(contain private pages and public pages), then how could i recognize the private pages and public pages? the database tables don't have on filed to recognize it. I know how to get private QuerySets and public QuerySets, use case like below: Page.objects.filter().all().public().live() Page.objects.filter().all().not_public().live() is there any filed i can use,like page.private to get this attribute? -
What it the meaning of csrf token?
I am getting this error please haldle the csrf token in django project.When I first made an AJAX call with a POST request, I got a HTTP 403 Forbidden error. A quick debug led me to the CSRF authorisation problem. The backend refused to authorise the request because there is no accompanying CSRF token to prove that the request is not from a foreign site. -
Same Django projects running on different databases
I am trying to run two identical Django projects on different databases, one for production using a certain port number (say, 80) and the other for testing using another port number (say, 8000). I also used Nginx and Gunicorn as the reverse proxy server and the application server. The problem is: how do I know the port number of the request in Django's settings.py so that the project can choose different databases? -
How do I create a popup in python?
I would like to know how to create a popup when I click the button. I wrote the code using python and I loop the data that I need. And the data that came out I created a button to press and a popup would appear. I'm not sure if the data I loop when I clicked on the popup button would show the details of the information I pressed. I don't know what I need to do Please help recommend me I tried searching and trying for half a day but I really couldn't. Here is my sample code. And I've tried creating a popup and writing a script at order.html. It can press the order button and the popup can only show in data1, but other data2,3,4,5.... cannot click the button and popup it does not show. order.html {% load cropping %} <div> <p>{{ order.name }}<p> <button id="myBtn">ORDER</button> </div> <div id="myModal"> <div class="show-content"> <span class="close">&times;</span> <p> Show menu info clicked #This will show the data of the data that I clicked on. </p> </div> </div> <script> var modal = document.getElementById("myModal"); var btn = document.getElementById("myBtn"); var span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; } span.onclick = … -
Not able to migrate changes to mysql database from Django
I have added foreign keys to some of the models in a Django application but the changes are not being reflected in the MySQL database even after migrating them. I have tried deleting all the previous migrations and then redoing but had no success. What could be the issue here? -
Django, edit button with modal form does not works
In one of my django app I have set the following architecture: #models.py class Income(models.Model): price = models.DecimalField() quantity = models.DecimalField() date=models.DateField() # forms.py class IncomeForm(forms.ModelForm): class Meta: model = Income fields = "__all__" #views.py def income_(request): elements = Income.objects.all() if request.method == 'POST': form = IncomeForm(request.POST) if form.is_valid(): new_input = form.save() else : form = IncomeForm() elements = Income.objects.all() context= { 'form': form, 'elements':elements, } return render(request, "income/income.html", context) def edit_income(request): pk = request.GET.get('pk') object = get_object_or_404(Income, pk = pk) form = IncomeForm(instance=object) return render(request, 'edit_income.html', { 'object': object, 'pk': pk, 'form': form, }) After that I have set the following urlspatterns: path('magazzino/gestionemagazzino/', views.income_, name ='gestione_magazzino'), path('magazzino/edit_modal/<int:materiale_pk/>', views.edit_income, name='edit_income') In my income.html file I have set the following {% load crispy_forms_tags %} <form id="" method="post"> <div class="form-group col-2 0 mb-0" > {{form.quantity|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.price|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.date|as_crispy_field}} </div> </div> After that I have created a table that list all data filled and in the last column I have set the following button: <button id="myBtn" data-target="#myModal"> </button> Now I want to create a button for each row that open a modal form that give me the possibility to modify …