Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django built-in class based view - Where is self.object from?
In the following code, I don't understand something. class SingleObjectMixin(ContextMixin): """ Provide the ability to retrieve a single object for further manipulation. """ model = None queryset = None slug_field = 'slug' context_object_name = None slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' query_pk_and_slug = False ... ... def get_context_data(self, **kwargs): """Insert the single object into the context dict.""" context = {} if self.object: context['object'] = self.object context_object_name = self.get_context_object_name(self.object) if context_object_name: context[context_object_name] = self.object context.update(kwargs) return super().get_context_data(**context) There is an atrribute self.object' in method get_context_data. I would like to figure out where the attribute `object' is created from. -
How to make elided pagination work in django-tables2
I am trying to use django-tables2 v2.5.2 to render a table of products. Pagination renders correctly, it basically looks like: ['prev',1,2,3,4,5,'...',18,'next'] each button is tag with href='?page=x' and after click it updates url with the page parameter but ellpsis button ('...') has href='#' and obviously does nothing when clicked on. Other pages buttons works fine. Do you have any idea how to setup django and/or django-tables2 to make elided pagination work? I am trying to setup simple table with products. I am using function view and RequestConfig, like this: views.py def product_list(request: HttpRequest): all_items = Product.objects.all().order_by("-publish_date") product_filter = ProductFilter(request.GET, queryset=all_items) table = ProductTable(product_filter.qs) RequestConfig(request, paginate={"per_page": 5}).configure(table) return render( request, "product/product_list.html", {"table": table, "filter": product_filter} ) and my tables.py code looks like this: class ProductTable(tables.Table): image_url = ImageColumn(verbose_name="Image") publish_date = tables.DateColumn(format="d M Y", order_by=["publish_date"]) user = tables.Column(verbose_name="Verified by") title = tables.Column(verbose_name="Product") class Meta: model = Product template_name = "django_tables2/bootstrap.html" sequence = ("title", "producer", "user", "status", "publish_date", "image_url") exclude = ("id", "image_url") filterset_class = ProductFilter I tried to read documentation to django-tables2 and django framework but I think I must be missing something. I am expecting the ellipsis button in pagination to load missing page range, so I guess it needs to … -
Creating a user using Djoser authentication is returning a 405 Method Not Allowed Error
I am using django and djoser for authentication. By testing the creation of the user using Postman at http://localhost:8000/auth/users using POST method, I am receiving a 405 Method Not Allowed Error. I am using an SQLite Database and already created a custom user model to use with Djoser: I already added an X-CSRFToken key and it's secret key in the Headers of the request,and made sure that the method is POST. -
why is my Jquery .on(clicked) function not getting clicked correctly?
I am trying to make - and + buttons to add items to shopping cart and I am using internal Jquery .on("click") to execute that. but it is neither performing any task nor is it actually getting clicked, it is not even showing the presence of jquery on inspection I want those button to get clicked and item to be added in cart -
"Authentication details were not provided." Django jwt
I've created a view for getting details of the user's profile. user_views.py @api_view(['GET']) @permission_classes([IsAuthenticated]) def getUserProfile(request): user = request.user serializer = UserSerializer(user, many=False) return Response(serializer.data) urls.py urlpatterns = [ path("/users/profile/", uv.getUserProfile, name="get-user-profile") ] serializers.py class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'name', 'isAdmin'] def get_id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def get_name(self, obj): name = obj.first_name if name == '': name = obj.email return name class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'name', 'isAdmin', 'token'] def get_token(self, obj): token = RefreshToken.for_user(obj) return str(token.access_token) I'm sending a get request through post man and sending a authorization header with Bearer <token>. And got { "detail": "Authentication details were not provided." } Using django-rest-framework and django-rest-framework-simplejwt. -
Is it possible to upload a django webapp for free
I followed a course where I made a django app like this https://www.studybud.dev/ and always get error when trying to upload it, I don't even have a solid understanding on how to uplaod my django website. I watched lots of videos but all of them were poor as none of them worked. Tried uploading it for more than a month but with no avail, I tried using heroku,python anywhere and many others but some of them required credit card info and others don't work. I would appreciate any form of help. -
How can I scale up my django app to utilize 4 cores and 8 threads?
I have a Django app. I am about to move this from a single core system to a multi core system. (8 threads because of hyperthreading) I am trying to figure out the changes I need to make to utilize all of the cores and all of the threads. I looked around and found bunch of settings for Rails. I can not find similar settings for Django online. I found an article that says, I don't need to make any changes to Django. I should just use gunicorn to run 8 instances to utilize 8 threads, but this did not make sense to me. What do I need to change to make sure my app utilizes 8 threads without wasting resources. Thanks in advance for your help. -
how to use delete() query in django?
I am trying to delete one of the items of a field in the table. For example, I want to remove the 'hadi', shown in the image, from the table. I make query to filter and exclude instance but in final part, delete() query does not accept input such as id or variable to remove specific thing in one field. image models.py class Expense(models.Model): expenser = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) debtors = models.ManyToManyField( CustomUser, related_name='debtors', ) amount = models.PositiveIntegerField() text = models.TextField() date = models.DateField(null=True) time = models.TimeField(null=True) def get_debtors(self): return ", ".join([str(d) for d in self.debtors.all()]) def who_has_no_paid(self): return ", ".join([str(d) for d in self.debtors.all() if str(d) != str(self.expenser)]) def debt(self): return int(float(self.amount/self.debtors.all().count())) def get_absolute_url(self): return reverse('expense_detail', args=[self.id]) Now what is the query that should be used in view? -
selinium slow preformance on realtime Django project
I'm working on a project which I'm getting posts from couple of websites and show it in the main page of my website but with filter and letting users to search for keywords and see the posts with that keywords. this is how the code works : In here with get the customized url of the site with our keyword and city filter def link_gen(city='', Kword='' ): # for example.com urls =[] if Kword != '': if city =='': url = f'https://www.example.com/search/with{Kword}' url = url.strip() url = url.replace(" ", "-") urls.append(url) else: url = f'https://www.example.com/search/with{Kword}in{city}' url = url.strip() url = url.replace(" ", "-") urls.append(url) else: if city != '': url = f'https://www.example.com/search/in{city}' url = url.strip() url = url.replace(" ", "-") urls.append(url) else: urls.append('none') return urls this part is where we crawl for the posts of the target website # function for getting the title, link, icon, desc of all posts def get_cards(urls): data = [] # for example.com if urls[0] != 'none': # we use webdriver to get site with dynamic component and design url = urls[0] options = Options() options.headless = True browser = webdriver.Firefox(options=options) browser.get(url) print ("Headless Firefox Initialized") soup = BeautifulSoup(browser.page_source, 'html.parser') jobs = soup.find_all( 'div', class_="job-list-item", … -
Can't connect to postgres database from docker container
2023-02-18 09:51:03.146 UTC [1] LOG: database system is ready to accept connections database starts succesful, but after Error: Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? ---docker-compose.yml--- version: '3.8' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app/ ports: - 8000:8000 depends_on: - db db: image: postgres container_name: todo_postgres environment: POSTGRES_USER: name POSTGRES_PASSWORD: password POSTGRES_DB: app_name POSTGRES_HOST: db ports: - '5432:5432' ---settings.py--- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': name, 'USER': username, 'PASSWORD': password, 'HOST': db, 'PORT': 5432, } } I have no idea what's wrong with connection, help me please At first i use "POSTGRES_HOST:localhost", but it doesn't work either -
Django REST - Trigger action when updating a model in a REST-friendly way
I have the following use case that I want to implement: an LMS app powered by DRF has an Exam model, which has a state field which can either be DRAFT or PUBLISHED. When a teacher publishes an exam, I want them to have the option to also create an announcement on the course (there a model called Announcement for that). I'm looking for an elegant and efficient way to encode and utilize the information of whether the user wants to contextually publish an announcement when publishing an exam. This requires identifying three steps: how to encode whether the user wants to publish the annoncement in a REST request to publish the exam how to intercept when an exam is being published to optionally publish an exam how to pass the information about whether the user wants to publish an announcement over to whichever part of the application will be responsbile for actually publishing it. For the second step, I decided to go with the django-lifecycle package.This beatiful package allows defining a method on the Exam model class itself to look something like: @hook(AFTER_UPDATE, when='state', is_now=PUBLISHED) def on_publish(self): # ... logic As per the rest, here's two possible solutions I've … -
Can I decrypt password using the private key generated in Django backend in Flutter?
I am making a password manager app where I am using asymmetric encryption to store passwords. I have created a Django backend for the app where I have stored the user's public key in the User model. During registration, I am storing the public key in the database and sending the user their private key to the Flutter app. I am using the following function to encrypt the password and store it in the password store model: def encrypt(data, key): key = serialization.load_pem_public_key( key.encode(), backend=default_backend() ) data = key.encrypt( data.encode(), padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) return data Now, I want to know if I can decrypt passwords or any other string data in Flutter using the private key that is generated in the Django backend. If yes, how can I do it? Also, I don't want to pass the decrypted password from the backend to the Flutter app. I want the client-side to handle it. For this, I am storing the private key in the user's device using shared preferences in Flutter: SharedPreferences.getInstance().then((prefs) { prefs.setString("privateKey", widget.privateKey); }); Can anyone help me with this? I tried using the decryptByPrivateKey function below to decrypt a password on the client side in … -
How to fix auto adding forward slash
In my models.py I have a function property that return thumbnail url return os.environ['BASE_URL'] + self.thumbnail.url my .env file BASE_URL=http://127.0.0.1:8000 but it keep adding 1 more forward slash ( / ) after my BASE_URL http://127.0.0.1:8000//media/uploads/... Anyone know how to fix this -
How can I fix "CSRF token missing" error?
I'm building a web application with Django as my backend framework and DjangoRestFramework as webAPI, React Native as the frontend, and apisauce as an HTTP client. When I try to make a POST request from the frontend to the backend, I'm getting a "CSRF Failed: CSRF token missing" error. I don't get the error when I use postman. I still get the error even if I comment this out "django.middleware.csrf.CsrfViewMiddleware", -
django not hashing password custom user
i am working on a model which inherits from from django.contrib.auth.models import AbstractBaseUser earlier i was specifying password field like: password = models.Charfield(max_length=150) but then i need to specify it as: create_password = models.CharField(max_length=150) in earlier case i was getting password in hashed format. but after changing password to create_password the value is saving in unhashed format (originally entered value). all other settings are same as before, i am using set_password(create_password) now . but still no hashing. how can i hash create_password field? -
ModuleNotFoundError: No module named 'api_yamdb.wsgi'
When deploying the project, the web container fails with the error No module named 'api_yamdb.wsgi'. Please help!) Dockerfile: `FROM python:3.7-slim WORKDIR /app COPY .. . RUN pip3 install -r ./requirements.txt --no-cache-dir CMD ["gunicorn", "api_yamdb.wsgi:application", "--bind", "0:8000"]` Workflow: `name: Yamdb workflow on: [push] jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.7 - name: Install dependencies run: | python -m pip install --upgrade pip pip install flake8 pep8-naming flake8-broken-line flake8-return flake8-isort pip install -r api_yamdb/requirements.txt - name: Test with flake8 and django tests run: | python -m flake8 pytest build_and_push_to_docker_hub: name: Push Docker image to Docker Hub runs-on: ubuntu-latest needs: tests if: contains(' refs/heads/master refs/heads/main ', github.ref) steps: - name: Check out the repo uses: actions/checkout@v2 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v1 - name: Login to Docker uses: docker/login-action@v1 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Push to Docker Hub uses: docker/build-push-action@v2 with: push: true tags: porter4ch/yamdb_final:latest file: api_yamdb/Dockerfile deploy: runs-on: ubuntu-latest needs: build_and_push_to_docker_hub steps: - name: executing remote ssh commands to deploy uses: appleboy/ssh-action@master with: host: ${{ secrets.HOST }} username: ${{ secrets.USER }} key: ${{ secrets.SSH_KEY }} passphrase: ${{ secrets.PASSPHRASE }} script: | sudo docker-compose … -
How to python-execute-file a django custom command in emacs
How can I C-c C-c or python-execute-file a django custom command? Currently I get this error (using the emacs settings at the bottom): -*- mode: compilation; default-directory: "~/src/django/" -*- Comint started at Fri Feb 17 16:45:33 /home/user/.local/share/virtualenvs/django-OfUvXXat/bin/python csv_import.py /home/user/.local/share/virtualenvs/django-OfUvXXat/bin/python: can't open file 'csv_import.py': [Errno 2] No such file or directory Inferior Python exited abnormally with code 2 at Fri Feb 17 16:45:33 This works as expected: python manage.py csv_import ~/django/crm/management/commands/csv_import.py: from django.core.management.base import BaseCommand, CommandError from crm.models import Organization,Person class Command(BaseCommand): def handle(self, *args, **options): print(Organization.objects.all()) I tried to no avail many settings e.g. (setq python-shell-interpreter "python" python-shell-interpreter-args "-i /home/user/src/django/manage.py shell") (defun django-shell () (interactive) (let ((python-shell-interpreter (read-file-name "Locate manage.py ")) (python-shell-interpreter-args "shell")) (run-python (python-shell-calculate-command) nil t))) Environment: lsp,pyright,pipenv -
Django-DataFrame constructor not properly called
views.py def preprocessedDatafile(request): dtf = pd.DataFrame(request.POST['myfile']) dtf.to_csv("../static/files/myPreprocessedata.csv") return render(request, "preprocessedDatafile.html") .html <form class="grid" method="POST" action="{% url 'preprocessedDatafile' %}" onSubmit="return empty()"> {% csrf_token %} <div style="border: 1px dashed rgb(148,10,34); width:59%" > <br/><br/> <input type="file" class='upload-box' accept=".csv" name='myfile' onchange='triggerValidation(this)' required='true'/> <br/><br/><br/> </div> <button type="reset" id='clr' ><b>Clear</b></button> <button type="submit" id="btn" ><b>Start</b></button> </form> I am making a web page that take csv file and than store this csv file in a specific location using django. but i do not know why i am getting "DataFrame constructor not properly called!". Is there way to remove this error? -
how to use rest_framework.urls, through /login/
i wanna make my own API through rest_framework.urls (/login/)=> i think /login/ url is provided by this framework. enter image description here as you can see, i wrote my client type of json, but i think that key:values are not "email" and "password". plz let me know the json type when using rest_framework.urls (/login/) Thank you # apps.urls.py urlpatterns = [ path('signup/', UserCreate.as_view()), **path('', include('rest_framework.urls')),** ] # project(root).urls.py urlpatterns = [ path('admin/', admin.site.urls), **path('login/', include('login.urls')),** path('', include('postapp.urls')), ] i want to enter my client to that page(rest_framework/login/) by using json type -
Volume doesn't work in a docker container and forgets data
I'm trying to build Django + Docker + PostgreSQL Dockerfile FROM python:3.10.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apk update RUN apk add postgresql-dev gcc python3-dev musl-dev COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh RUN chmod +x /usr/src/app/entrypoint.sh COPY . . ENTRYPOINT ["/usr/src/app/entrypoint.sh"] docker-compose.yml version: '3.9' services: web: build: . command: gunicorn pets.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 env_file: - .env depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env nginx: build: ./nginx ports: - 1337:80 depends_on: - web volumes: postgres_data: entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $POSTGRES_HOST $POSTGRES_PORT; do sleep 0.1 done echo "PostgreSQL started" fi cd pets python manage.py flush --no-input python manage.py migrate exec "$@" So, when the container starts i use docker exec -it <container_id> python manage.py createsuperuser to create a superuser and then add some data to database. But, when i use docker-compose stop and then running again with the same id the container forgets about the written data and everything has to be repeated. Shouldn't volume solve this issue? -
Why django_session and auth_user have no relations?
The Django authentication system is a great system that can be helpful to develop authentication in apps. However, the django_session table and auth_user have no relation. When we want to fetch all of the active sessions of a user we have to fetch all the active sessions, deserialize the session_data, and then find the users' sessions. This is practically a complete table scan. Is there any special or security reason for that? Can we just create an association between these tables without making any vulnerabilities? -
How to fetch Individual Values from the Queryset in Django Template
How to fetch Individual Values from the Queryset Skill <QuerySet [{'id': 1, 'name': 'Django', 'score': 100, 'is_key_skill': True}, {'id': 2, 'name': 'Python', 'score': 75, 'is_key_skill': True}]> in Django template Here is my views.py : def home(request): value = profile.objects.get(id=1) skills = Skill.objects.filter().values context = { 'value': value, 'Skill': skills, } return render(request, 'home.html', context) I want to fetch individual values like Django and its corresponding values separately. -
Django channels connection failed (nginx + daphne + certbot + docker-compose)
I'm using Django channels using docker-compose and nginx outside it websockets were working just fine but after installing certbot, it stopped working it returns 404 as if it is treated as just normal http request VM253:1 WebSocket connection to 'wss://example.com/ws/results/tjrtudvzanxxqbyt' failed: daphne : "GET /ws/results/tjrtudvzanxxqbyt" 404 2618 my nginx file for the server is upstream language_transcriber{ server localhost:8000; } # the nginx server instance server { listen 443 default_server; server_name example.com; access_log /var/log/nginx/example.com.log; ssl_certificate_key /etc/nginx/ssl/example.com.private_key.pem; ssl_certificate /etc/nginx/ssl/fullchain.crt; root /var/www; ssl on; # pass the request to the node.js server with the correct headers # and much more can be added, see nginx config options location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP$remote_addr; proxy_set_header X-Forwarded-For$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto$scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_set_header X-NginX-Proxy true; proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://127.0.0.1:8000; } location /static/ { alias /var/www/example.com/static/; autoindex off; } location / { proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://language_transcriber/; proxy_redirect off; } } and here's my docker-compose.yml version: "3.8" services: django: build: . container_name: django command: daphne … -
Validate field input using django serializer
I have a field code in my django model. I have to check if the input string has following properties: Length should be 5 characters 1st & 2nd characters should be alphabets 3rd & 4th characters should be numbers 5th character should be E or N I have a serializer as shown below which satisfies the first condition. class MyModelSerializer(serializers.ModelSerializer): code = serializers.CharField(max_length=5, min_length=5) class Meta: model = MyModel fields = '__all__' How can I fulfil the remaining conditions. Need your help with this. Thanks in advance -
session handling between react django app if user browser cookies blocked
in my react-django app,my scenario is each user has multiple accounts and when user login there will be a session check call and if no data in session then we have to select particular account and store it in session thus django and react passes session cookie in every request.suppose if cookies are blocked in user browser then what to do? how to handle session data then?