Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redis on Docker: Error 111 connecting to 0.0.0.0:6379. Connection refused
Python and Redis work fine together in my local. I try to dockerize the project. When I docker-compose up, redis container works fine. > Server initialized > Ready to accept connections But when I call a request in POSTMAN, I get the following error: Error 111 connecting to 0.0.0.0:6379. Connection refused. My settings: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://0.0.0.0:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } My docker-compose.yml: redis: image: bitnami/redis:latest volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf environment: - ALLOW_EMPTY_PASSWORD=yes ports: - "6379:6379" ...and in Dockerfile: ENV REDIS_URL=redis://0.0.0.0:6379/1 What am I missing? -
Django migrate Killed every time
I uploaded an update to my production server. Every time I run migrate (python manage.py migrate), which took only a few seconds on my development machine, it hangs for a long time and then simply says "Killed". This also bounces me out of the pipenv shell. I have tried using the migrate flags --list, --plan, and --fake, but they all do the same thing, hang and then "Killed." I accidentally ran makemigrations on the production machine first. Is that what screwed it up? How can I find out what is killing the process? And how can I fix it? I desparately need to update the database to run the code that got installed. I have checked the database and none of the changes have been made. Also the migration files in the app have not been corrupted either. I am at a loss here. Frank -
Django field with list of objects
I'm trying to write a model Question which has a field called universities that is supposed to contain many universities, but I dont want to create oneToMany relationship as I just need the reference to University model in Question. I found ModelMultipleChoiceField which is ideal, but it applies only to forms and I can't seem to find anything similar for models. -
Do Django Apps have reserved/illegal names? Imports/makemigrations don't work based on app name
My Django project has several apps, which all have no issue, with the exception of the app called platform. To import from this app, I need to use the full path, rather than being able to import it directly, for example: from app.models import MyModel # Doesn't work for platform app, but it does for others vs from project_root.app.models import Mymodel # Have to do this only for platform app I changed the name from platform to theplatform and it worked. Imports worked without full paths, the makemigrations starting finding the models. The only thing that changed was the name of the app. Each of my apps have an apps.py, with a class inheriting from AppConfig with the name of the app, and all of them are in installed apps. I've also made sure adding/removing init.py doesn't mess with anything. I feel pretty certain the only variable here is the name of the app. Are there reserved or illegal app names in Django? If there are is there a place I can read up on it if there are? The only restriction I'm aware of is not having dashes in the name. -
Requirements.txt dependencies not being deployed with code on azure web app
I've been developing a Django site and have been testing it on a basic tier azure web app, and now its almost finished I've started a production instance, but I've had no luck deploying to it. I'm using basically the same deployment script as I was previously and the deployment logs output looks the same but when the start it fails because Django hasn't been installed, and none of the requirements have been either. this is my deployment script # Python to Linux Web App on Azure # Build your Python project and deploy it to Azure as a Linux Web App. # Change python version to one thats appropriate for your application. # https://docs.microsoft.com/azure/devops/pipelines/languages/python trigger: - Release-0.1 variables: # Azure Resource Manager connection created during pipeline creation azureServiceConnectionId: '' # Web app name webAppName: '' # Agent VM image name vmImageName: 'ubuntu-latest' # Environment name environmentName: '' # Project root folder. Point to the folder containing manage.py file. projectRoot: $(System.DefaultWorkingDirectory) # Python version: 3.8 pythonVersion: '3.8' stages: - stage: Build displayName: Build stage jobs: - job: BuildJob pool: vmImage: $(vmImageName) steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(pythonVersion)' displayName: 'Use Python $(pythonVersion)' - script: | python -m venv antenv source … -
Swagger UI with authentication
How do I allow authenticating through Swagger UI? How to send Authorization header with a request in swagger-ui-react? assumes that we are working with a static schema file and says to add securitySchemes to it. In my case, I generate an Open API schema for a REST API implemented with Django REST Framework following the directions in the docs. Schema view: schema_view = get_schema_view( title='REST API', url='/rest/', urlconf='apps.rest.urls', ) Then I add a view to generate the documentation with Swagger UI: class DocsView(TemplateView): template_name = 'rest/docs.html' extra_context = { 'schema_url': 'rest:schema', } And I wire up the URLs: urlpatterns = [ path('rest/schema/', views.schema_view, name='schema'), path('rest/docs/', views.DocsView.as_view(), name='docs'), ] When I navigate to http://localhost:8000/rest/schema/, there is no components let alone securitySchemes. So my question is how do I get these to generate or otherwise allow the user to submit authenticated requests when they click on "Try it out" in the Swagger UI page? In case it is important, all of my REST views declare authentication_classes. These all appear to be custom subclasses of BaseAuthentication. Do I need to add anything to these subclasses to allow get_schema_view() to generate the correct security schemes? -
How can I set the cache lifetime?
I am trying to implement the function remember me, when the user has not ticked remember me, then the cache should be cleared after closing the browser, the saved data in the cache was deleted. For some reason my implementation doesn't work. When debugging, I get the value from POST correctly and there are no errors when setting the cookie lifetime. Tell me what am I doing wrong? class AccountLoginView(LoginView): template_name = 'login.html' form_class = AccountLoginForm def form_valid(self, form): remember = self.request.POST.get('remember-me', False) if not remember: self.request.session.set_expiry(0) return super().form_valid(form) -
FATAL: role "postgres" does not exist
I am brand new to postgres and I'm trying to set up a server for the first time to use with Django, but whenever I try to save it I get this error: FATAL: role "postgres" does not exist connection settings Thanks for the help in advance -
build_attrs() got an unexpected keyword argument 'type' with Django 1.8.7
There are already two questions with this error message but those two are specific to a change introduced in Django 1.11. This does not apply in my case, where the version of Django is 1.8.7 under Ubuntu 16.04 LTS. It was last automatically updated on Feb 3, 2021 and now forms are broken with the error message in the title of my question. How can I fix this? I never use build_attr directly, but I also use the package django-selectable in an older version, when this is of relevance. -
python app to call kubernetes to create pod programmatically
I am designing a web application where users can have trade bots running. So they will sign in, pay for membership then they will create a bot, enter the credentials and start the bot. The user can stop / start the trade bot. I am trying to do this using kubernetes, so I will have everything running on kubernetes. I will create a namespace named bots and all bots for all clients will be running inside this bot namespace. Stack is : python (django framework ) + mysql + aws + kubernetes question: Is there a way to programmatically create a pod using python ? I want to integrate with the application code. So when user clicks on create new bot it will start a new pod running with all the parameters for the specific user. Basically each pod will be a tenant. But a tenant can have multiple pods / bots. So how do that ? Is there any kubernetes python lib that does it ? I did some online search but didn't find anything. Thanks -
Write a photo upload model for three different tables
I am writing a project with Django. I have three product tables with different fields. For each row of these tables have multiple photos must be uploaded! How should models be written? Should a photo upload table be created for each product table ?! please help :) -
How to enable id for label tag when using django forms?
I'm using django forms, looking suggestion how to enable id for label tag? i could see id by default enabled for all tags except label. -
Postgres connection problem in docker-compose up in Django project
My Django project works fine with python manage.py runserver with no problem. Postgres, redis, django, djangorestframework all fine together. I try to Dockerize the project, but I get the following error for Postgres: .... web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "127.0.0.1" and accepting web_1 | TCP/IP connections on port 5432? Here's my docker-compose. version: '3' services: db: image: postgres # use latest official postgres version env_file: - database.env # configure postgres volumes: - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down redis: image: bitnami/redis:latest web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db volumes: database-data: Note: I also tried an alternative postgres repo: https://github.com/sameersbn/docker-postgresql -
Django - Incorporating new models with their own pages
I have managed to set up one model within my Django project and can create posts within it and display those posts through views and templates, however, I don't appear to be able to do the same with the new Models I've created. I have attempted to do this as I have done with the initial Model, which is to set up its own html files, just as the first one, as well as similar entries in urls.py in the main project folder and views.py in the app folder. My intent is to have different categories aligned with different models and have all of those categorier and corrosponding pages as links within a navbar. I'm not entirely sure where I'm going wrong, or even if I'm anywhere near right. Help would be very much appreciated. Here is the folder structure of my project Files under the app folder: article_detail.html: {% extends 'base_layout.html' %} {% block content %} <div class="article-detail"> <div class="article"> <h2>{{ article.title }}</h2> <p>{{ article.body }}</p> <p>{{ article.date }}</p> </div> </div> {% endblock %} article_list.html: {% extends 'base_layout.html' %} {% block content %} <h1>Articles List</h1> <div class="articles"> {% for article in articles %} <div class="article"> <h2><a href="{% url 'articles:detail' … -
Can't add a field to serializer.data django rest
I have a view that displays the project by ID. I want to add one more value into response, but for some reason it is not added. class ProjectApiView(APIView): def get(self, request, project_id=None): if project_id: project = Project.objects.get(id=project_id) serializer = ProjectSerializer(project) serializer.data["all_users"] = 'test' print(serializer.data) return JsonResponse({'project': serializer.data}) class ProjectSerializer(serializers.ModelSerializer): prototype = PrototypeSerializer(read_only=True) class Meta: model = Project fields = ['id', 'name', 'prototype', 'colors'] Serializer.data {'id': 2, 'name': 'test 2', 'prototype': OrderedDict([('id', 1), ('device_name', 'iphone'), ('width', 900), ('height', 1200), ('image', '/media/blank'), ('image_hover', '/media/blank')]), 'colors': {}} -
FileSystemStorage django, link to file in admin panel not working
Iam using the FileSystemStorage to store some private files, outside the media root. # settings.py ... PRIVATE_STORAGE_ROOT = join(BASE_DIR, 'private') ... # models.py from django.conf import settings from django.core.files.storage import FileSystemStorage from django.db import models private_storage = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) class MyModel(models.Model): upload = models.FileField(storage=private_storage) Everything is working fine, the logged in user can only see their own files through django authentication. But when i open the admin panel, the file link is http://Media/...... So the admin panel is still searching in Media Root for the file, which ofcourse isnt there. How can i change the code so that de the file link is correct in admin panel. -
How to use the list of lists in the same template by pagination?
the question might be not clear but I will try to explain. I sent three dicts that have the (objects.all()) context query as you can see in below. one of them is (a sentence) object which divides the page into 20 objects in a page for many pages. when I use the sentence in a template I need to use it as the main loop to iterates the objects and there are other objects which have a name are (Words and actors ) that also contains the context quey (objects.all()) and that will be such as sub looping which has put them into the main loop. when I try to send the dictionary of the list from views.py file to the template I get an error: ValueError: Need 2 values to unpack in for loop; got 1. I took a moment to look for this error and I found this answer: Reference list item by index within Django template? but it didn't help me and also, I can't use it because I need to create more than one loop into each other such as: {% for x in objects %} {% for y in x %} ................. and so on. … -
I need help accessing a nested list inside a nested dictionary
For some reason I can't access the odds key, I know it is a list inside a dictionary and I can print or do whatever I want to everything else. What am I doing wrong? My dictionary is named games so if I did print(games['summary']) it will print it properly. But if I did print(games['odds'][0]) or games['odds'] it returns a key error. Any idea why? this is what one entry in the dictionary looks like... { "schedule": { "date": "2021-03-03T02:00:00.000Z", "tbaTime": 5 }, "summary": "Marquette @ DePaul", "details": { "league": "NCAAB", "seasonType": "regular", "season": 2020, "conferenceGame": 5, "divisionGame": 5 }, "status": "scheduled", "teams": { "away": { "team": "Marquette", "location": "Marquette", "mascot": "Golden Eagles", "abbreviation": "MARQ", "conference": "Big East" }, "home": { "team": "DePaul", "location": "DePaul", "mascot": "Blue Demons", "abbreviation": "DEP", "conference": "Big East" } }, "lastUpdated": "2021-03-02T20:09:39.029Z", "gameId": 256879, "venue": { "name": "Wintrust Arena", "city": "Chicago", "state": "IL", "neutralSite": 5 }, "odds": [ { "spread": { "open": { "away": -5.5, "home": 5.5, "awayOdds": -110, "homeOdds": -110 }, "current": { "away": -5.5, "home": 5.5, "awayOdds": -110, "homeOdds": -110 } }, "moneyline": { "open": { "awayOdds": -240, "homeOdds": 200 }, "current": { "awayOdds": -224, "homeOdds": 192 } }, "total": { "open": { … -
Which way is best to create a database for a Django web app?
I am developing a web app with Django for a project. I want to collect historical financial data using Quandl API and build a small database to use for the website. The data collected will be mostly the adjusted closing price for all 2020 of about 10-20 stocks. Which way is the best to do this? Using HDF5 is sufficient? Any help is welcomed as this is my first project and first experience with Django. Thanks everyone 🙏🏻 -
Django Stripe Checkout.session.completed Error 500
I'm using just the standard Stripe Checkout module to test products, in the dashboard I can see the new user subscribe after buying the product with everything saying 'active'. For some reason though, the checkout.session.completed event returns a status 500 instead of 200. Not an expert at Django yet, but is the if-statement below just looking to see that the checkout.session.completed event exists, or if it has been successful? I'm guessing the latter since a new 'StripeCustomer' object isn't being created. (Not sure if this is related, but the 'HTTP_STRIPE_SIGNATURE' throws a KeyError when I try to visit the webhook url too) Views.py @csrf_exempt def stripe_webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY endpoint_secret = settings.STRIPE_ENDPOINT_SECRET payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] client_reference_id = session.get('client_reference_id') stripe_customer_id = session.get('subscription') user = User.objects.get(id=client_reference_id) StripeCustomer.objects.create( user=user, stripeCustomerId=stripe_customer_id, stripeSubscriptionId=stripe_subscription_id, ) print('just subscribed') return HttpResponse(status=200) -
python manage.py migrate --fake <appname> vs python manage.py migrate --fake <appname> zero
When I run python manage.py migrate --fake photos zero : Operations to perform: Unapply all migrations: photos Running migrations: Rendering model states... DONE Unapplying photos.0001_initial... FAKED After running above command, I ran python manage.py migrate at that time this error occurred. Traceback:Traceback (most recent call last): File "C:\Users...\lib\site-packages\django\db\backends\sqlite3\base.py", line 411, in execute return Database.Cursor.execute(self, query) django.db.utils.OperationalError: table "photos_userphoto" already exists When I run python manage.py migrate --fake photos: Operations to perform: Apply all migrations: photos Running migrations: Applying photos.0001_initial... FAKED Applying photos.0002_auto_20210303_0120... FAKED After running above command, I ran python manage.py migrate and this work perfectly. Running migrations: Applying photos.0003_auto_20210303_0123... OK So my question is that what difference between python manage.py migrate --fake <appname> vs python manage.py migrate --fake <appname> zero and Why first command throws me an error? Thank you.. -
How to display a image on a react-app before sending the image to the backend using django rest framework?
I am using react for the frontend and django rest framework for the backend. In my project the user has the possibility to update his profile-details. I am using Axios for the data transfer. My goal: The user can select a image, display it and then send the image to the server. I have tried many ways to do this but i keep getting different type of errors. I have already succeeded to fetch the image that i uploaded with the user in admin site. The structure of my app: (parent)Userpage.js The parent renders the Userdatalist component in a map function. (child) UserDatalist.js When the user goes to his userpage, i use useEffect to get the userdata and display the data in the UserDataList component. Here is the code when i render the child component. This is the child component. import React from "react"; function UserDatalist (props) { console.log('1'); console.log(props); return ( <div>{ props.displayImage ? <img src={props.displayImage} alt="UserImage" /> : <img src={props.user.profile_image} alt="UserImage" /> } <br /> <input type="text" name="username" disabled={props.disablemode} onChange={(event) => props.onChange(event)} value={props.user.username} /> <br/> <input type="text" name="company" disabled={props.disablemode} onChange={(event) => props.onChange(event)} value={props.user.company} /> <br/> <input type="text" name="birthday" disabled={props.disablemode} onChange={(event) => props.onChange(event)} value={props.user.birthday}/> <br/> <input type="text" name="interest" disabled={props.disablemode} … -
ModelForm making more calls for ForeignKey relations
I am using a ModelForm which seems to making 2 database calls for each of the ForeignKey fields in the model i.e. course and board models.py class Board(ModelBase): name = models.CharField(max_length=500) class Meta: ordering = ["name"] def __str__(self): return "{0}".format(self.name) class Course(ModelBase): title = models.CharField(max_length=255) description = models.TextField(max_length=2000) affiliation = models.ManyToManyField(Board) def __str__(self): return "{0}".format(self.title) class Registration(ModelBase): course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) board = models.ForeignKey(Board, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=255) def __str__(self): return "{0}".format(self.name) forms.py class RegistrationForm(forms.ModelForm): class Meta: model = Registration fields = "__all__" views.py class RegistrationPage(SuccessMessageMixin, CreateView): form_class = RegistrationForm template_name = "registration.html" success_url = reverse_lazy("register") success_message = "Thank you for registering. We will contact you shortly!" registration.html <div class="col-md-6 ftco-animate"> <form action="#" method="post" id="registration"> {% csrf_token %} {% for error in form.non_field_errors %} <div class="form-group has-errors text-danger small"> {{error}} </div> {% endfor %} {% for field in form %} <div class="form-group row"> <div class="col-sm-12"> <label for="">{{field.label}}</label> </div> <span class="form-group has-errors text-danger small"> {{field.errors}} </span> <div class="col-sm-12">{{field}}</div> </div> {% endfor %} <div class="row form-group"> <div class="col-sm-12 pt-1"> <input type="submit" value="Submit" class="btn btn-primary theme-btn"> </div> </div> </form> </div> I suppose it should only be making a query to get all the boards and another one to get all the … -
How do I add text before and after a Django slider widget?
Let's say I define a Django widget like so in models.py happy_slider = models.FloatField(widget=widgets.Slider(attrs={'step': '0.01'}), verbose_name = '''How happy are you?''') I have lots of these slider widgets on a page, and would like, for each slider, to have text to the left and right of the slider that is unique to the sliders themselves. For example, "Very Unhappy" to the very left and "Very Happy" to the very right of the slider. In there a straightforward solution to implementing this without manually modifying the CSS of each formfield in the .html page? -
Why is there a Django Error Regarding ‘Secrets’ only in Production
I am using Django 3.0.8 to serve a web application and Django-Trench for the multi-factor authentication. In production I find that trying to obtain an MFA QR code causes a server error with the error being ‘Secrets must be at least 160 bits’. In development, it works absolutely fine with no errors. I’ve ensured Python packages and versions are identical between both environments with nearly identical settings.py files. All the usual app settings like the secret key, Django-Trench settings, etc. are all valid. What is happening? Can anyone help?