Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Amazon EC2 Instance using HTTPS?
How to Launch EC2 Instance using secure HTTP i.e; HTTPS Right now when I launch it and Associate and Elastic IP with it. It goes through HTTP and not HTTPS For Example - Suppose the Elastic IP is - 3.45.53.122 So when I launch a Django app using python manage.py runserver 0.0.0.0:80 and When I use another Computer or Mobile device and go to http://3.45.53.122/MyApp It works fine. But I want to use HTTPS.. any idea how to use it in EC2 Instance? -
Docker volume does not consistently update code
I am running a web server in docker container with the code mounted as a volume. I start the development server using docker-compose. In one of the server's Python files, I've put the following line that is executed on every refresh: print('1') After building it, it works fine. If, however, I change it to: print('2') without rebuilding, I expect to get '2' printed consistently but I get 1 and 2 printed randomly every refresh until I restart. Is this expected behavior? I don't want to restart the container each time I make a change. What would be the best solution for development? I am using IntelliJ PyCharm Professional Edition. version: '3' volumes: app: static: services: python_web_server: &python_web_server build: context: . dockerfile: python/Dockerfile volumes: - ../app:/app - ../app/static:/static command: bash -c "cd /app && gunicorn -w 4 webapp.wsgi -b 0.0.0.0:8000" depends_on: - rabbitmq - celery_worker -
issues while searching models in wagtail django
I'm having a bit of crisis in searching models in wagtail django This is my code for model objects recipes = RecipePage.objects.child_of(self).live().public() \ .select_related('listing_image') extra_url_params = '' error_message=False filter_categories_raw = request.GET.get('categories') filter_categories = False filter_name = request.GET.get("name") if filter_categories_raw: filter_categories = [] filter_categories_raw = filter_categories_raw.split(",") for fc in filter_categories_raw: try: value = int(fc) filter_categories.append(value) except ValueError: filter_categories = False error_message = "Invalid category value" if filter_categories: for filter_category in filter_categories: recipes = recipes.filter(categories__category=filter_category) if filter_name: recipes = recipes.search(filter_name, recipes) <---- issue here if not filter_name: filter_name="" My RecipePage model I added search_fields = BasePage.search_fields + [ index.SearchField('title'), ] Now when I do this for searching, recipes = recipes.search(filter_name, recipes) it gives me error Can't convert 'RecipePage' object to str implicitly When I do this recipes = recipes.search(filter_name, recipes.title) or recipes = recipes.search(filter_name, recipes.objects) It gives me 'PageQuerySet' object has no attribute 'title' I'm stoned. What am I doing wrong? -
In django, how can i upload file via url?
Hi i'm making my own webserver using django. i just want to upload local file to django server. i google every method but i can't get answer. every method using form or html but i don't want to using form and html example : from www.localfolder/example.txt to /media/examplefolder. i don't know how to do.. any help? this is my code. @csrf_exempt def download_file(request, file): fl_path = 'media/' filename = str(file) fl = open(fl_path, 'r') mime_type, _ = mimetypes.guess_type(fl_path) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename = %s" % filename return response -
Wrapping a BlockFeature in Draftail (Wagtail Rich Text Editor)
I am stuck at a problem. Maybe someone of you does have an Idea. The Problem looks like following: We have in Wagtail for the Draftail Editor 2 possible Features. Which are BlockFeature and InlineStyleFeature. But what, if you want to add a Feature in the Rich Text Editor, which should wrap an BlockFeature? As example: H1,H2,H3 etc. are BlockFeatures. I have done an custom Feature which will highlight stuff with an border, i did that with the InlineStyleFeature. So, this works properly on normal plaintext. But when you are adding some BlockFeatures like a H1 or a H2 the InputStyleFeature will automatically wrap inside the other Block Features. Example: Without Border: Some Plain Text <h1> Test </h1> With Border: <border> Some Plain Text <h1><border> Test </border> </h1> </border> The thing i want to accomplish is a simple : <border> Some Plain Text <h1> Test </h1> </border> When i am using a Border as a BlockFeature, the Headline Tags and all other BlockFeatures will be gone logically. So.. my question is : Is there any way to accomplish something like that ? Does anyone has experience with that kind of stuff? I would be happy if someone could help me. … -
Django models, dealing with multiple foreign keys
I'm busy dealing with datasets based on Freshwater Lakes in the USA. So my models are basically State and Lake. State being a foreign key in Lake. As I started loading data, I quickly realised that it appears that some Lakes are bordering multiple states. Example Lake Erie goes into 4 states + an international border. I then had to rethink my models a bit and came up with the following, class State(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return str(self.name) class Lake(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE, verbose_name="primary state", related_name="related_primary_state", help_text="Primary State") state_secondary = models.ForeignKey(State, on_delete=models.CASCADE, null=True, blank=True, related_name="related_secondary_state", verbose_name="secondary state", help_text="Secondary State") state_three = models.ForeignKey(State, on_delete=models.CASCADE, null=True, blank=True, related_name="related_three_state", verbose_name="three state", help_text="three State") state_four = models.ForeignKey(State, on_delete=models.CASCADE, null=True, blank=True, related_name="related_four_state", verbose_name="four state", help_text="four State") state_five = models.ForeignKey(State, on_delete=models.CASCADE, null=True, blank=True, related_name="related_five_state", verbose_name="five state", help_text="five State") name = models.CharField(max_length=200, null=True) def __str__(self): return str(self.name) Would this be okay to do, or are there better ways to approach this? Thanks! -
Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['edit/(?P<page>[^/]+)$']
I'm trying to code wiki plagia. But I got this unexpected error: Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['edit/(?P[^/]+)$']. So there is the page of the Python Function who redirect it. {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <form method=POST action="{% url 'edit' %}"> {% csrf_token %} <label>The Title Of Your Wiki Page</label> <input type="text" name="Title" value="None"> <label>The Content Of Your Wiki Page</label> <input type="text" name="Content" value="None"> <input type="submit" value="Submit Your Wiki Page" value="None"> </form> {% endblock %} And there is my Python Function : def edit(request): print(page) return render(request,"encyclopedia/edit.html") The path fuction in urls.py: path("edit/<str:page>", views.edit, name="edit") -
First Heroku deploy failed `error code=H10` django
2020-08-06T12:21:33.078655+00:00 app[web.1]: [2020-08-06 15:21:33 +0300] [11] [INFO] Worker exiting (pid: 11) 2020-08-06T12:21:33.079530+00:00 app[web.1]: [2020-08-06 15:21:33 +0300] [10] [INFO] Worker exiting (pid: 10) 2020-08-06T12:21:33.267992+00:00 app[web.1]: [2020-08-06 12:21:33 +0000] [4] [INFO] Shutting down: Master 2020-08-06T12:21:33.268123+00:00 app[web.1]: [2020-08-06 12:21:33 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-08-06T12:21:33.365498+00:00 heroku[web.1]: Process exited with status 3 2020-08-06T12:21:33.412212+00:00 heroku[web.1]: State changed from up to crashed 2020-08-06T12:28:10.624445+00:00 app[api]: Starting process with command python3 manage.py migrate by user covid19estimator@gmail.com 2020-08-06T12:28:18.428944+00:00 heroku[run.1641]: State changed from starting to up 2020-08-06T12:28:18.445437+00:00 heroku[run.1641]: Awaiting client 2020-08-06T12:28:18.467153+00:00 heroku[run.1641]: Starting process with command python3 manage.py migrate 2020-08-06T12:28:24.657902+00:00 heroku[run.1641]: Process exited with status 0 2020-08-06T12:28:24.690587+00:00 heroku[run.1641]: State changed from up to complete 2020-08-06T12:29:30.510298+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=barablog.herokuapp.com request_id=3fd8546e-d99a-4a2b-9456-9074506bb3f8 fwd="102.166.4.30" dyno= connect= service= status=503 bytes= protocol=https 2020-08-06T12:29:33.147084+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=barablog.herokuapp.com request_id=41abf53e-d5d8-4e04-b9ef-eb69571727f1 fwd="102.166.4.30" dyno= connect= service= status=503 bytes= protocol=https PROCFILE web: gunicorn Blog.wsgi --log-file - -
Django: File upload loading animation
I was just wondering if there's any way I can make/show a loading animation show up while my media file is being uploaded on the server by user? -
docker-compose up command not responding
I am using Ubuntu and tried to run Django with Docker. When I give docker-compose run command it give below output Starting aug6_web_1 ... done Attaching to aug6_web_1 web_1 | Watching for file changes with StatReloader and it give no other output ... for almost 20 min now. docker-compose.yml version: '3' services: web: build: context: ./ command: python manage.py runserver 127.0.0.0:8000 volumes: - .:/AUG6 ports: - '8000:8000' Dockerfile FROM python:3 ENV PYTHONBUFFERED 1 RUN mkdir /AUG6 WORKDIR /AUG6 COPY /requirements.txt /AUG6/ RUN pip install -r requirements.txt COPY . /AUG6/ Very first day of learning Docker, excuse if any mistakes -
How to see the query (NOT SQL) in a variable with all the parameters without evaluating it in Django?
Suppose I have a form and from it returns data. After processing and several if-else statements with respect to the data( for example, the initial query might be x = User.objects.filter(active=True) and after that, suppose a value from the form say created_before is present then the query is further changed to x.filter(created_at__lte=created_before) and so on.), the variable x will have a query. I want to be able to see that final query without evaluating it. If I use the .query it only returns the RAW SQL query. If I print the variable the query gets executed. Is there a way to do this? -
Django dynamic forms - problem creating a select widget (dropdown)
I am using Django 2.2. I am creating a dynamic form (unbound to a model). I have managed to create several form inputs dynamically (including inputs accepting more than one choice), but I am having problems creating a select (i.e. dropdown) form input element. When I render my form using {{ form.as_p }} in my template, the select form field is being rendered as checkbox instead. I have tried ALL of the statements below, and the result is the same: the form input field is still rendered as a checkbox. form_field = CharField(label=the_label, widget=forms.Select(choices=CHOICES, required=is_required)) form_field = ChoiceField(label=the_label, choices=CHOICES, widget=Select, required=is_required) form_field = ChoiceField(label=the_label, widget=Select(choices=CHOICES), required=is_required) How do I force django to render this field as a select (drop down) field? -
How can I use email instead of username in djangoreostframework-simplejwt?
I am going to use email instead of username when I get access token and refresh token using djangoreostframework-simplejwt. So after writing the code, I could access my browser and confirm that the field that was username was renamed to email.But when I post the email of user in email field, the following error appears. "detail": "No active account found with the Given Credentials" Can you tell me what is wrong with my code? Here is my code. Serializers.py from rest_framework_simplejwt.serializers import TokenObtainSerializer from django.contrib.auth.models import User class EmailTokenObtainSerializer(TokenObtainSerializer): username_field = User.EMAIL_FIELD class CustomTokenObtainPairSerializer(EmailTokenObtainSerializer): @classmethod def get_token(cls, user): return RefreshToken.for_user(user) def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data["refresh"] = str(refresh) data["access"] = str(refresh.access_token) return data views.py from rest_framework_simplejwt.views import TokenObtainPairView from .serializers import CustomTokenObtainPairSerializer class EmailTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer thanks -
Override the django translation method
I wish to find a simple way to override the gettext method use by Django. I wish to create my own method and tell Django to use it everywhere (.py, Template …). In my .py it's simple, I can use my new method directly but in the Django engine I do not know how to do it ? My aim is to use a database of translations + Google Cloud Translation. I do not find a way to do it … but Django si perfect, so I suppose there is a way ? :) -
Django Email issues while sending to others
@ Code is in settings.py and removed the line in the settings.py EMAIL_BACKEND = ‘django.core.mail.backends.smtp.EmailBackend EMAIL_HOST= 'smtp.gmail.com' EMAIL_HOST_USER= 'xxx@gmail.com' EMAIL_HOST_PASSWORD='app-specific-pass-word' EMAIL_USE_TLS= True EMAIL_PORT= 587 My question is if any current user login in the application(like leave application) and he raise a request other user have received the emails notification from the application, but why mail is going to the EMAIL_HOST_USER= ‘xxx@gmail.com’ instead of current login user email id . I need to other person receive from the current login user email id not from the “EMAIL_HOST_USER” Thanks -
Is it possible to store video and audio in django database?
I am trying to create a diary entry application using django which has video and audio input options. What i want is: 1)Create start recording button in my template which seek camera and audio permissions and start recording 2)Create a stop recording button which will send the recording to my views.py function and that function will store the video/audio as an object of class created in models.py Are these two steps possible to achieve with html and javascript as frontend and django in backend? -
Can't get Login through Facebook in python, Kindly guide me
setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo', 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'social_django', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.linkedin.LinkedinOAuth2', 'social_core.backends.instagram.InstagramOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ]SITE_ID = 1 LOGIN_REDIRECT_URL = 'index' index.html (My login page through Facebook) I set each and everything {% load socialaccount %} {% providers_media_js %} <body> Hello {{user.username}} Weclome:<be> <button><a href="{% provider_login_url 'facebook' method = 'oauth2' %}"> Login Through Facebook </a></button> When I log in to Facebook it gives me that Error (Django_API) is my app name on Facebook for developers site Error ! Facebook has detected that Django_API isn't using a secure connection to transfer information. Until Django_API updates its security settings, you won't be able to use Facebook to log in to it. Kindly help me how can I login in my site through Facebook API. -
How to fetch image from django FileResponse using javascript
I would like to render an image in html using javascript, and the image is being retrieved from a django view using the fetch api. I think I am close but can't figure out how to display image in browser using javascript. view #1: (url: builds/imgretrieve/int:device/) class imgRetrieve(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): device = self.kwargs['device'] deviceVals = CustomUser.objects.get(id=device) buildImg = ImageRequest.objects.filter(author = deviceVals).latest("dateAdded") return FileResponse(buildImg.image) When I access this view directly using a browser, it displays an image as expected. However when I want the javascript to display it in a different view, it just displays [object Response] instead of the image. Here is how I am attempting to do this: view #2 (url: builds/chamberCam/int:device/) class chamberCamView(LoginRequiredMixin,TemplateView): template_name = 'chamberCam.html' login_url = 'login' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) device = self.kwargs['device'] deviceVals = CustomUser.objects.get(id=device) CustomUser.objects.filter(id = device).update(imgRequested = True, imgReceived = False,) context['deviceName'] = deviceVals.UserDefinedEquipName context['deviceID'] = deviceVals.id return context html {% block body %} <p hidden id = "id">{{ deviceID }}</p> <div class="">Chamber cam for {{deviceName}}</div> <div class="imageDiv" id = "image"> </div> {% load static %} <script src="{% static 'camera/chamberCam.js' %}"></script> {% endblock %} chamberCam.js let deviceID = document.getElementById("id").innerHTML; getImg(deviceID) function getImg(deviceID){ fetch('http://127.0.0.1:8000/builds/imgretrieve/' + … -
Deplying Django to Heroku - DisallowedHost Error despite Heroku URL in DJANGO_ALLOWED_HOSTS
I've been at this for hours and need help. Initially I thought it was because I had mistakenly done something small that caused it, so I deleted the app, and created everything - virtual env, heroku app, django projects/apps - fresh. I get the same error. I made a cookiecutter django app and deployed it to heroku. Everything goes smoothly until it's time to actually use the site. When I run heroku open, I get the DisallowedHosts error: DisallowedHost at / Invalid HTTP_HOST header: 'MY-NEW-APP.herokuapp.com'. You may need to add 'MY-NEW-APP.herokuapp.com' to ALLOWED_HOSTS. heroku config shows that DJANGO_ALLOWED_HOSTS=MY-NEW-APP.herokuapp.com. I don't overwrite it in my settings file. I have import django_heroku and django_heroku.settings(locals()) in my settings file. DJANGO_SETTINGS_MODULE is correctly set to that file. What's more, I get a warning about DEBUG=True, when DEBUG=False in my settings file and in the heroku environment. What am I missing? Are hyphens a bad thing? Should I be using herokuapp.com instead of the full URL? -
Django Google login does not work for some users
I have implemented google login in my django website through allauth. But it does not work for some users. I don't know how do I fix this. I have double checked the links I entered in the redirect URI in OAuth and the sites model in Django. I have not entered any extra "/" or "www". I have matched it exact to the domain. I still don't get it. -
Need guide on how can I connect Integrate multiple IDP's on Pysaml2 project
I would like to add one more SSO in my current project. Can anyone please guide me or share some resources on how can I configure my django project to do so. I am using pysaml2 and django. Thank you. -
DRF - how get auth token, for users that login/register with google API?
I have nice working google login/register - users can easily login/register using it, when it comes to logging in/creating account on website. I am using following packages: 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google' I have another kind of problem - my frontend (React Native app) works with 'rest_framework.authentication.TokenAuthentication'. Every request made from frontend has this header: 'Authorization': 'Token ' + auth_token. Here the problem comes - how am I supposed to use googe auth for my app? Is there any way to create Auth Token (in the db) for user that is registered with google? -
! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/stark-dawn-54447.git'
Im new to Django / Python and trying to deploy my first project to Heroku. Im getting the following error and have been following this guide to the letter: 'Django for beginners' by William S Vincent. When I run: $git push heroku master I get this: error: ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/stark-dawn-54447.git' I've included all of the code returned below... Many thanks -----> Python app detected -----> Installing python-3.8.5 -----> Installing pip 9.0.2, setuptools 47.1.1 and wheel 0.34.2 -----> Installing dependencies with Pipenv 2018.5.18… Traceback (most recent call last): File "/tmp/build_4d226441/.heroku/python/lib/python3.8/site-packages/pipenv/patched/prettytoml/elements/abstracttable.py", line 27, in _enumerate_items yield next(non_metadata), next(non_metadata) StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/pipenv/project.py", line 438, in _parse_pipfile return contoml.loads(contents) File "/tmp/build_4d226441/.heroku/python/lib/python3.8/site-packages/pipenv/patched/contoml/__init__.py", line 15, in loads elements = parse_tokens(tokens) File "/tmp/build_4d226441/.heroku/python/lib/python3.8/site-packages/pipenv/patched/prettytoml/parser/__init__.py", line 17, in parse_tokens return _parse_token_stream(TokenStream(tokens)) File "/tmp/build_4d226441/.heroku/python/lib/python3.8/site-packages/pipenv/patched/prettytoml/parser/__init__.py", line 29, in _parse_token_stream elements, pending = toml_file_elements(token_stream) File "/tmp/build_4d226441/.heroku/python/lib/python3.8/site-packages/pipenv/patched/prettytoml/parser/parser.py", line 375, in toml_file_elements captured = capture_from(token_stream).find(one).or_find(file_entry_element).or_empty() File "/tmp/build_4d226441/.heroku/python/lib/python3.8/site-packages/pipenv/patched/prettytoml/parser/recdesc.py", line 33, in find element, pending_ts = finder(self._token_stream) File "/tmp/build_4d226441/.heroku/python/lib/python3.8/site-packages/pipenv/patched/prettytoml/parser/parser.py", line 372, in one c1 = capture_from(ts1).find(file_entry_element).and_find(toml_file_elements) File "/tmp/build_4d226441/.heroku/python/lib/python3.8/site-packages/pipenv/patched/prettytoml/parser/recdesc.py", line 109, in and_find return Capturer(self.pending_tokens, self.value()).find(finder) File … -
Wagtail serialize non-page models
i've recently trying to convert my current wagtail project to become headless using the wagtail v2 api , everything is working great when serializing page related data , however im having difficulty finding resources on how to serialize non-page data. Heres an example of the menu system that im using: class NavigationBar(models.Model): companySettings = ParentalKey('CompanySettings', related_name='navi_links' , null=True , blank=False) link_display_name = models.CharField(max_length=100,null=True,blank=False) link = models.ForeignKey( "wagtailcore.Page", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) panels= [ FieldPanel('link_display_name'), PageChooserPanel('link'), ] This model is used to create a menu like system within my project . Would appreciate any help in allowing me to expose a api endpoint for these types of data -
Django and Azure SQL key error 'deferrable' when start migrate command
I try connect django to Azure SQL and have error KeyError: deferrable when i start migrate command. i can't find resolution for this issue. i use this application: asgiref==3.2.10 Django==3.1 django-mssql-backend==2.8.1 pyodbc==4.0.30 pytz==2020.1 sqlparse==0.3.1 and this is my config in settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DBNAME', 'USER': 'DBUSER', 'PASSWORD': 'PASSWORD', 'HOST': 'databasename.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } The error is when i try to run 'manage.py migrate`. Everything runs fine until the 8th step. Here's the output: (venv) C:\Users\...\...\>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\...\...\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\...\...\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\...\...\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\...\...\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\...\...\lib\site-packages\django\core\management\base.py", line 85, in wrapped …