Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How dowload image from url to this custom ImageField(JsonField) Django
I have custom model_field in Project. I upload an excel file with data where I store links to photos(of this type https://url?token).I perform excel processing using pandas, and save data to the database via the serializer. How can I open the link and get the image to write it to this field of the model. This custom field in model_field.py class PsImageModelFieldBase(JSONField): def __init__(self, ps_image_class, **kwargs): assert issubclass(ps_image_class, BasePsImage) self.ps_image_class = ps_image_class super().__init__(**kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() args.append(self.ps_image_class) return name, path, args, kwargs def create_object(self, kwargs): if kwargs is None: return None try: if isinstance(kwargs, BasePsImage): return kwargs return self.ps_image_class(**kwargs) except TypeError: return kwargs class PsImageModelField(PsImageModelFieldBase): def get_prep_value(self, value): if value is not None and isinstance(value, (dict, list, BasePsImage)): value = self.create_object(value).as_json return super().get_prep_value(value) def from_db_value(self, value, expression, connection): return self.create_object(value) image.py import os import re from django.conf import settings from common.utils import camel_to_snake from photoservice.service import PhotoService class InvalidFormatError(Exception): pass _default_photo_service = PhotoService() def _validate_format(format_, format_regexes): is_valid = any(regex.match(format_) for regex in format_regexes) return is_valid def _validate_versions(class_name, versions, format_regexes): for fname, format_ in versions.items(): if not _validate_format(format_, format_regexes): raise InvalidFormatError(f'{class_name}: version="{fname}": "{format_}" is invalid') class PsImageMeta(type): """ Metaclass for default formats validation. """ def __new__(mcs, … -
AttributeError: module 'oauth' has no attribute 'OAuthDataStore'
I am facing this error while running the command "python3 manage.py runserver" at my system. I am using oauth module to facilitate connection between Python Oauth and Django Database. I have enclosed the library import and the Base class usage of oauth.OAuthDataStore in my class DataStore. Kindly help. -
You are trying to add a non-nullable field 'id' to useraccount without a default - django
i have this models and when i try to write python manage.py makemigrations it say You are trying to add a non-nullable field 'id' to useraccount without a default; we can't do that (the database needs somet hing to populate existing rows). my models.py : class UserAccount(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Profile_Image = models.ImageField(upload_to='images/',null=True, blank=True) slug = models.SlugField(unique=False) # new def save(self, *args, **kwargs): if not self.id or not self.slug: super(UserAccount, self).save(*args, **kwargs) self.slug = slugify(f"{self.user}") super(UserAccount, self).save(*args, **kwargs) def get_image(self): if self.Profile_Image and hasattr(self.Profile_Image, 'url'): return self.Profile_Image.url else: return '/path/to/default/image' def __str__(self): return self.name what is the error here -
Django djoser has two same urls
I'm reading about Djoser framework for Django. I found that there are two url patters to include, both of which are the same: urlpatterns = [ (...), url(r'^auth/', include('djoser.urls')), url(r'^auth/', include('djoser.urls.jwt')), ] I thought that Django always takes the first match How is it possible that the second path is picked? -
Decrypt in django by using spring boot api
I have a django project and spring project from : in spring project cipher using and in reactjs cryptojs using and in django project i am hitting api of spring boot and i am able to get data but it is in encryption format so how ? i will decrypt that data in django project please help me with proper guidance and flow -
Django creates new user every time doing sign in with apple
I implemented sign in with apple backend on Django by looking this repository's code: https://github.com/truffls/sign-in-with-apple-using-django/blob/master/backend.md. I made very little changes to the code which should not affect to any logic(like changing declaration name and etc.) It strangely re creates a new user every time an iOS app signs in with sign in with apple. I there any way to fix this? class AppleOAuth2(BaseOAuth2): """ Custom BaseOAuth2 backend class for Sign in with Apple Usage: Add this to AUTHENTICATION_BACKENDS on settings.py """ name = 'apple' ACCESS_TOKEN_URL = 'https://appleid.apple.com/auth/token' SCOPE_SEPARATOR = ',' ID_KEY = 'uid' @handle_http_errors def do_auth(self, access_token, *args, **kwargs): """ Finish the auth process once the access_token was retrieved Get the email from ID token received from apple do_auth override this method as you need to verify the code or access token given by mobile client from apple and get the ID token from which other details can be extracted. """ ## Retrieve django project stored data client_id, client_secret = self.get_key_and_secret() headers = {'content-type': "application/x-www-form-urlencoded"} data = { 'client_id' : client_id, 'client_secret': client_secret, 'code' : access_token, 'grant_type' : 'authorization_code', 'redirect_uri' : 'https://example-app.com/redirect' } ## Form data # ID Token(= from AppleID Service) res = requests.post(AppleOAuth2.ACCESS_TOKEN_URL, data = data, headers = … -
Active Directory Authentication - Django & Angular
I am currently working on a web app written with Django as the backend and Angular as the frontend. The webapp will be deployed on an enterprise network, which uses smartcard to authenticate the users with the Active Directory upon login to windows, and I want to use that authentication to automatically login users to my site and get their info, without password / registration / login page. I searched a lot about how we can integrate this smart card authentication with out app but could not find something that uses smartcards / Windows authentication, at least not that I understand that supports it. Any lead on where / what should I look for? -
Django not sending email when attachment size is near to 1 mb Error message SMTPServerDisconnected
I am able to send email with django, in normal course. But when size of attachment is more than few hundred kb, it is showing error. i am not able find the exact cause. i tried changing mysql my.conf max_allowed_packet=10M SMTPServerDisconnected at /sendemail/forfinal Server not connected Request Method: GET Request URL: http://10.0.10.106/assetlist/sendemail/forfinal?doeinput=27-Mar-2021&dofentryinput=2021-04-02 Django Version: 3.1.6 Exception Type: SMTPServerDisconnected Exception Value: Server not connected Exception Location: c:\python\lib\smtplib.py, line 357, in send Python Executable: C:\xampp\apache\bin\httpd.exe Python Version: 3.7.9 . . . . During handling of the above exception ([WinError 10054] An existing connection was forcibly closed by the remote host), another exception occurred: . . . -
Django query self referencing queryset
I have a model Thing that is self referencing. The relation copied_from is being used to save the Thing-Object that the current Thing-Object was copied from. Here is my Model: class Thing(models.Model): copied_from = models.ForeignKey("Thing", related_name="copies", null=True, default=None, on_delete=models.SET_NULL) collection = models.ForeignKey(Collection, ...) ... What I would like to achieve is to get all Things from a collection that have no been copied. I was thinking about using unionto take all Things and "substract" all things that have been copied. The issue is that in my solution I had to iterate over the Queryset where copied_from__is_null=False to get the ids of Things that have been used to create a copy. This is of course not a good solution. -
Django Djoser Token Authentication not working
TLDR: How and where do I get a user's token after logging in and pass it as a header on all subsequent restricted URLs using Django/Djoser? I'm trying to create a user login/sign up using Djoser. On the backend after logging in, I get the auth token but then when I try to access any other pages (e.g. /users/me) it says: { "detail": "Authentication credentials were not provided." } I looked online and everywhere says I need to pass the authentication token in the header but all the examples I see use Postman or curl and they just copy and paste the token into the header section. But I want to use Django to do it without knowing the token. I've seen to use token = request.META['HTTP_AUTHORIZATION'] in order to get the token but I'm not sure where to put it because all I've got is urlpatterns = [ path('', include('djoser.urls')), path('', include('djoser.urls.authtoken')), ] in my urls.py file and that's supposed to handle everything for me, so I don't have anything in my views.py or models.py And then to pass the token value as header I've seen to use the Python requests package: import requests response = requests.get('https://website.com/id', headers={'Authorization': 'access_token … -
How to use Django reset password without using User model class
I have created a custom register model and have used it for registration but now i cannot implement the Django forgot password because it uses Django User model. So is their any solution for this please help -
Terminate Django views function after x seconds
I have a function in my views.py and I want that function to run for 10 seconds after the button click if the output is produced run the whole function else terminate it and show the home page. -
Webpack tries to resolve deleted CSS file (module)
I have a React application where I want to use webpack (and babel). After having a lot of trouble doing so, I decided to clean up my program and remove my CSS files (to simplify everything). While I managed to get rid of some errors this way, I got a new one that I simply can't fix. Now I get the error message : ERROR in ./src/App.js Module not found: Error: Can't resolve './App.css' in 'C:\Users\Garbers\harvardedx\finalproject\finalproject\frontend\src' @ ./src/App.js 1:0-19 @ ./src/index.js I really don't know where the problem lies. webpack.config.js: const path = require("path"); const webpack = require("webpack"); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: "development", entry: "./src/index.js", output: { path: path.join(__dirname, "dist"), filename: "bundle.js", }, devServer: { contentBase: path.join(__dirname, 'dist'), }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: { loader: "babel-loader" }, }, ], }, optimization: { minimize: true, }, plugins:[ new HtmlWebpackPlugin({ template: './dist/index.html', filename: 'index.html', inject: 'body' }) ] }; package.json: { "name": "frontend", "version": "0.1.0", "private": true, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.13.0", "@material-ui/core": "^4.11.3", "@testing-library/jest-dom": "^5.11.10", "@testing-library/react": "^11.2.6", "@testing-library/user-event": "^12.8.3", "babel-loader": "^8.1.0", "react-router-dom": "^5.2.0", "react-scripts": "4.0.3", "web-vitals": "^1.1.1", "webpack-dev-server": "^3.11.1" }, "scripts": { "start": "webpack --mode=development", "build": "webpack --mode=production", "dev-server": "webpack-dev-server", "test": "react-scripts … -
How to change my Heroku management command to use a worker dyno
I am new to all things Heroku/Django so apologies if this question is elementary. I've developed my first minor app using Django and have just deployed it into Heroku. A major part of the app is that I have a scraper that scrapes about 150K records and dumps the data into my Heroku Postgres database...it takes about 2.5 hours to run - ideally, I'd like this to run every other day but for now, that is another issue. As of right now I have this scraper in a management command in my project and when I want to run it I manually use: heroku run python manage.py scrape_data I inspected my logs while this was running and noticed it is using a one-off-dyno as opposed to a worker which I read was better for long-running jobs like mine. My question is, how can I change my Procfile (or something else) so that Heroku knows to use a worker dyno whenever I execute this task? If it's something I can add to the Heroku scheduler that'd be great to solve, though from what I understand those exclusively use one-off dynos so that is probably out of the question. Here's my current … -
TabError: inconsistent use of tabs and spaces in indentation in views - Django
i am trying to create register in views but i got this error TabError: inconsistent use of tabs and spaces in indentation in views - Django error at line 32 if user_form.is_valid() and profile_form.is_valid(): views.py : def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserAccountForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): # line 32 user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'app_image' in request.FILES: profile.app_image = request.FILES['app_image'] profile.save() registered = True else: print(user_form.errors,profile_form.error) else: user_form = UserForm() profile_form = UserAccountForm() return render(requset,'user/regiseter.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered}) how i can fix this error -
Django REST framework hide a specific serializer field
I want to know how to hide a specific field in serializer(ModelSerializer) Example Models.py class Book(models.Model): title = models.CharField(max_length=30) author = models.CharField(max_length=30) hide_this_one = models.CharField(max_length=30) # hide this field serializers.py class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' views.py class BookApiView(views.APIView): template_name = 'book/create-book.html' permission_classes = (AllowAny, ) renderer_classes = [TemplateHTMLRenderer] def get(self,request,*args,**kwargs): serializer = BookSerializer() return Response({'serializer':serializer}) I want to hide the hide_this_one field when the serializer is rendered to HTML And I need the hide_this_one field on the html but stay hidden(<input type="hidden" ......>) Please tell me how to hide the label if you change the field in style. Example: class BookSerializer(serializers.ModelSerializer): hide_this_one = serializers.CharField(...., style={'input_type':'hidden'}) class Meta: model = Book fields = '__all__' Thanks for the help! -
query set object could not be shown in website in Django
I have used Django2 in python3.7 to develop a web app in windows. I want to show a list of query set in html. view.py: @csrf_exempt def View_by_Course_list(request): print(request.method) if request.method == 'POST': ... query_results_book = Title.objects.filter(id=query_results_book_id).values() print(query_results_book) return render(request, 'list.html', context={'query_results_book': query_results_book}) list.html: {{query_results_book}} <ol> {% for obj in query_results_book %} <li>{{obj.title}} <br> iSBN:{{obj.isbn}} <br> Format issued: {{obj.is_etextbook}}</li> {% endfor %} </ol> The print debug, print(query_results_book) outputs this: <QuerySet [{'id': 4, 'created': datetime.datetime(2020, 6, 25, 10, 15, 41, 856235), 'isbn': 11112, 'is_etextbook': 'Textbook', 'title': 'ACC210 Accounting for Decision Making and Control (customised text), McGraw-Hill'`}]> But in the website page nothing is shown. I have added {{query_results_book}} in the html for debug, but also nothing shown. -
Show only most viewed post from last 2 days
I am building a BlogApp and I am stuck on a Problem. What i am trying to do:- I am trying to access only BlogPosts which is mostly viewed in last 2 days. models.py class BlogPost(models.Model): blog_post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_blog_posts',editable=False) views.py def viewd_post(request): d = timezone.now() - timedelta(days=2) posts = BlogPost.objects.annotate(total_views=Count('viewers')).filter(date_added__gte=d).order_by('-total_views') context = {'posts':posts} return render(request, 'most_views.html', context) What have i tried :- I also tried annotate method to get most viewed post, It works perfectly like : it shows most viewed blogpost at top but it shows all the posts which are posted in last two days and got no views. Any help would be Appreciated. Thank You in Advance. -
SAML2 with Django stuck on infinite loop
I am trying to use the djangosaml2 1.1.0 module in order to implement SSO login. After the successful login, it gets stuck in an infinite loop trying to constantly login again. I have tried to remove the @login_requried decorator, it works on then. But, I need the @login_required decorator in order to prevent not logged in users to access specific views. My believe is that django.contrib.auth.backends.ModelBackend is not properly configured with djangosaml2.backends.Saml2Backend This is my code: settings.py SAML_CONFIG = { # full path to the xmlsec1 binary programm 'xmlsec_binary': '/usr/bin/xmlsec1', # your entity id, usually your subdomain plus the url to the metadata view 'entityid': 'http://localhost:8000/saml2/metadata/', # directory with attribute mapping 'attribute_map_dir': path.join(BASEDIR, 'attribute-maps'), # this block states what services we provide 'service': { # we are just a lonely SP 'sp' : { 'name': 'Federated Django sample SP', 'name_id_format': saml2.saml.NAMEID_FORMAT_PERSISTENT, # For Okta add signed logout requets. Enable this: # "logout_requests_signed": True, 'endpoints': { # url and binding to the assetion consumer service view # do not change the binding or service name 'assertion_consumer_service': [ ('http://localhost:8000/tacdb/items/', saml2.BINDING_HTTP_POST), ], # url and binding to the single logout service view # do not change the binding or service name 'single_logout_service': [ … -
Django Q Filter - Too many Values to unpack
I want to dynamicly create some filter criteria depending on the url query params. For this I created a nested Django Q-Object which looks like: query = <Q: (AND: (OR: region=30, region=39), name__endswith=Hannover, zip_code=30165)> Now I want to pass this Q object to Model-Filter Eort.objects.filter(query) Thereby I get a ValueError : too many values to unpack (expected 2) Traceback (most recent call last): File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\felix\Documents\WZO\WZO\WZO_App\views.py", line 47, in get log.debug(Eort.objects.filter(eq)) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1380, in _add_q split_subq=split_subq, check_filterable=check_filterable, … -
scheduled web scraper using django and celery
I want to scrape multiple websites at every 15 minutes. If there's no update (new feed) found after 5 tries, I want to stop the worker and trigger a notification. I have tried the following: @app.task def scrape(): urls = Website.objects.all() for obj in urls: s_data = scrape(obj.url) for s in s_data: ser = WebsiteSerializer(data=s, many=True) ser.is_valid() ser.save() return 'updated' Celery config: app.conf.beat_schedule = { # Executes every 15 min 'scrape': { 'task': 'app.tasks.scrape', 'schedule': crontab(minute='*/15') }, } I am not sure if I should put a range function in scrape to execute 5 times and delay or there is a way to configure the celery settings? -
make django2exe python3.9 compatible
I want to use django2exe to run my django project. The problem is that it's using Python-2.7.10 and my django project is using Python3.9.1. I have tried replacing the Python-2.7.10 folder with Python3.9.1 folder and still not working, I don't know if I'm doing it right. -
Server taking too long to respond and I'm getting response 504 Gateway Time-out when running Docker, Nginx, Gunicorn
I have implemented an endpoint to upload excel file and then save the records into the database. Tested running locally on machine environment without using docker; When the request is made the file is uploaded, read and records saved on DB successfully and I get the response as a success. When I run on docker the request is taking too long and then get a 504 Gateway Time-out. logs: worker_1 | [2021-04-05 08:49:28,229: INFO/MainProcess] celery@e7d1cfa8d332 ready. appseed-app_1 | [2021-04-05 08:52:48 +0000] [11] [DEBUG] POST /api/uploaded_files/ nginx_1 | 2021/04/05 08:53:50 [error] 22#22: *2 upstream timed out (110: Connection timed out) while reading response header from upstream, client: x.x.x.x, server: , request: "POST /api/uploaded_files/ HTTP/1.1", upstream: "http://x.x.x.x:5006/api/uploaded_files/", host: "localhost:86" nginx_1 | x.x.x.x - - [05/Apr/2021:08:53:50 +0000] "POST /api/uploaded_files/ HTTP/1.1" 504 167 "-" "PostmanRuntime/7.26.10" "-" appseed-app_1 | [2021-04-05 11:54:19 +0300] [1] [CRITICAL] WORKER TIMEOUT (pid:11) appseed-app_1 | [2021-04-05 08:54:19 +0000] [11] [INFO] Worker exiting (pid: 11) appseed-app_1 | [2021-04-05 11:54:19 +0300] [24] [INFO] Booting worker with pid: 24 Questions Why is this happening? How do I fix this problem. I attempted to increase gunicorn's timeout to 90 and added 4 workers in the gunicorn-cfg.py file and also did a couple of changes to … -
Reset Password Using Django
I am trying to reset password using Django but I am getting the following error: Method Not Allowed (POST): /reset/done/ Method Not Allowed: /reset/done/ Below is my form: <form action="{% url 'password_reset_complete' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="password" class="form-control" name="new_pass" placeholder="New Password" required autofocus> </div> <div class="form-group"> <input type="password" class="form-control" name="confirm_pass" placeholder="Confirm Password" required> </div> <input type="submit" value="Update Password" class="btn btn-primary btn-block"> </form> URL path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='feebeeapp/login.html'), name='password_reset_complete') Not sure, what I am doing wrong. Can someone please guide me? -
! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/cardamageapp.git'
I followed the exact steps as mentioned in the article 'https://medium.com/bithubph/how-to-deploy-your-django-applications-on-heroku-8b58fdb09dd0', while deploying my django project to heroku. However, I am getting the following error: [git push heroku master][1] Please could anyone let me know what could be the possible issue. FYI: I have the Procfile, requirements.txt, runtime.txt in my project root directory. I am also sure my credentials are correct. Also, I havnt pushed anything to master before and I am the only owner of this app. My runtime.txt has the code: python: 3.7.9. My Procfile has the code: web: gunicorn cardamage.wsgi --log-file - My requirements.txt: absl-py==0.12.0 astunparse==1.6.3 cachetools==4.2.1 certifi==2020.12.5 chardet==4.0.0 cycler==0.10.0 dj-database-url==0.5.0 Django==1.10 django-heroku==0.3.1 gast==0.3.3 google-auth==1.28.0 google-auth-oauthlib==0.4.4 google-pasta==0.2.0 grpcio==1.36.1 gunicorn==20.1.0 h5py==2.10.0 idna==2.10 importlib-metadata==3.10.0 joblib==1.0.1 Keras==2.4.0 Keras-Applications==1.0.8 Keras-Preprocessing==1.1.2 kiwisolver==1.3.1 Markdown==3.3.4 matplotlib==3.4.1 numpy==1.20.2 oauthlib==3.1.0 opt-einsum==3.3.0 pandas==1.1.5 pickle5==0.0.11 Pillow==8.2.0 protobuf==3.15.7 psycopg2==2.8.6 pyasn1==0.4.8 pyasn1-modules==0.2.8 pyparsing==2.4.7 python-dateutil==2.8.1 pytz==2021.1 PyYAML==5.4.1 requests==2.25.1 requests-oauthlib==1.3.0 rsa==4.7.2 scikit-learn==0.24.1 scipy==1.4.1 seaborn==0.11.1 six==1.15.0 tensorboard==2.2.2 tensorboard-plugin-wit==1.8.0 tensorflow==2.2.0 tensorflow-estimator==2.2.0 termcolor==1.1.0 threadpoolctl==2.1.0 typing-extensions==3.7.4.3 urllib3==1.26.4 Werkzeug==1.0.1 whitenoise==5.2.0 wrapt==1.12.1 zipp==3.4.1