Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: populate ID field with initial data in an upload image form
I want to create a form to upload ecography images for a specific "consulutation". when I click on add images buuton, the form should show with the field "Consultation_id" already filled with the ID of this consultation.the problem is that i Can't do that using views.py here is my code : models.py class Echographie(models.Model): created_at = models.DateField(auto_now_add=True) consultation_id=models.ForeignKey(Consultation,on_delete=models.CASCADE,) image=models.ImageField(blank=True, null=True,upload_to="images/echo/") @property def nom_patient(self): return self.consultation_id.nom_patient form.py: class NewEchographieForm(forms.ModelForm): image=forms.ImageField(required=False) class Meta: model = Echographie fields = ['consultation_id','image'] views.py: def echographie(request,pk): current_consultation = Consultation.objects.get(id=pk) form = NewEchographieForm(request.POST or None,request.FILES,initial={'consultation_id':[current_consultation.id]} ) if request.user.is_authenticated: if request.method == "POST": if form.is_valid(): add_image = form.save() messages.success(request, "Image added successfully....") return redirect('home') return render(request, 'echographie.html', {'form': form, 'current_consultation': current_consultation}) else: messages.success(request, "You should login in....") return redirect('home') Can you help me? -
I want to implement django-polaris deposit and withdrawal integration
I'm building an anchor with django-polaris on the stellar network using the readthedocs tutorial. I'm stuck at the Enable Hosted deposit and withdrawals. Here is the code for the deposit integration; from decimal import Decimal from django import forms from rest_framework.request import Request from polaris.models import Transaction from polaris.templates import Template from polaris.integrations import ( DepositIntegration, WithdrawIntegration, TransactionForm ) from .users import user_for_account, create_user class AnchorDeposit(DepositIntegration): def form_for_transaction( self, request: Request, transaction: Transaction, post_data: dict = None, amount: Decimal = None, *args, **kwargs ): # if we haven't collected amount, collect it if not transaction.amount_in: if post_data: return TransactionForm(transaction, post_data) else: return TransactionForm(transaction, initial={"amount": amount}) # if a user doesn't exist for this Stellar account, # collect their contact info user = user_for_account( transaction.muxed_account or transaction.stellar_account ) if not user: if post_data: return ContactForm(post_data) else: return ContactForm() # if we haven't gotten the user's full address, colelct it elif not user.full_address: if post_data: return AddressForm(post_data) else: return AddressForm() # we don't have anything more to collect else: return None def after_form_validation( self, request: Request, form: forms.Form, transaction: Transaction, *args, **kwargs, ): if isinstance(form, TransactionForm): # Polaris automatically assigns amount to Transaction.amount_in return if isinstance(form, ContactForm): # creates the user to … -
How can I deal with data creation that depends on response of a microservice?
I have two microservices: one is responsible for manage players and the other is responsible for manage authentication/authorization. When I create a new player inside the player microservice I make a call to create the auth data like: auth_data = create_auth_object(data) # This will make a post in auth microservice and after it I use the ID return from auth microservice to create players infos like: data_example = { auth_id: auth_data.get("id"), #sometimes auth_data is empty (explained below) name: "example", real: "example2" } create_player(data_example) but sometimes the auth microservice return a timeout error (some GCP problem) and I cant create the player without the ID from auth microservice, but the auth data has been created in the database even I got the timeout error. So, if I try to create the player again I will receive an error that show the player already exists, but only the auth data exists, the player data was not created. How is the proper way to deal with It? Tell me if you need more details. -
How would you implement a front end file editor? [closed]
As title suggests, I want to implement a file editor for users, so that they can upload their own .txt, .py, .md files and edit them directly on front end. I already have the upload part, but I can't seem to figure out how to implement the file editor, I've been thinking on CKeditor but I do not know how to provide it with the file so it displays it's contents. The best guess I have while researching online is to parse the file and the provide ckeditor with it as context, but how would you do it? -
I want to send excel file with post API with a body of form-data in python/Django
this is the format Here is the code (https://i.stack.imgur.com/Yv60u.png) I've tested it with (https://i.stack.imgur.com/6boPz.png) I've checked the url. I got JSON response content-404 and status code-500 when I run that but if I send from postman it works. Do I have to contact API team or what is the problem? -
DRF return errors from model validation
I have models and serializers. Errors that are returned from the serializer are helpful because I can send them as a response to API and user can correct invalid data. However, errors that are from models are useless for me. They return 500 error and they don't have a body that I can send back to the user. Should I overide validate method even more to give me some usable errors or there is a method for that? models class School(models.Model): SUBJECT = ( ('Math', 'Mathematic'), ('Eng', 'English'), ('Cesolved', 'Chemistry'), ) name = models.CharField(blank=False, max_length=50) subject = models.CharField(choices=SUBJECT, max_length=15, blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(f'{self.name} is {self.subject}') serializers class SchoolSerializer(serializers.ModelSerializer): subject = serializers.ChoiceField(choices=School.SUBJECT) def validate(self, data): name = data["name"] if (5 > len(name)): raise serializers.ValidationError({"IError": "Invalid name"}) return data class Meta: model = School fields = "__all__" views class SchoolViewSet(viewsets.ModelViewSet): queryset = School.objects.all() serializer_class = SchoolSerializer def create(self, request): serializer = SchoolSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) for example, if name is shorter than 5 i return a kinda helpful error but when name is to long and I let the django models return the error only thing that I … -
Attribute error str object has no attribute get while submitting form
This is the ObjectCreateMixin class which from which my TagCreate class inherits from django.shortcuts import redirect, render class ObjectCreateMixin: form_class = None template_name = '' def get(self, request): return render( request, self.template_name, {'form': self.form_class()}) def post(self, request): bound_form = self.form_class(request.POST) if bound_form.is_valid(): new_object = bound_form.save() return redirect(new_object) else: return render( request, self.template_name, {'form': bound_form} ) Here is My TagCreate class class TagCreate(ObjectCreateMixin, View): form_class = TagForm template_name = 'organizer/tag_form.html' I am trying to create Tag object by passing the name and slug in form but whenever i submit form it gives error ATTRIBUTE error 'str' has no attribute 'get' -
I am trying to communicate between a r307 finger print sensor and a Django website using arduino and esp32
I am creating a Django website which reads finger prints and replies in true or false using the r307 finger print sensor, arduino and Esp32. Can anyone guide me how to do that. I have connected the finger print sensor with the arduino IDE and it enrolls and verifies finger prints successfully but I can not figure out how to connect it with my website. I am making a Django project. All I want it it read the fingerprint and respond in true or false. -
Combining Django Rest Framework with Python Azure Functions for bulk data retrieval - better alternatives?
I developed a Django Rest Framework application, which serves as the backend to my website. The app can retrieve data from an external API in bulk, for a given Django queryset that is retrieved from the request parameters. I have created a Django APIView that first retrieves the Django queryset from my Postgres database, using the standard DjangoFilterBackend and then makes a separate HTTP call for each unique ID in the queryset. Since the queryset can be quite big (1000+ records), implementing this in a 'standard' synchronous Django view was very slow. Hence I have decided to implemented the external API datea retrieval part as a (Python) Azure Function. This takes all the unique IDs from the retrieved Django Queryset as input in one JSON and then makes async calls in parallel for each ID using the asyncio and aiohttp modules. Below is a snippet of my Python code within the Azure Function that calls the external API: import asyncio import aiohttp async def call_external_api(session, unique_id) -> dict: ## Set params for request params = {'id': unique_id, 'apiKey': API_KEY} async with session.get(EXTERNAL_API_ENDPOINT, params=params) as resp: response_json = await resp.json() response_status_code = resp.status The communications within my current set-uplook somewhat like … -
Django file sharing system
Inspired by a idea of wetransfer.com, i decided to create a similar app with the same functionality. This is a one page app. And i got stuck a bit. The question itself is about system design rather than writting a code. On the high level the following is happening: A user selects files Once a file list is formed and an user presses a button to get a link, ajax-request is being initialized with files upload Once files upload ended, an unique link is being formed and a client gets it Easy, but i'm really confused how to make it well from design viewpoint Let's start from the beginning. How i see that (without too detailed things): Let's say there will be a temporary folder for forming a final user hierarchy and a final folder for storing a ready-download archive like this: TEMP_USER_FILES = os.path.join( BASE_DIR, "tmp") FINISHED_USER_FILES = os.path.join( BASE_DIR, "files") Technically i've done something like this: There are two inputs (in index.html): for files and folders respectively. JS creates a new empty FormData If it gets a file: a file is beeing added into FormData as key: value, where key is a file name and key is a … -
Django form in templatags
I need to place my form diffrent pages. How can I render form in my html? templatetags.py(https://i.stack.imgur.com/um4GL.png) -
How do I retrieve every row that is at least `interval` apart with Django's ORM?
Suppose I have the following model: class MyModel(Model): timestamp = models.DateTimeField(auto_now=True) ... I'd like to retrieve every row for MyModel that is at least some interval (in seconds) from the previous row. Rows are typically added every 30s, but I'd like to get those that are 30s or more apart. I've tried a variety of different solutions with the following getting me the closest. queryset = MyModel.objects.annotate( time_diff=F("timestamp") - Window( expression=Lag("timestamp"), order_by=(F("timestamp"),) ) ) Obviously, it doesn't really do anything, but, unlike below, this doesn't immediately error out. The field time_diff exists when I try to use it (i.e. queryset.last().time_diff outputs a timedelta). However, when I try to .filter on time_diff, I get an error like NotSupportError: Window is disallowed in the filter clause. Some of the other, non-working, attempts I've tried are below (note that I'm also trying to limit the records to a specific date range, but that's working fine): start_date = datetime(...) end_date = datetime(...) time_interval = ... # total seconds time_diff_window = Window( expression=Lag('timestamp'), order_by=F('timestamp').asc(), ) queryset = MyModel.objects.filter( timestamp__range=(start_date, end_date), ).annotate( time_diff=Extract('timestamp', 'epoch') - Extract('lagged_timestamp', 'epoch'), lagged_timestamp=Lag('timestamp', default=start_date, over=time_diff_window), ).filter( time_diff__gte=time_interval, ).order_by('timestamp') window = Window(expression=Lag("timestamp"), order_by=F('timestamp').asc()) lagged_timestamp = Lag("timestamp", default=Value(timedelta(seconds=0), output_field=DurationField()), over=window,) # Compute the … -
Css is working fine in Firefox but will not load in Microsoft edge or Chrome
While coding in Django i was trying to customize my website with some css but while testing multiple webbrowsers i found out that the css is not being applied in Microsoft or Chrome. But its working in firefox. The css file is loading correctly in all browsers but is not being applied. My HTML: <!DOCTYPE html> <html> <head> {% load static %} <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed&family=Roboto:wght@300&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" /> </head> <body> <label for="label1" id="label1">eeee</label> {% for card in cards %} <div class="card"> <img class="card_img" src="{{card.img.url}}" alt=""> <div class="card-content"> <h2 class="card_name" >{{card.name}}</h2> <p class="card_desc" >{{card.desc}}</p> </div> </div> {% endfor %} </body> </html> My css: *{ margin: 0; padding: 0; } /* Colors */ $color-primary-white: rgb(1, 240, 240); /* Colors */ #label1{ color: red; } body { display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 50px; font-family: 'Roboto', sans-serif; } .card { width: 24rem; height: 36rem; border-radius: 10px; overflow: hidden; cursor: pointer; position: relative; color: #fff; box-shadow: 0 10px 30px 5px rgba(0, 0, 0, 0.2); } .card_img { position: absolute; object-fit: cover; width: 100%; height: 100%; top: 0; left: 0; opacity: 0.9; transition: opacity .2s … -
Zoho Oauth flow returning invalid client
I am trying to build a Oauth flow using python Django. The goal is to get the access token for zoho and save it to DB. but at the step where we exchange access token by sending authorization_code, I am getting invalid-client error. I couldn't figure out what's wrong. I have tried changing to .in domain in token url but that too didn't worked. -
Cannot run celery worker while importing playwright library
I'm trying to run a simple playwright code with celery as you can see below: @shared_task def get_title(): with sync_playwright() as playwright: browser = playwright.chromium.launch() page = browser.new_page() page.goto('https://github.com') print(page.title()) browser.close() When I start the celery worker I get this error immediately from command line. I've tried every possible way with playwright using sync/async methods bot none of them worked. When I remove playwright imports and code belong to it celery worker starts without any issues. I think the main issue is with the import order. I import playwright or select library before celery get imported but i got the similar error from command line like this 'select' has no attribute 'epoll' without the full traceback. # celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") app = Celery("celery_app") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() The code is running on python:3.9.6-slim-buster Full traceback code: Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.9/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/usr/local/lib/python3.9/site-packages/celery/bin/celery.py", line 217, in main return celery(auto_envvar_prefix="CELERY") File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1404, in invoke … -
How to use Django REST Framework to pass data from one app to another, and in different Docker containers?
My current university assignment consists of us making a cinema website. One of the requirements is that the payment system (I am using Stripe) needs to be a seperate application that runs on a seperate container, and we need to use the Django REST Framework to pass info between them. My trouble at the moment is that I don't understand how to go through the process of: Customer selects all the tickets they want for a viewing Pass that information to the Stripe Payment App and redirect the customer to the checkout page Process the customers payment, and redirect them back to the main cinema apps index page I've placed comments in the below code to point out exactly where and how I intend to do this, but I just don't understand how to implement it using REST Framework. Any help would be greatly appreciated. My code in the views.py file to process the ticket and showing selection the customer has made is: def make_booking(request, pk=None): form = ReservationForm() if pk: form.fields['showing'].initial = Showing.objects.get(id = pk) # If the submit button is pressed if request.method == 'POST': ............. # Code to handle extracting information from the customers form ............. if … -
Error in uploading image from a react form into django model using django rest framework
I am building a website using Django and React I want to create a form that enters data into a model containing image field. I have followed many tutorials to make this but I have failed to upload image into the Image field models.py: class entry(models.Model): title = models.CharField(max_length=600) body = models.TextField() entryCover = models.ImageField(upload_to='entrycover', blank=True, null=True) def __str__ (self): return self.title serializers.py: class EntryFormSerializer(serializers.ModelSerializer): entryCover = serializers.ImageField(required=False) class Meta: model = entry fields = ['title', 'body', 'entryCover'] views.py: class EntryFormViewSet(viewsets.ModelViewSet): queryset = entry.objects.all() serializer_class = EntryFormSerializer parser_classes = (MultiPartParser, FormParser) def post(self, serializer): serializer.save(creator=self.request.user) urls.py: urlpatterns = [ path('entryForm/', views.EntryFormViewSet) ] in Form.js: import React from "react"; import Select from 'react-select' import axios from 'axios'; import { AxiosInstance } from "axios"; export default function Form(){ const [inputs, setInputs] = React.useState({}); const handleImageChange = (e) => { console.log(e.target.files[0]) let image = e.target.files[0] setInputs(values => ({...values,'entryCover' : image})) }; const handleChange = (event) => { const name = event.target.name; const value = event.target.value; setInputs(values => ({...values, [name]: value})) } const handleSubmit = (event) => { event.preventDefault() let form_data = new FormData(); form_data.append('entryCover', inputs.entryCover, inputs.entryCover.name); form_data.append('title', inputs.title); form_data.append('body', inputs.body); axios.post('/entryForm/', form_data, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => { console.log(res); }).catch(err … -
Prevent the user from going to the URL manually
I am writing a website on the Django framework I have a user application in which authorization, registration, password change, user password reset are configured I have a url: auth/password_change/ that processes a view of the PasswordChangeView class embedded in Django with a form for changing the user's password and, if successful, redirects to the url: auth/password_change_done/ auth/password_change_done/ handles the representation of the PasswordChangeDoneView class built into Django, which handles a template that says: you have successfully changed your password But any authorized user, even without changing the password, can manually go to the URL auth/password_change_done/ and get the page to which the redirect should go only if the password is successfully changed Tell me how to make it so that no one can manually get to the URL auth/password_change_done/, but only if the password has been successfully changed I tried to use re_path, but it has nothing to do with it at all I need some other way I will be grateful to everyone -
Django admin page formatting is messed up
Picture of formatting I made some updates to my django backend that is running on an azure app service and suddenly the formatting is all broken, see above. I tested it on a local server and the formatting is perfectly normal so I'm very confused, has anybody experienced a similar issue before or have any ideas on what could cause this? EDIT: Wanted to add that I checked the web browsers inspector logs and found errors saying that "the resource from [url] was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)." I assume thats the issue but I'm unsure how to fix that through azure -
Django App not able not able to run on Heroku Container
I am trying to build and deploy a Django app using docker images with heroku.yml, but I am having issues running the app. All I get is application error, which might be related to the configuration I have. Attached below is the Dockerfile and the heroku.yml: Dockerfile FROM python:2.7.17 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -U pip RUN pip install -r requirements.txt COPY . /code/ EXPOSE $PORT CMD ["uwsgi", "--ini", "uwsgi/production/uwsgi.ini"] heroku.yml build: docker: web: Dockerfile run: web: command: - uwsgi - --ini - uwsgi/production/uwsgi.ini image: web -
KeyError: 'ATOMIC_REQUESTS' when running DRF tests with mysqlclient installed
I have a functioning test suite for DRF. It uses @pytest.mark.django_db() to access an SQL Server DB. I now have the need to access an ancillary MySQL DB, so I installed mysqlclient. Without changing any of my source code or django settings, intalling this package alone breaks my test suite. Note, that the actual mysqlclient seems to work fine and allows me to access the ancillary MySQL DB. This is the error django/core/handlers/base.py(348)make_view_atomic() def make_view_atomic(self, view): non_atomic_requests = getattr(view, "_non_atomic_requests", set()) for alias, settings_dict in connections.settings.items(): > if settings_dict["ATOMIC_REQUESTS"] and alias not in non_atomic_requests: E KeyError: 'ATOMIC_REQUESTS' I have tried using this: @pytest.mark.django_db(databases=["default"]) to isolate things to the SQL Server DB. It doesn't help. I have tried setting ATOMIC_REQUESTS in settings and it doesn't stick. DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ['DATABASE'], 'USER': os.environ['USERNAME'], 'PASSWORD': os.environ['PASSWORD'], 'HOST': os.environ['SERVER_URL'], "ATOMIC_REQUESTS": True, 'OPTIONS': { 'driver': 'ODBC Driver 18 for SQL Server', 'extra_params': "Encrypt=no" }} In the debugger, it doesn't show 'ATOMIC_REQUESTS' in the settings. ipdb> settings_dict {'ENGINE': 'mssql', 'HOST': 'localhost', 'NAME': 'dev'} -
Testing 500 error code in django rest API unit test
I am working on unit tests for my API endpoints which I have built using Django rest_framework. I was able to test most of the error codes related to my endpoint except the 500 error code. Is there are way to mock the client function to return 500 error response or any cleaner way in unit test framework? class UserApiTests(TestCase): def setUp(self): self.client = APIClient() ... def test_retrieve_user(self): """Test server failure while retrieving profile for user.""" res = self.client.get(USER_URL) # Below should return server error self.assertEqual(res.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR) -
Django using database without migration
I have a Django application running using MySQL database, and everything works fine. For another part of the same application, I want to create a new Django application, implement database sharding, and have a separate database to store the tracking data and use the existing database (used by previous Django application) for authentication and other stuff. But since I need to get data from the existing database using Django ORM, I created models with the required-only fields in the new application as well. # authentication.models.User class User(AbstractUser): email = models.EmailField('email address', blank=True, unique=True) is_shared = models.BooleanField(verbose_name='Is Shared User', default=False) class Meta: app_label = 'authentication' managed = False I want to use this model for authentication in the admin panel as well (the same is used in the existing application). But I do not want this new application to migrate changes to the master database, so added managed=False in the Meta class. The settings.py file is AUTH_USER_MODEL = 'authentication.User' DATABASE_ROUTERS = [ 'app.database_routers.tracking.TrackingRouter' ] DATABASES = { 'default': eval(os.environ.get('DATABASE_MASTER')), 'database_tracking': eval(os.environ.get('DATABASE_TRACKING')) } where the default database has to be used for authentication and access to the admin panel. Migration should not write to this database as the migration should only be … -
Uncaught TypeError: Cannot read properties of null (reading 'classList') Django extends
I know this is bit common to ask but I'm still confused why it didn't read the classlist it says error in the console. I just want to pops the toaster when button was click I've tried putting js scripts in different places because The JS script tag should run after the HTML elements have been declared. The DOM element exists before accessing, still don't have any idea why it doesn't work what I did. <script src="{% static 'assets/vendor/libs/toastr/toastr.js' %}"></script> <script src="{% static 'assets/js/ui-toasts.js' %}"></script> transaction.html <button type="button" class="btn btn-label-primary add-data">Click button</button> {% block footer_scripts %} <script> $(document).ready(function(){ $('.add-data').click(function (event) { const toastAnimationExample = document.querySelector('.toast-ex'); let selectedType, selectedAnimation, selectedPlacement, toast, toastAnimation, toastPlacement; if (toastAnimation) { toastDispose(toastAnimation); } toastAnimationExample.classList.add('animate__fadeInRight'); toastAnimationExample.querySelector('.ti').classList.add('text-success'); toastAnimation = new bootstrap.Toast(toastAnimationExample); toastAnimation.show(); // Dispose toast when open another function toastDispose(toast) { if (toast && toast._element !== null) { if (toastPlacementExample) { toastPlacementExample.classList.remove(selectedType); toastPlacementExample.querySelector('.ti').classList.remove(selectedType); DOMTokenList.prototype.remove.apply(toastPlacementExample.classList, selectedPlacement); } if (toastAnimationExample) { toastAnimationExample.classList.remove(selectedType, selectedAnimation); toastAnimationExample.querySelector('.ti').classList.remove(selectedType); } toast.dispose(); } } }); }); </script> {% endblock footer_scripts %} -
Django Rest Framework Mock Test
I have a requirement where I need to execute testcases of a view that uploads data to cloud when the create method is called. I want to mock this view to verify create functionality without the file upload happening. Can you please tell me Which DRF library I need to use? thank you.