Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django webserver falis after sending a password reset request email
I have asked this question multiple times now, and it is definitely my fault for not explaining the problem properly, so I have made a short screen-recording that showcases the problem. The URLS: path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), Settings setup: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '*******@gmail.com' EMAIL_HOST_PASSWORD = *******' Here are the logs, I tried to read them but I got no idea how to fix this error. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 850, in resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [is_nav_sidebar_enabled] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf..get_val at 0x00000285F295D488>>, 'request': <WSGIRequest: GET '/reset_password/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.. at 0x00000285F2B482F0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x00000285F2A4EE10>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x00000285F2B200F0>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': , 'view': <django.contrib.auth.views.PasswordResetView object at 0x00000285F2B201D0>, 'title': 'Password reset', 'LANGUAGE_CODE': 'en-us', 'LANGUAGE_BIDI': False}] "GET /reset_password/ HTTP/1.1" 200 1903 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en\formats.py first seen with mtime 1603131647.8355522 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en_init.py first seen with mtime 1603131647.8345575 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\staticfiles\storage.py first seen with mtime 1603131653.6030731 … -
using django project as a standalone file
i need to use my django project in a standalone system where i can't install python, so i try to use pyinstaller on my manage.py file and i added function that opens the browser so when i click on the icon- the project will open automatically in the browser. my manage.py code is: import os import sys import webbrowser import django def open_in_browser(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'feedback.settings') django.setup() from django.core.management import call_command from django.core.wsgi import get_wsgi_application application = get_wsgi_application() webbrowser.open('http://127.0.0.1:8000', new=1) call_command('runserver', '127.0.0.1:8000') def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'feedback.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) open_in_browser() if __name__ == '__main__': main() the code work before pyinstaller but when i try to use pyinstaller the file manage to open the browser but the server stop running so the browser cannot find the page. how can i keep the server running? -
How to run Django APScheduler on a view function
I want to run a Django view every day preferably at a specific time that calls an API and saves the data in a ForeignKey relational model. I can't use the schedule package in python because it requires infinite loop which can't run alongside a web server. Django APScheduler looks like an elegant solution though the problem is view functions take request as an argument which can't be passed to APScheduler which I need to save the data with the user's id thus I'm getting a Name error views.py def sync_data(): api_url = "" access_token = RefreshToken.response headers = { 'Authorization': 'Bearer {}'.format(access_token), 'Content-Type': 'application/json;encoding=utf-8', } user_id = request.user.id response = requests.post(api_url, data=json.dumps(body), headers=headers) r = response.json() s = Model(user=request.user, starttime = startdate , endtime = endate, field = i['value'][0]) s.save() return redirect('app:dash') scheduler.py from .views import sync_data def start(): scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") # run this job every 24 hours scheduler.add_job(sync_data, 'interval', hours=24, name='sync_daily_data', jobstore='default') register_events(scheduler) scheduler.start() print("Scheduler started...", file=sys.stdout) How do I go about this? Appreciate any help I'll get -
Default regex django uses to validate email
recently, I started playing with Django and created a custom form for user registration. In that form to create the field for email I use something like email = forms.EmailField() I observed that address such as a@a.a is considered invalid by the form. Of course this is a nonsense email address. Nonetheless, I wonder how does Django checks for validity. I found some topics on the net discussing how to check for validity of an email address but all of them were providing some custom ways. Couldn't find something talking about the django default validator. In their docs on the email filed they specify Uses EmailValidator to validate that the given value is a valid email address, using a moderately complex regular expression. However that's not very specific so I decided to ask here. -
xmlhttprequest post not posting to view in django
I am having a login page like this which gets data authenticated from google sign-in successfully and after that I need to post the data to the login view function onSignIn(googleUser) { // Useful data for your client-side scripts: var profile = googleUser.getBasicProfile(); console.log("ID: " + profile.getId()); console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); console.log('Family Name: ' + profile.getFamilyName()); console.log("Image URL: " + profile.getImageUrl()); console.log("Email: " + profile.getEmail()); var id_token = googleUser.getAuthResponse().id_token; console.log("ID Token: " + id_token); alert("Token*"+id_token); //this gets executed var xhr = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); } }; request.open('POST', '/login'); //i tried this also 'login' but not working xhr.open('POST', 'http://localhost:8000/login'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { console.log('Signed in as: ' + xhr.responseText); alert("*******Token*"+id_token) xhr.send('idtoken=' + id_token); }; views def login(request): //does not get called if request.method=='POST': print("in login") print(request.body.decode()) ---more code urls.py path('/login', views.login, name="login"), path('',views.login,name="login"), I am getting no response on the view, i am not getting any error on the console also. Can anyone please help here? Thanks. Starting development server at http://localhost:8000/ Quit the server with CONTROL-C. [09/Feb/2021 07:44:13] "GET / HTTP/1.1" 200 3048 [09/Feb/2021 07:45:15] "GET / HTTP/1.1" 200 … -
Distance between two coordinates in swift does not match geodjango query
I am in the process of developing a mobile application in Swift that is connected to a Python/Django backend. I have a group of objects that need to be sorted by location. Each object has a Point representing the coordinate pair. I connect to the backend from the frontend by passing in the source_latitude and source_longitude into the url parameters. I then use geodjangos with geospatial indexing for two different queries: latitude = request.query_params.get('source_latitude', None) longitude = request.query_params.get('source_longitude', None) if latitude is None or longitude is None: return queryset ref_location = Point(float(latitude), float(longitude), srid=4326) return queryset.annotate(distance=Distance('location', ref_location, spheroid=False)).order_by('distance').distinct() In my second query, I need to organize by within a certain range, which includes a radius URL parameter: return Store.objects.filter(location__distance_lte=(ref_location, D(mi=[radius input into from url parameter]))) Since the distance calculated is different for each object on each phone. I calculate the distance to display to the user on the frontend. However, there seems to be a discrepancy with the distance calculated between the frontend and the backend. For some objects that are close in distance, say 1-3 miles, the ordering of the objects is wrong. This is the frontend swift Code let currentLocation = CLLocation(latitude: Double(latitude)!, longitude: Double(longitude)!) let storeLocation = … -
Is there a way to pass in variable to <div> id in django template?
I am new to the Django template language and I am playing around with bootstrap collapses to display my items. Below is my code: {% for item in items %} <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> {{item.item_name}} </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> {{item.description}} </div> </div> </div> </div> {% endfor %} This is taken from the Bootstrap documentation for collapse, here. In this implementation, all of the items passed in would have the same id, collapseOne. So whenever I click on an item, any item, it would collapse/uncollapse every item on the page. I've tried id="collapse{{item.item_name}}" but that doesn't seem to work. Is there a way to pass in variables in <div> id? -
how to show the name of uploaded file as download link in Django
In my Django project, I want to show the download link as the name of the uploaded file. Here is my models.py class QuoteList(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) attached_file = models.FileField(upload_to='documents/QuoteList/%s/'%owner, blank=True) def __str__(self): return self.owner.email In views.py, I just query an object and send it to the template: def quote_details(request, quote_id): quote = get_object_or_404(QuoteList, id=quote_id) quote.is_opened = True quote.save(update_fields=['is_opened', ]) context = { 'quote': quote, } return render(request, 'basket/quote_details.html', context) In the template I use the following code to generate download link: {% if quote.attached_file %} <div class=""> <a role="button" href="{{ quote.attached_file.url }}" download="{{ quote.attached_file.url }}" class="btn btn-light text-dark ml-0"> Download attachment <========== the name which is showing to the user </a> </div> {% endif %} how to change the Download attachment to the name of uploaded file? -
Flask API access through headers token from a Django app
I'm a web dev beginner and I am trying to implement the following solution for my problem. I have several public Flask APIs, that I need to access from a Django App. These APIs is for back-end use, with the objective to provide data from the database to the Django app access and display the data (in graphics) for the user. This strategy was build in order to separate the database from the web app for protection purpouses. I want to limit Flask APIs public access in a way that just my Django app access it. The simplest solution I came up with was creating a JWT token with SECRET_KEY information shared between applications, Flask API and Django app, and pass the token through headers request: Django request: token = jwt.encode({'user_name' : 'admin_user'}, app.config['SECRET_KEY']) url = "http://website.com/api-flask" requesturl = Request(url) requesturl.add_header('Token', '%s' % token) response = urlopen(requesturl) Flask token check: def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = request.headers.get('Token') token_b = tokenurl.encode('UTF-8') if not tokenurl: return jsonify({'message' : 'No token!'}), 401 try: dataurl = jwt.decode(token_b, app.config['SECRET_KEY']) except: return jsonify({'message' : 'Token is invalid!'}), 401 return f(message, *args, **kwargs) return decorated @app.route("/api-flask") @token_required def apiflask: conn = db_connect.connect() query = conn.execute("SELECT … -
ValueError: Field 'id' expected a number but got 'kumarsingha922@gmail.com'
I made a django projects in which i made a test i assign email to email but it was taking it as a Id solve thi problem It was a django project in which i am making a receipe api . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . , , . . . Models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager,PermissionsMixin # Create your models here. class UserManager(BaseUserManager): def create_user(self,email, password, **extra_fields): user = self.model(email, **extra_fields) user.set_password(password) user.save(using= self._db) return user class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(max_length=255,unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" test_models.py from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_sucessfully(self): email = "kumarsingha922@gmail.com" password = "Singh@922" user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email,email) self.assertTrue(user.check_password(password)) Error WARNING: Found orphan containers (recipe-api_db_1) for this project. If you removed or renamed this service in your compose file, you can run this command … -
how to get Category in Django Serializer
i have hierarchical category in Django 3.1.5 class Categories(models.Model): category_name = models.CharField(max_length=250, unique=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='parent') slug = models.CharField(max_length=250, blank=True, null=True) data like - [{ "id": 1, "category_name": "1", "parent": null}, { "id": 2, "category_name": "1.1", "parent": 1}, { "id": 3, "category_name": "1.1.1", "parent": 2}, { "id": 4, "category_name": "1.2", "parent": 1}, { "id": 5, "category_name": "1.1.1.1", "parent": 3}] i using django Serializer. so how can we get category hierarchical data like- { "id": 1, "category_name": "1", "parent": null, "SubCategories": [{ "id": 2, "category_name": "1.1", "parent": 1, "SubCategories": [{ "id": 3, "category_name": "1.1.1", "parent": 2, "SubCategories": [{ "id": 4, "category_name": "1.1.1.1", "parent": 3, "SubCategories": [...] },] },] }, { "id": 5, "category_name": "1.2", "parent": 1, "SubCategories": [...] },] } -
How to receive SMS and store it to a local database in Twilio?
I'm starting an SMS project. One of the features is that people can respond to a form through SMS. Is it possible to receive an SMS and store the information in a local database? How do I that with Twilio? For example, the user sends a message with a request to fill-up a form. It then replies the needed information to fill in and the format for responding. After the user replies with the proper format, the collected data would then be written into the database. For a clearer example: User: I want to fill the form APP: Answer the following: [1] First Name, [2] Middle Name, [3] Last Name, [4] Age, [5] City To respond, follow the format: (First Name) (Middle Name) (Last Name) (Age) (Street) (City) User: (replies with proper format) APP: Thanks your response has been recorded! These variables of each info (First name, Last name, Age, City) would then be stored in a database. How do I make a GET and POST method? I would like to use Python, and use Django and connect it with a MySQL database. I've been searching for ways, but I tend to get lost. I'm having a hard time learning … -
Serve files in django
I am using React with Django. And I want to serve react public files from Django. but django static and media files are served with a prefix url, like this /static/favicon.ico /static/manifest.json /media/image.png but I want to serve files like this, without any prefix /favicon.ico /manifest.json So how do I do it? -
hosting my Django website on the internet with SSL certification overseas
I have completed my django project and I intend to host it online. I do not want to host it through Heroku or PythonAnywhere and I also require an SSL certificate. I come from Singapore, and after some research, I realised they only offer support to Wordpress, PHP websites. As such, I am wondering if it is possible for me to host it in another country such as USA/UK instead of in my own country. Will it be very difficult to manage my website hosted in another country? Also, do you guys have any recommended hosting providers in those countries that I can reach out to for a good deal? Sorry that this isn't a coding question. Advises will be super appreciated! -
Django premailer - Removes responsiveness from email template
I am trying to send an email using Django. The email template was made by someone else with a ton of CSS and it will take a lot of hours just to "inline" it. So I used premailer to inline the CSS automatically. It worked pretty well till I saw that it also inlined the media queries that were responsible for the responsiveness of the templates. One solution I saw was to put media queries in a separate style tag and put data-premailer="ignore" but unfortunately, I think this solution does not work anymore. I also tried using django_inlinecss, but that didn't work for me also. Please let me know how to fix premailer or if there any other package available that can inline CSS. -
JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) in POST request
I'm working on a project where I integrated a payment gateway, where I created a JSON string and pass URL, when all information is correct, then it generates a payment link. When I used demo URL and demo data it worked perfectly but when I use real URL it says this error. here is view.py: def payment(request): jsonObj={ "name": "name" } json_string = json.dumps(jsonObj) print(json_string) url = "https://url.something" headers = {'Content-type': 'application/json', 'Accept': 'application/json'} r = requests.post(url, data=json_string, headers=headers) print(r.json()) j = r.json()['status'] k = r.json()['data'] if j == "200": payment_id = k['payment_id'] redirect_url = k['redirect_url'] payment_link = str(redirect_url) + "?" + str(payment_id) print(payment_link) context = { 'payment_link': payment_link, } return render(request, 'users_dashboard/payment.html', context) return render(request, 'users_dashboard/product_rashid.html') -
Deployed two versions of same code (Django) on App engine standard but they are working differently
I am working on a Django project and deployed two versions of it on Google cloud app engine standard. And it is working perfectly fine locally but when tested with the version URL on the app engine, one version is working fine but another was not. Actually, I am using the fpdf module in python to write pdf files whenever a user writes a text. But only one version was able to do that another one giving me a blank pdf. When I checked the size of both the version there was a difference of 0.1MB.This image shows you the size of both the version: I went through the source code of both versions, and I don't have seen any difference between them, and no file is deleted. I have also checked the requiements.txt and app.yaml file but there was no difference at all.This image shows the files I used Till 4th Feb 2021, every version I have deployed is working perfectly but it was not working now Thanks in Advance -
How to use Django Qml and Javascript to create a Desktop App
I want to use qml, pyside and django to create a desktop app that will be connecting to the internet. I know it makes sense to use php but because i am an intermediate with qt and python, I would like to use my strongest suite. How possible is it to create this app which will be full of report generation and user activity monitering. If not how do u suggest I go about solving the problem. -
Update changes on React + Django without running "npm run build" everytime
My Django + React app is integrated fine at least for most parts. Because every time I have to make changes on my React code, in order to apply those changes I have to stop django from running then run npm run build everytime. I've already read this is there any way to run React + Django in same project without running npm run build again and again? and tried to apply it to my problem but it didn't work. Still new in React but with a few experiences with Django. Would appreciate your help -
Django SQLITE3 BASE_DIR not working when moving machines
So I have the following code which specifies the path of where my db file is located on my system. It works flawlessly on the computer which I have created my django project in. However, when I move the project to a different machine, it does not find the db.sqlite3 file and instead creates a new one in the root directory of that machine, so I have to create a DB_DIR and manually specify the path and cannot use BASE_DIR for the database connection. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Does anyone have any suggestions? -
(Djoser) Weird activation email when I update the user fields
Every time when I try to update my user with the PATCH method to the /users/me/ endpoint, an activation email is always sent. The user is already active in the system... so I don't know what is happening. SEND_ACTIVATION_EMAIL is True, but I understand that the email will be sent only after: creating an account or updating their email (I'm not updating the email) DJOSER = { .... 'ACTIVATION_URL': 'auth/users/activation/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, .... } -
TemplateDoesNotExist at /account/password_reset_confirm/MQ/set-password/ registrationpassword_reset_confirm.html
I`m using the Django authentication system to reset the user password. I create an app named account, in which I add the following codes in the urls.py modules: from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns=[ path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] I create all the templated needed in the app`s template/registration repository: password_reset_form.html, password_reset_done.html, password_reset_confirm.html, password_reset_complete.html, And I also add the email setting to my project: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '********' EMAIL_HOST_PASSWORD = '**********' EMAIL_PORT = 587 EMAIL_USE_TLS = True I run the server, on the password reset page I enter the email that the user is verified, after that, I received the password reset link in my inbox, but When I click it then the TemplateDoesNotExist exception occurs. -
How to get react components in a separate static js file read by Django? What is the least to be installed to make it work?
What are the modifications needed to be done ? And/or what is the least needed to be installed for this to work? First, in a static reactclasses.js file the file only contains this. (Is there anything else needed to be added?) class Login extends React.Component { render() { return ( <div id="login"> <form action="/login" method="POST"> <input type="text" name="username" placeholder="Username" required/> <input type="password" name="password" placeholder="Password" required/> <input type="submit" value="Submit"/> </form> </div> ); } } In an html file <!--- in the head tag ---> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="{% static 'reactclasses.js' %}" type="text/babel"></script> <!--- in a script tag with type=text/babel in the body tag --> ReactDOM.render(<login />, document.querySelector("thediv")); the console errors image -
Send related image to Django Rest Framework
Hello everyone reading this post. I got such issue. So, first of all I have such models layout class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') description = models.TextField(max_length=4000, null=True) liked_profiles = models.ManyToManyField('self', related_name='likes') disliked_profiles = models.ManyToManyField('self', related_name='dislikes') class Image(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='images', max_length=6) path = models.ImageField(upload_to='profile_images') So, I want to create a drf endpoint that will receive some kind of image, create it, and link to the profile model. But I really not sure how to implement this(I want to make it with django viewsets). The main goal is not to provide another viewset class (like ImageViewSet), but to make it part of ProfileViewSet. So now I have such viewset (contains a method to update the description) class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() permission_classes = (IsAuthenticated, ) @action(detail=True, methods=['PUT']) def set_description(self, request, pk=None): profile = self.get_object() serializer = DescriptionSerializer(data=request.data) if serializer.is_valid(): profile.description = request.data['description'] profile.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want to add something like "add_image" method to it. How can I implement it and is it actually possible(otherwise you can help me to implement it with another viewset)? I will be extremely grateful for your help -
ArrayReferenceField(ManyToManyField) in django-admin, Djongo/MongoDB
I catch error while saving Diary document in django-admin Here Diary model