Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to fill a form returns Cannot query "useraccount": Must be "SellerAccount" instance
I am trying to build a trading market sort of app, and I have models that have foreign keys connected in a multiple level sort of hierarchy. They are as follows: models.py class SellerAccount(models.Model): # unimportant fields user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.user.username class SellerCardDetail(models.Model): # unimportant fields seller_details = models.ForeignKey(SellerAccount, on_delete=models.CASCADE) def __str__(self): return self.seller_details.user.username The forms in question are simply formsets with only the required fields added as an argument. views.py @login_required(login_url="/account/") def add_seller_card(request): card_form = SellerCardFormSet # imported from forms.py user = SellerAccount.objects.get(user=request.user) # imported from models.py if request.method == "POST": formset = card_form(request.POST, request.FILES, instance=user) if formset.is_valid(): formset.save() messages.success(request, "Successfully listed a card!") return redirect("/") else: formset = card_form(instance=request.user) return render(request, 'account/profile/addcard.html', {"add_card": formset}) else: print(type(user)) return render(request, 'account/profile/addcard.html') What I thought would happen is that I would get the SellerAccount instance with user = SellerAccount.objects.get(user=request.user) but that has proven to be untrue. I wanted to test what I would get when I let that query through with the simple print(type(user)), and it returns <class 'account.models.SellerAccount'>. I'm baffled by this, both because my understanding of Django is not good enough, and because this should work in theory and it doesn't. Since I can't get … -
Send email with django and celery inside docker gives OSError: [Errno 99] Cannot assign requested address
I am trying to send mail through django and celery inside docker, i am using different container for celey and different for django. here is my compose:- version: "3.8" services: # Redis redis: image: redis:alpine container_name: redis expose: - 6379 # Database Postgres db: image: postgres:alpine volumes: - local_pgdata:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db # Migrations migration: env_file: - .env image: app:django volumes: - .:/django command: > bash -c "python manage.py collectstatic --noinput && python manage.py migrate --noinput" depends_on: - db # Django Application app: env_file: - .env build: . volumes: - .:/django image: app:django ports: - "8000:8000" container_name: django_app command: python manage.py runserver 0.0.0.0:8000 # command: gunicorn HopeAndHappiness.wsgi:application depends_on: db: condition: service_started migration: condition: service_completed_successfully # Celery celery: env_file: - .env restart: always image: app:django volumes: - .:/django command: celery -A HopeAndHappiness worker -l DEBUG container_name: celery depends_on: - db - redis - app - migration nginx: image: nginx:latest ports: - 80:8080 volumes: - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro depends_on: - app volumes: local_pgdata: My Dockerfile:- FROM python:slim-buster EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 # Install system packages required by Wagtail and Django. RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ … -
Custom SessionAuthentication logic not working in my Django REST Framework project
So, the problem is with my custom implementation of SessionAuthentication. I researched google and docs trying to find a way to implement a logic of authenticating Custom User by his telegram_id and personal code, which is defined this way: class CustomUser(AbstractBaseUser): telegram_id = models.IntegerField(unique=True) name = models.CharField(max_length=35) surname = models.CharField(max_length=35) is_curator = models.BooleanField(default=False) developer_result = models.CharField(max_length=256, blank=True, null=True) design_result = models.CharField(max_length=256, blank=True, null=True) code = models.CharField(max_length=8, default=12345678) password = None USERNAME_FIELD = 'telegram_id' def __str__(self): return str(self.telegram_id) Then I created a similar to the example in the documentation CustomAuthentication class: class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self, request): telegram_id = request.data.get('telegram_id') code = request.data.get('code') if not telegram_id or not code: return None try: user = CustomUser.objects.get(telegram_id=telegram_id, code=code) # get the user except CustomUser.DoesNotExist: raise exceptions.AuthenticationFailed('Неверный логин или пароль') # raise exception if user does not exist return (user, None) Created a serializer for login: class CustomLoginSerializer(serializers.Serializer): telegram_id = serializers.CharField() code = serializers.CharField() def create(self, validated_data): telegram_id = validated_data['telegram_id'] code = validated_data['code'] user = CustomUser.objects.get(telegram_id=telegram_id, code=code) return user API view, allowing anybody to have access to it: class CustomUserLogin(GenericAPIView): permission_classes = (permissions.AllowAny,) authentication_classes = (SessionAuthentication, CustomAuthentication) serializer_class = CustomLoginSerializer def post(self, request): serializer = CustomLoginSerializer(data=self.request.data) serializer.is_valid(raise_exception=True) user = serializer.save() login(request, user) return Response("Login successful", … -
Cant load an image in Django Application
I'm trying to build an app and I want from views.py to save an image in a specific file and after that call the image from the template using static I try this path_to_save = r"..\AISystem\texttohandwriting\static\result.png" BG.save( rf"{path_to_save}") return render(request, "text_to_handwriting.html", context) as you can see I saved the image that was produced in the static\result.png and it saves correctly since i see the image. < The image changes every time the user enters a text in the HTML file, I do this <img width="400" height="400" src="{%static 'result.png' %}" alt=""> Terminal show this Could not find file. Using default file... [29/Aug/2023 17:39:00] "POST /text_to_handwriting.html HTTP/1.1" 200 992 -
issue with importing image in django project
#home{ background-size: cover; display: flex; flex-direction: column; padding: 3px 200px; height: 921px; justify-content: center; align-items: center; } #home::before { content: ""; position: absolute; background-image: url("{% static 'Image/Bg2.jpg'%}") no-repeat center center/cover; background-size: cover; top: 87px; left: 0; height:840px; width: 100%; z-index: -1; opacity: 0.78; } This is my code in style.css of my Django project. I am unable to import this image when I am running my server. My Project structure looks like this Project 4 |----App1 |--migration |--static | |---CSS | | |---style.css | |--Image | |---Bg2.jpg |--template |---index.html I had two folders in my static folder. My path to the image is ( "My Project/My app/static folder/Image folder/My_image" ). I imported this image in my CSS file. I tried below URLs also background:url("../Image/Bg2.jpg"). I just want my image to be available I run my server localhost:8000/index/ -
solution to use django-advanced-filters in html template instead of django-admin
I'm looking for a solution to using Django-advanced-filters in Django template instead of Django-admin currently Django-advanced-filters can use just in django-admin , I'm looking solution to get query from user based on conditions -
Django Form tag and action attribute
I am not good at English, but no matter how much I try, there is a problem, so I write a question. I wrote it using a translator, but I can read English a little bit. I want login page in Django. I have 2 app. "mysite", "myapp" mysite urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] myapp urls.py from django.urls import path from myapp import views from django.contrib.auth import views as auth_view app_name = 'myapp' urlpatterns = [ path('', views.index), path('result', views.result), path('reuslt2', views.result2), ] myapp views.py from django.shortcuts import render, HttpResponse from django.shortcuts import get_object_or_404, redirect from django.utils import timezone # Create your views here. def index(request): return render(request, 'main_page.html') def login_success(request): #login_info = [request.POST['username'], request.POST['password']] if request.method == 'POST': return HttpResponse('success') #return HttpResponse(login_info[0], login_info[1]) else: return HttpResponse('fail') def result(request): return render(request, 'main_page.html') def result2(request): return render(request, 'temp.html') The login page I want uses two input tags, and the method uses the POST method to get the ID and password input. I connect 127.0.0.1:8000/result. I can see 2 input tags. click submit button. -> connect 127.0.0.1:8000/result2 If the above method is successful, I think it will be possible … -
Cannot override UserCreateSerializer of Djoser
I would like to add additional fields when user registering. I created an app account. Added it to INSTALLED_APPS = [ ... 'account.apps.AccountConfig', ] In account I've created serializers.py from django.conf import settings from djoser.serializers import UserCreateSerializer class CustomUserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): fields = ( settings.LOGIN_FIELD, settings.USER_ID_FIELD, 'password', 'first_name', 'last_name', 'email', ) I've changed SERIALIZERS setting of DJOSER: DJOSER = { 'USER_CREATE_PASSWORD_RETYPE': True, 'SERIALIZERS': { 'user_create': 'account.serializers.CustomUserCreateSerializer', }, } urlpatterns in urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/auth/', include('djoser.urls')), path('api/v1/auth/', include('djoser.urls.authtoken')), ] When I send POST data to http://localhost:8000/api/v1/auth/users/ new user successfully registered. But fields 'first_name', 'last_name' are empty! I think DJOSER SERIALIZERS doesn't see 'user_create': 'account.serializers.CustomUserCreateSerializer'. My question - what I did wrong? How can I override UserCreateSerializer of Djoser? -
Trying to connect django and ms sql 2019 with django-mssql-backend
I've got this error: django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' ENGINE': 'sql_server.pyodbc', pip freeze shows me this: asgiref==3.7.2 distlib==0.3.7 Django==4.2.4 django-mssql==1.8 django-mssql-backend==2.8.1 filelock==3.12.3 mssql-django==1.3 platformdirs==3.10.0 pytz==2023.3 sqlparse==0.4.4 tzdata==2023.3 virtualenv==20.24.3 i tried use 'mssql' engine, but it doesn't work too -
Related drop-down lists in the Django admin panel?
how do I make linked drop-down lists in the Django admin panel? there are 3 models when you add a category to products, for example, electronics, and only what is related to electronics fell out in the subcategory. class Products(models.Model): name = models.CharField(max_length=255, verbose_name='Название') category = models.ForeignKey('Category', on_delete=models.CASCADE, verbose_name='Категория') subcategory = models.ForeignKey('SubCategory', on_delete=models.CASCADE, verbose_name='subКатегория') class Category(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') class SubCategory(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') category = models.ForeignKey('Category', on_delete=models.CASCADE) -
Django. Buttons stop working after fetching
I'm trying to fetch text,images from another html file using django and javascript. HTML Code: <body> <nav style="background: #000;"> <div class="top-bar"> <button type="button" id="page1" >Button</button><button type="button" id="page2">Button</button><button type="button" id="page3">Button</button><button type="button" id="page4">Button</button><button type="button" id="page4">Button</button> </div> </nav> <div id="content"> {% block body %} {% endblock %} </div> </body> JS Code: document.addEventListener("DOMContentLoaded",()=>{ const content = document.getElementById("content"); document.getElementById('page1').addEventListener('click', function() { fetch('path/to/index') .then(response => response.text()) .then(data => { content.innerHTML = data; }); }); document.getElementById('page2').addEventListener('click', function() { fetch('path/to/info') .then(response => response.text()) .then(data => { content.innerHTML = data; }); }); document.getElementById('page3').addEventListener('click', function() { fetch('path/to/comms') .then(response => response.text()) .then(data => { content.innerHTML = data; }); }); }) Whenever i fetch the data, my buttons stop working. I've created this file as a test. I'm currently trying to get texts into the content div using sidebar on my main site that im working on. Both files have the same issue. -
how to send post request when browser closing in React
Well, in order to be able to detect the status of browsers, if users are on the site, I want to send a request if they close the browser and change a feature in a model. It should be noted that this model is different from the user model in Django. Also, I'm using Django sessions and SESSION_EXPIRE_AT_BROWSER_CLOSE=True but that's not working. So I use React window.onblur event and that's not working again! I try this code in react but it's not working! let stid:string|null=localStorage.getItem('stationid') useEffect(() => { window.onblur=()=>{ console.log('hello') Api.delete(STATION_ID(stid)).then((res)=>{ console.log(res.data) }).catch(err=>{ console.log(err) }) } return () => { console.log('hello') } }, []) -
Running background tasks in Flask using Django
I have a web application built fully using Flask, at the moment the entire project runs on flask, i'm using many flask libraries for various functionality. However, some of these tasks i am running are very time consuming and take around 5 minutes to finish, and because of this if someone was to run this task and someone else wanted to navigate the website they would be stuck loading while the other lengthy task is done. I'm currently looking for ways to finish running this task in the background so that users can freely navigate the website without being held hostage for 5 minutes while processing is done, I looked into Celery but would rather not use it. Someone instead suggested that I integrate Django to handle this instead, is this feasible, if so how? Here is a quick sample of the current code I have: @app.route("/apple/newoffercodes/<int:appID>", methods=['GET','POST']) @login_required def newoffercodes(appID): application = ApplicationApple.query.filter_by(appleID=appID).first_or_404() package_name = application.appleID form = offerCode() if form.validate_on_submit(): filename = form.file.data result = createSubscriptionOffer(filename) if result == 200 or result == 201: flash("Offer Code Created Successfully","success") return redirect(url_for('offercodes',appID=appID)) else: flash("An error has occurred while creating the offer. Please check Apple Connect.", "danger") return redirect(url_for('offercodes',appID=appID)) return render_template('newOfferCodeApple.html', … -
Sonarqube exection failure while trying to analyse Python code locally on windows
C:\sonar-scanner-5.0.1.3006-windows\bin>sonar-scanner.bat INFO: Scanner configuration file: C:\sonar-scanner-5.0.1.3006-windows\bin..\conf\sonar-scanner.properties INFO: Project root configuration file: NONE INFO: SonarScanner 5.0.1.3006 INFO: Java 17.0.7 Eclipse Adoptium (64-bit) INFO: Windows 10 10.0 amd64 INFO: User cache: C:\Users\AREKAN.sonar\cache INFO: Analyzing on SonarQube server 9.9.0.65466 INFO: Default locale: "en_US", source code encoding: "UTF-8" INFO: Load global settings INFO: Load global settings (done) | time=105ms INFO: Server id: 147B411E-AYos9Bu0eOBihffPYMUp INFO: User cache: C:\Users\AREKAN.sonar\cache INFO: Load/download plugins INFO: Load plugins index INFO: Load plugins index (done) | time=48ms INFO: Load/download plugins (done) | time=313ms INFO: Loaded core extensions: developer-scanner INFO: Process project properties ERROR: Invalid value of sonar.sources for OLU-APP INFO: ------------------------------------------------------------------------ INFO: EXECUTION FAILURE INFO: ------------------------------------------------------------------------ INFO: Total time: 2.546s INFO: Final Memory: 21M/74M INFO: ------------------------------------------------------------------------ ERROR: Error during SonarScanner execution ERROR: The folder 'C:sonar-scanner-5.0.1.3006-windowsbincode' does not exist for 'OLU-APP' (base directory = C:\sonar-scanner-5.0.1.3006-windows\bin) ERROR: I put my django code in a folder and then edited the .property file to point to the folder where my Django code is but when I ran the sonarscan.. i go the error shown -
DRF ModelSerializer implicitly ignore some fields that are not excluded
I have a model: class GeneratedMessage(models.Model): generated_message_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) status = models.CharField(...) message_type = models.CharField(...) ... prospect = models.ForeignKey(to=Prospect...) ai_prompt = models.ForeignKey(to=AiPrompt...) And a model serializer: class GeneratedMessageSerializer(serializers.ModelSerializer): class Meta: model = GeneratedMessage exclude = ['prospect', 'ai_prompt'] read_only_fields = ['__all__'] Actually, I use this serializer inside another one: class GeneratedEmailSerializer(serializers.Serializer): body = GeneratedMessageSerializer() ... This is the way I create a response: class ProspectGenerateMessageAPI(APIView): ... @extend_schema(..., responses={200: GeneratedEmailSerializer}) def post(self, request): ... generated_message.save() response = GeneratedEmailSerializer(data={ ... "body": GeneratedMessageSerializer(generated_message).data }) response.is_valid(raise_exception=True) return HttpResponse.ok(response.data) However, the response has no field body.generated_message_id even though it was never excluded! Other fields like the body.status are presented in the response. Important facts: I find out in the Debug mode that GeneratedMessageSerializer(generated_message).initial_data have a valid id, while GeneratedMessageSerializer(generated_message).data not. Swagger docs generated by @extend_schema are somewhy correct with the field generated_message_id -
page not found while giving path in urls.py of app 'blog-single.html/<int:id>',views.blogsidebar, name='blog-sidebar'
It shows page not found while giving path in urls.py of app 'blog-single.html/<int:id>',views.blogsidebar, name='blog-sidebar' enter image description here It is my urls.py 's paths. Here while I added <int:id > the blog-single.html page started showing page not found enter image description here and it is my views.py's file .....can anyone say what causes for showing this error enter image description here -
Why dosent django find my assets and attachements?
I have a website hosted on centos7 And I want to move it to ubuntu22.04.3 I installed python 3.10.12 and 3.11.4 versions django and all prerequisits I'v changed the apacheconfig file but when I run the server It works but it does not find my assets and attachements here is the output on the stdout: sudo python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). August 29, 2023 - 12:00:53 Django version 3.2.12, using settings 'website.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [29/Aug/2023 12:00:58] "GET /fr/ HTTP/1.1" 200 55434 [29/Aug/2023 12:00:58] "GET /assets/css/default.css HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /assets/css/bootstrap-icons.css HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /assets/css/bootstrap.min.css HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /uploads/2022/12/08/photo1.PNG HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /uploads/2023/03/17/image35.JPG HTTP/1.1" 404 179 Please any idea might help share if you have a clue I tried modifying the apache2 config file and a lot more. -
Why can't gunicorn utilize more workers (google app engine)?
In documentation you can find https://cloud.google.com/appengine/docs/flexible/python/runtime. It says that not having gunicorn.conf.py that sets multiple workers could increase latency since default worker number is 1 (latency does get high with one worker 800ms). However obeying the recommended gunicorn setup increases the response time by 4 more seconds and sometimes it just fails to deliver. My entrypoint: entrypoint: gunicorn -c gunicorn.conf.py -b :$PORT main:app Entrypoint with one worker: entrypoint: gunicorn -b :$PORT main:app What could be the issue? -
Django:- The QR code is being generated successfully, but it is not being saved to the database
I'm using qrcode, a Python library that enables you to generate QR codes. I want to use this Python library inside my Django signals to generate a QR code for every newly created user. However, when the user is created, it doesn't create an Account model object, and the QR code is generated inside my project directory, instead of static folder. How can I solve this problem. signals.py: @receiver(post_save, sender=User) def create_account(sender, instance, created, **kwargs): if created: random_number = ''.join(random.choices(string.digits, k=20)) img = qrcode.make('cullize') img.save('default.png') Account.objects.create( user=instance, qr_code=img, account_id=random_number ) class Account(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) qr_code = models.ImageField(upload_to='qrcode') account_id = models.IntegerField() -
CommandError: App 'accounts' does not have migrations
when i run python manage.py makemigrations accounts and python manage.py migrate accounts, it does not create a migrations folder and even when i run python manage.py migrate it migrates all apps except accounts. The app has a pycache folder though I expected it to create a migrations folder -
Excluding venv directory in PyCharm does not work
I have a django project with the python virtual environment installed within the project directory. The directory is ignored by git. Now I would like to mark the directory as excluded in PyCharm. I can do this with other directories but if I do it with the venv directory, it doesn't work. It seems as the process is started. If I try do do it again, I get the option "Cancel Exclusion" (see screenshot). This does not go away and does not resolve itself also after longer periods of time (2hrs+). Any idea what I might be doing wrong or how I can fix this issue? -
Django transactions: the documentation about handling exceptions is not clear
In short: does the transaction.atomic() roll back the transaction if an exception occurs, regardless of whether it's properly handled or not? Here's a slightly modified example based on the documentation: try: with transaction.atomic(): generate_relationships_1() generate_relationships_2() generate_relationships_3() return True except IntegrityError: handle_exception(generic_message) return False However, what if I desire a more descriptive message when this happens? Consider the following: with transaction.atomic(): try: generate_relationships_1() except IntegrityError: handle_exception(message_1) return False try: generate_relationships_2() except IntegrityError: handle_exception(message_2) return False try: generate_relationships_3() except IntegrityError: handle_exception(message_3) return False Will the transaction still be rolled back if there's an exception? Examine the code carefully: the exception can arise within the transaction.atomic() block, and it's handled inside the block without transaction.atomic() being aware of the issue. -
Ctrl+C doesnt quit development server in VS Code (MacOS)
A couple months ago or so VS Code was automatically updated and ever since Im not able to kill development servers within the VS terminal for whatever reason. Before it used to work perfectly fine. It doesnt work for Django, React and Flask apps. Every time I want to quit a server I have to open up a new terminal and kill the entire process with "pkill -f", activate the virtual environment again etc. Im using MacOS High Sierra 10.13.01 and VSCode Version: 1.81.1 Screenshot: -
In Wagtail how can I access the Page object from inside the StructBlock template?
I have a page called Event For the event I would like to have a program. Program consists of ProgramEntry objects linked to the page with ParentalKey. I would like this program to be displayed in the html, but it should be in a streamfield so that the editors can place it wherever they like in the page. To do this I would like to render the my custom ProgramEntryBlock that is simply this: class ProgramEntryBlock(blocks.StructBlock): class Meta: label = _("Program entry") template = "blocks/program-entry-block.html" in my template blocks/program-entry-block.html I would like to have something like this: {% if page.program_entries.exists %} (...) {% for entry in page.program_entries.all %} (...) {% endfor %} {% endif %} How can I pass the Page object in this template? Or, what could be a better solution to my problem? -
Find count of students who made payment this month for each teacher
I have got following models Teacher(models.Model): name = models.CharField(...) Student(models.Model): name = models.CharField(...) Group(models.Model): teacher = models.ForeignKey(Teacher) students = models.ManyToManyField(Student) Payment(models.Model): student = models.ForeignKey(Student) I have to prepare report about teachers that includes tottal number students who made payment in this month. like Tacher A 12 students. Here I have tried this one to find number of students for single teacher. teacher.group_set.select_related("course").annotate(students = Count("students").aggregate(tottal = Sum("students")) Here I got number of all students but I can't filter students who made payment.