Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error Msg : "can't convert from BSON type string to Date
db.newc.aggregate( [ { $project: { _id: 0, formattedDate: { $dateToString: { format: "%d/%m/%Y", date: "applied_on" } } } } ] ) I am having the Code like this, and i am using mongodb compass and mongosh.The aggregation is not working. -
Sort a list from different classes by one field - Django
I connect multiple queryset from different objects into one list: query_1 = Room.objects.all() query_2 = Apartment.objects.all() query_3 = Plot.objects.all() all_user_objects = list(chain(query_1, query_2, query_3)) How can I add a sort by created_at date from the newest? I try this: all_user_objects.order_by('-created_at') and this: from operator import attrgetter all_user_objects = list(chain(query_1, query_2, query_3), key=attrgetter('-created_at')) -
Django cannot revert migration
im trying to undo my last migration by migrating previous migration but django throws an error "Cannot find a migration matching" how can i solve this ? -
One page to another page using JAVASCRIPT or JQUERY using Html anchor tag with dynamic Id
Basically I have two pages working on different categories. I am working on Sandbox. I have two pages with dynamic URL using anchor tag. I just want to call First page on button click when we are on Second page without changing windows location. The Windows location should be same. Avoid using windows.location functionalities in JS. Simple I want to jump from one page to another page with the help of JS or jQuery. <li> <a href="{% url "analysis" report.analysis.info.id "summary" %}" {% if env.view_kwargs.page == 'summary' %} class="active" {% endif %}> <div class="parent-icon"><i class='bx bx-home'></i> </div> <div class="menu-title">Summary</div> </a> </li> <li> <a href="{% url "analysis" report.analysis.info.id "reboot" %}" {% if env.view_kwargs.page == 'reboot' %} class="active" {% endif %}> <div class="parent-icon"><i class='fa fa-power-off'></i> </div> <div class="menu-title">Reboot Analysis</div> </a> Suppose, If I am on the page of Reboot Analysis so with the help of JS or jQuery I should jump to the Summary page. -
Docker django app running but cannot access the webpage
I am trying to run two separate django apps using docker (building on a linux server). The first application runs smoothly (using default ports) the second one apparently runs (it says starting development server at http://0.0.0.0:5000), I got no issues looking inside the portainer. Everything is running and no issue is there. When I try to connect to the page, it fails. docker-compose: version: '3' services: vrt: build: context: . dockerfile: Dockerfile ports: - "5000:5000" volumes: - ./nuovoProgetto:/VehicleRammingTool command: > sh -c "python3 manage.py wait_for_db && python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:5000" env_file: - ./.env.dev depends_on: - db db: image: postgres:14.1-alpine restart: always environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - db:/var/lib/postgresql/data redis: image: redis:alpine celery: restart: always build: context: . command: celery -A nuovoProgetto worker --pool=solo --loglevel=info volumes: - ./nuovoProgetto:/VehicleRammingTool environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - vrt - redis volumes: db: driver: local Dockerfile: FROM ubuntu:18.04 ENV http_proxy=http://++++++++++proxyhere ENV https_proxy=http://+++++++++proxyhere ENV PATH="/root/miniconda3/bin:${PATH}" ARG PATH="/root/miniconda3/bin:${PATH}" RUN apt-get update RUN apt-get install -y wget && rm -rf /var/lib/apt/lists/* RUN wget \ https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \ && mkdir /root/.conda \ && bash Miniconda3-latest-Linux-x86_64.sh -b \ && rm -f Miniconda3-latest-Linux-x86_64.sh RUN python --version RUN conda install -c conda-forge django psycopg2 celery redis-py django-leaflet … -
How to write unit test ValidationError case in response by use client.post()
I have a model with a time validator raise ValidationError('End time cannot be earlier than start time') So I want to write a unit test using client.post() with data invalid (from_time > to_time), and I expected ValidationError to appear in this test. -
cannot print an integer to a pdf python django
As the title says, I want to print integers to a pdf, because it will be a receipt, and the data for them are on FK. But I get an error named "bad argument type for built-in operation", is there any workarounds for it? here is the view of the function: def receipt(request): buf = io.BytesIO() c = canvas.Canvas(buf, pagesize=letter, bottomup=0) textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont ("Helvetica", 10) items = ShopCart.objects.all() lines = [] for item in items: lines.append(item.product) lines.append(item.size) lines.append(item.sugar) lines.append(item.ice) lines.append(item.addOn) lines.append(item.quantity) lines.append("") for line in lines: textob.textLine(line) c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='Receipt.pdf') Also, I've tried printing the said items columns on the terminal and got their values but, noticed that whenever I try to generate the PDF it will look like this: using print() tea1 Petite 10 normal milk 1 Im guessing this is the for line in lines: textob.textLine(line) tea1 Petite 10 -
creating custum user and login without registering through mobile in Django
I want that user should login without register he should login through mobile and otp so how to implement this in django .application to login without registration in django.when the user enter mobile no it should save in database how to do this without django own username n password field by changing the fields as mobile and then otp -
Django Migration error due to auth_user field not existing
django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... this is the error that I'm getting I'm using PostgreSQL as my database here is my connection to the database DATABASES = { 'default' : { 'ENGINE' : 'django.db.backends.postgresql', 'NAME' : 'listeners', 'USER' : 'postgres', 'PASSWORD' : '***********', 'HOST' : 'localhost' } } this is my models: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from flask_login import user_accessed class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, phone_number, password=None): if not email: raise ValueError("User must have an email address") if not username: raise ValueError("User must have a username") user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, phone_number = phone_number ) user.is_admin = False user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, email, username, password): user = self.create_user( email = self.normalze_email(email), username = username, pasword = password, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50,unique=True) email = models.CharField(max_length=50, unique=True) phone_number = models.CharField(max_length=10,unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) … -
How to use django-star-ratings
I got an error when I use django-star-ratings. Error 'str' object has no attribute '_meta' menu.html error at line 33 {% load ratings %} <div class="col-md-7"> <img src="{% static 'image/Indian-vegetarian-mark.svg' %}"> <h4 class="card-title" style="color: #FFC222;">{{i.product}}</h4> <h6 class="price-tag text-left mt-2 mb-1" style="font-size: 0.9rem;" > MRP:<span id=""> {{i.price}}</span> RS. </h6> {% ratings object %} </div> line 33 is {% rating object %} I also follow the document -
Method \"POST\" not allowed django
I am getting error as Method "POST" not allowed. urls.py from django.conf.urls import url from . import views urlpatterns = [ url('', views.listTutorials), url('create/', views.createTutorial), url('<str:pk>/update/', views.updateTutorial), ] views.py from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .serializers import TutorialSerializer from .models import Tutorial @api_view(['POST']) def createTutorial(request): serializer = TutorialSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['PUT']) def updateTutorial(request, pk): tutorial = Tutorial.objects.get(pk=pk) serializer = TutorialSerializer(tutorial, data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_204_NO_CONTENT) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def listTutorials(request): tutorials = Tutorial.objects.all() serializer = TutorialSerializer(tutorials, many=True) return Response(serializer.data) serializers.py from rest_framework.serializers import ModelSerializer from .models import Tutorial class TutorialSerializer(ModelSerializer): class Meta: model = Tutorial fields = '__all__' models.py from django.db import models class Tutorial(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) def __str__(self): return self.title project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('tutorials/', include('tutorials.urls')) ] Now I am using POST request as http://localhost:8000/tutorials/create/ with body { "title": "Django framework", "description": "Learning django framework" } But I am getting error { "detail": "Method "POST" not allowed." } -
Response body coming improperly in the browsable API in django
import json # Data to be written response = ['KIN', 'YAC', 'NAC', 'QUE', 'DEL'] context = {'categories': response} # Serializing json json_object = json.dumps(context, indent = 4) print(json_object) #return Response(json_object, status=status.HTTP_200_OK) On writing a code similar to this I gaet a response like this in the browsable API "{\"categories\": [\"KIN\", \"YAC\", \"NAC\", \"QUE\", \"DEL\"]}" whereas it is working fine on IDE. { "categories": [ "KIN", "YAC", "NAC", "QUE", "DEL" ] } I am new to django and some help will be appreciated. -
Django post_save signal ( request.COOKIES['device'] )
Currently working on a Django Ecommerce project so I would like to get the cookies of a user from the model I know we use request.COOKIES['device'] in our view but is there a way to get the cookies in our models part -
Django - How can I filter and count related objects of different ids
Model 1: class Member(models.Model): id = models.AutoField(primary_key=True) names = models.CharField(max_length=255, blank=True) student = models.ForeignKey('School', on_delete=CASCADE, null=True, blank=True) Model 2: class School(models.Model): id = models.AutoField(primary_key=True) I want to count the total students who are in different schools. I tried total_student = Members.filter(school=1+5+8).count()but this is not working. Note: 1, 5 and 8 are the ids of the same type of schools in the school model which different members attend. Please help me get this right. -
Django Unable to login credentials eventhough credentials is correct
I'm trying from a few days to create a login & register system for my WebSite, built with Django. But, every time I try to login to my account that I've created, I get an error. When I enter my credentials in the form and press the Submit button, the page reloads back to the signin page. Nevertheless, despite the credentials are right, I am given a mistake, and moreover on the wrong page. Here is my code. views.py from django.shortcuts import redirect, render from django.http import HttpResponse from .forms import UserForm, MemberForm from .models import User from django.contrib import messages, auth from django.contrib.auth.decorators import login_required, user_passes_test def registerUser(request): if request.method == 'POST': form = UserForm(request.POST) m_form = MemberForm(request.POST, request.FILES) if form.is_valid() and m_form.is_valid(): first_name = form.cleaned_data['first_name'] middle_name = form.cleaned_data['middle_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] mobile_number = form.cleaned_data['mobile_number'] password = form.cleaned_data['password'] user = User.objects.create_user(first_name=first_name, middle_name=middle_name, last_name=last_name, username=username, email=email, mobile_number=mobile_number, password=password) user.role = User.MEMBER user.save() member = m_form.save(commit=False) member.user = user member.save() messages.success(request, 'Your account has been registered successfully!') print(user.password) return redirect('registerUser') else: print('invalid form') print(form.errors) else: form = UserForm() m_form = MemberForm() context = { 'form' : form, 'm_form' : m_form, } return render(request, 'accounts/register.html', context) … -
Django | no such table: users_profile Mysql
help me find a bug please. I am migrating my project from sqlite to mysql. When I create a superuser, I manage to connect to the database and create a user line in it, but I get an error when I open the website page: enter image description here I think the creation is sent correctly, but further queries are sent from sqlite. How can this be fixed, what is my mistake? Also, the sqlite database is automatically created (empty) - probably trying to search in it. I've already deleted all the migration files and the database itself, and then: python manage.py makemigrations users python manage.py migrate DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bdname', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '000.000.000.000', 'PORT': '' } } What other information can I provide? -
Est ce python django gere les images qui sont sur la machine après déploiement du site web gratuitement sur heroku?
Je suis étudiant et nouveau sur le langage python et le framework Django, je viens de développer un site pour mon université, sur le site il est possible de publier les actualités et chaque actualité a un champ obligatoire "image" qui hérite de la classe models: image=models.Imgefield(), quand mon site était en Local le locahost de ma machine garder les images que je chargeais sur mon site, depuis hier j'ai déployé mon site sur heroku, je me rends compte que je charge les photos sur chaque publication le matin mais le jour suivant je trouve que les images ne s'affichent pas , on m'affiche " image card up", moi je vais que je charge les images une seule fois au lieu d'avoir ce travail qui m'oblige de choisir les images chaque jour et le jour suivant ça n'apparaît plus, s'il vous plaît aidez moi -
How to create single Form for two models that are related by a Foreign Key?
I developed a voting system using Python and Django. I would like the user to be able to register new polls. However, when the user registers a new poll, it results in an IntegrityError. It looks like it can't get the ID of the first model. How do I fix this error? The photo of the error and the form is below... models.py from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(default=timezone.now, verbose_name='Date') show = models.BooleanField(default=True) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text forms.py from django.forms import ModelForm from .models import * class addPollsForm(ModelForm): class Meta: model = Question fields = ['question_text', 'pub_date', ] class addChoiceForm(ModelForm): class Meta: model = Choice fields = ['choice_text'] views.py def addPollsPage(request): if request.user.is_authenticated: formAddPolls = addPollsForm() formAddChoice = addChoiceForm() if request.method == 'POST': formAddPolls = addPollsForm(request.POST) formAddChoice = addChoiceForm(request.POST) if formAddPolls.is_valid(): formAddPolls.save() if formAddChoice.is_valid(): formAddChoice.save() return redirect('votacao:index') context = {'formAddPolls': formAddPolls, 'formAddChoice': formAddChoice, } return render (request, 'votacao/addPolls.html', context) else: return redirect('main') addPolls.html <form action="" method="POST"> {% csrf_token %} {{formAddPolls.as_p}} {{formAddChoice.as_p}} {{formAddChoice.as_p}} {{formAddChoice.as_p}} <br> <input type="submit" name="Submit"> </form> IntegrityError error photo -
Django DetailView ValueError: Field 'id' expected a number but got 'Ryan'
I created a profile page that uses DetailView, but the profile page just doesn't work on newly created users and is giving me this error message: Internal Server Error: /user/Ryan/ Traceback (most recent call last): File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 1822, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'Ryan' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/views/generic/base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/views/generic/detail.py", line 107, in get context = self.get_context_data(object=self.object) File "/Users/raymond/Documents/GitHub/Management/blog/views.py", line 32, in get_context_data context['requests'] = Request.objects.filter(teacher=user.username, completed=False).order_by('-request_time') File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/query.py", line 974, in filter return self._filter_or_exclude(False, args, kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/query.py", line 992, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/query.py", line 999, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1375, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1396, in _add_q child_clause, needed_inner = self.build_filter( File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1329, in build_filter condition = self.build_lookup(lookups, col, value) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1180, … -
Trying to have link shown if user owns post or if user is staff
I'm trying to hide an Edit and Delete button from posts made unless it's the user who made it, or the user is staff/superuser. I got it to work in my views.py to allow staff users to edit, but I can't get it to show in the html. {% if request.user == room.host and room.host.is_staff %} This is what I have currently but it's not showing me the links as a staff user. -
When extending a base.html , is the <!DOCTYPE html> tag passed on aswell?
The title says it all. Is the doctype of: (base.html) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> Passed on to (home.html) {% extends 'base.html' %} Or do I need to declare the doctype in all of my documents? like so: <!DOCTYPE html> {% extends 'base.html' %} -
Django html script in TextField of a model
I created a mail model that has the following properties class Mail(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') title = models.CharField(max_length=50) content = models.TextField() sent_time = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('mail-detail', kwargs={'pk':self.pk}) I am trying to add a link that redirects to the detail of the request in the content section of the mail. This is what I tried m = Mail( sender=self.request.user, to=self.get_object().student, title='Request Comfirmed', content=f'Your request has been confirmed by {self.request.user.username}.' + '\n<small class="text-muted"><a class="ml-2" href="{% url \'request-defail\' ' + str(self.get_object().id) + ' %}">Click here to view details of the request</a></small>' ) This is what happened And this is how the mail is displayed <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.sender.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-profile' object.sender.username %}">{{ object.sender.username }}</a> <small class="text-muted">{{ object.sent_time }}</small> </div> <h2 class="article-titile">{{ object.title }}</h2> <p class="article-content">{{ object.content }}</p> </div> </article> -
Exception has occurred: ImportError Vscode While Debugging
I am trying to try the debug tool in my vs code I am totally new to vs code and I am getting an error such as this when I run it ERROR MESSAGE I have a folder called .vscode with a launch.json file ` "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\myPro\\manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true } ] } I watched a lot of videos on youtube and I see people who have settings.json in there .vscode file. WHAT I HAVE DONE: I have downloaded django == 3.25 I have downloaded python == 3.10.4 IN a virtual environment my environment works perfectly fine its just that I can find the reason to this problem I would really appreciate it if someone can help me out -
How to connect 2 models in the admin, if they are already connected OnetoOne?
models.py from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) Every time for new user(when he registers) I must choose user in admin('in Customer model') https://prnt.sc/waTmROxj3-xn(screenshot), if I don't choose a new user I have error RelatedObjectDoesNotExist at / User has no customer. How to do it automatically? What I did do wrong? It is possible to catch this exception, but then what data should be added to the customer to connect it? It won't change the user's flag to his own(https://prnt.sc/waTmROxj3-xn(screenshot)): views.py def cartData(request): if request.user.is_authenticated: try: customer = request.user.customer except ObjectDoesNotExist: customer = ? order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems': cartItems, 'order': order, 'items': items} -
RuntimeError: There is no current event loop in thread 'Thread-1' in Django project
I have a Django project that should parse some data from a particular web-site and saves the data into the database. In the app I use requests_html that is somehow dependant on asyncio which raises an error each time i'm trying to make a request. (I have to use requests_html, not beautifulsoup because I need scripts to be rendered into html) Here is the isolated problem: # project/app/render_js.py import requests_html def render_js(url): session = requests_html.HTMLSession() r = session.get(url) r.html.render() return r.html.text # project/project/views from django.http import HttpResponse from app.render_js import render_js url = 'some url' def view(request): print(render_js(url)) return HttpResponse("<h1>success!</h1>") # project/project/urls from django.urls import path from .views import view urlpatterns = [ path('', view) ] While attempting to make a GET request to http://127.0.0.1:8000/ throws: Internal Server Error: / Traceback (most recent call last): File "C:\Users\User\PycharmProjects\project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\User\PycharmProjects\project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\PycharmProjects\project\project\views.py", line 6, in view print(render_js('https://docs.python.org/3.7/library/threading.html#threading.Thread.run')) File "C:\Users\User\PycharmProjects\project\app\render_js.py", line 7, in render_js r.html.render() File "C:\Users\User\PycharmProjects\project\venv\lib\site-packages\requests_html.py", line 586, in render self.browser = self.session.browser # Automatically create a event loop and browser File "C:\Users\User\PycharmProjects\project\venv\lib\site-packages\requests_html.py", line 727, in browser self.loop = asyncio.get_event_loop() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\asyncio\events.py", line 642, in …