Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have two errors because of Django or Apache
Two errors: Error 404 (Not Found) on POST request to http://localhost/upload-avatar/ and SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON.When I try to send a POST request to http://localhost/upload-avatar/ I get a POST error http://localhost/upload-avatar/ 404 (Not Found) and a SyntaxError: Unexpected token '<', "< !DOCTYPE "... is not valid JSON. I would like to understand what is the reason and how to fix this problem. There are suspicions that the problem is in Apache. I am using wamp. I connected Django after some time of using and writing wamp code. I configured Apache. I also checked the routing settings and the server startup, but the problem remains. I ask for help in identifying and eliminating this problem. Thank you in advance! Code: JS: PhotoUpload.addEventListener('change', function() { const file = this.files[0]; if (file) { const reader = new FileReader(); reader.addEventListener('load', function() { photo.setAttribute('src', this.result); photo.classList.remove('alt-centered'); PhotoUpload.style.display = 'none'; const formData = new FormData(); formData.append('photo', file); fetch('/upload-avatar/', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.error('Error:', error); }); }); reader.readAsDataURL(file); } else { photo.setAttribute('src', '#'); photo.classList.add('alt-centered'); PhotoUpload.style.display = 'block'; } }); }; views.py from django.shortcuts import render from django.views.decorators.csrf import … -
request.user return AnonymousUser in django, react project
I have a web project what back-end is coded with django and front-end is coded with react. In my project, i want to create an order to a special user so this part of project needs to know the user but when i used request.user it returned AnonymousUser. here are the react, axios code and views.py with rest_framework: react code // Hook to save game id and price const [all, setAll] = useState({'game': 0, 'price': 0}); // get state const location = useLocation(); const state = location.state; useEffect(() => { setAll({'game': state[0]}, 'price': suggestion); }, []) // To check user confirm suggestion and make order api. const orderApi = async (e) => { e.preventDefault(); try { // console.log({'state': state[0], 'suggestion': suggestion}); console.log(all); const {status} = await axios.post('http://127.0.0.1:8000/api-1/order/create/', all); if (status === 201) { console.log('created'); } } catch (err) { console.log(err) } } views.py from rest_framework import status from rest_framework.response import Response from . import serializer from rest_framework.decorators import api_view from . import models from game.models import Game @api_view(['GET', 'POST']) def orderCreate(request): # Here my program return AnonymousUser print(str(request.user) + '\n') if request.method == 'POST': ....... orders = models.Order.objects.all() serialized = serializer.OrderSerializer(orders, many=True) return Response(serialized.data, status=status.HTTP_200_OK) To write a clean code … -
Using enums in Django with error ModuleNotFoundError: No module named 'models'
I am trying to use enums in my unit tests but I'm getting an error when I try to import them. An excerpt from models.py: class SeekingConstants: MEN = 'Men' WOMEN = 'Women' BOTH_MEN_AND_WOMEN = 'Both men and women' An excerpt from test_user_api.py: from models import SeekingConstants ... def test_update_user_seeking_choice(self): """Part 1: Update the seeking choice from nothing""" payload = { 'email': 'test@example.com', 'seeking_choice': SeekingConstants.WOMEN } res = self.client.patch(ME_URL, payload) self.user.refresh_from_db() self.assertEqual(self.user.email, payload['email']) self.assertTrue(self.user.seeking_choice, payload['seeking_choice']) self.assertEqual(res.status_code, status.HTTP_200_OK) """Part 2: Update an existing seeking choice""" new_payload = { 'email': 'test@example.com', 'seeking_choice': SeekingConstants.BOTH_MEN_AND_WOMEN } res = self.client.patch(ME_URL, new_payload) self.user.refresh_from_db() self.assertEqual(self.user.email, payload['email']) self.assertTrue(self.user.seeking_choice, payload['seeking_choice']) self.assertEqual(res.status_code, status.HTTP_200_OK) I'm not sure why I can't import this enum or how I should import this enum. -
Trying to implement the django-formset library but I am unable to get any of the buttons to work. They are completely non-responsive
I am trying to utilize the django-formset library to create dynamic forms. However, I am unable to get any of the buttons to work (whether they're add/submit or add forms). The only error in the javascript console was the following: Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules at Object.i [as convertPseudoClasses] (http://127.0.0.1:8001/static/formset/js/chunk-KFPGMBXM.js:1:354) at http://127.0.0.1:8001/static/formset/js/django-formset.js:25:29909 This is my first time working with django, html, css, javascript, and jquery but as far as I could trace the issue, I thought it maybe had something to do with not loading the typescript implementation of the 'click' webelement based on this error. But I got stuck tracing the error and so I tried to simplify/isolate the issue by creating a new project and copying the examples in the documentation. I also though there could be a conflict or issue with one of my templates, another library, or with a javascript function... ...but I can't get even the simplest model/form button to work using the example in Chapter 9 of the documentation. So I'm wondering if there's something really basic I'm missing. The following example doesn't throw any errors in the browser console but results in the same dead … -
"The client was disconnected by the server because of inactivity" using an async function in Django
I'm using Django 4.2 connected to a MySQL 8 database. I'm using asyncio for a function I really need to run asynchronously: example_object = asyncio.run(example(request)) async def example(request): object = await ModelExample.objects.filter(example=example).afirst() return object I started by having the error in the await line: MySQL server has gone away Then, by manually closing connection like: example_object = asyncio.run(example(request)) connection.close() I started having the following error: The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior This error don't happen right away, but after a few hours (maybe 8h, like the default wait_timeout variable) after I restart the (nginx) server. Things that I tried: Adding close_old_connections() before asyncio.run. Don't understand why there is an inactive connection left open at all. Increasing the wait_timeout value and interactive_timeout variables in my MySQL config file. I find it very strange that this had no impact at all but the "SHOW VARIABLES" command shows me they are indeed currently set to 31536000. Then I thought that maybe the connection from Django is somehow independent of that and tried setting CONN_HEALTH_CHECKS option to True, in the hopes that "if the health check fails, the connection will be reestablished … -
Likes as a many to many
I'm making a public prayer journal in full stack(react w/ nextjs and python w/ django) where you can also add and like verses. As the title says the likes are the many to many but I need it to where any component that displays verse likes will need all of the likes for a user and store them in state. If a verse is in the userLikes for a user, the like button should get checked on render. I need a change handler to submit a userlike to the api whenever the like button is checked, and delete a userlike whenever the like button is unchecked. But I'm unsure of how it's supposed to look exactly, I have trouble translating sentences to code. I already have the api views and data module, as seen below: user_like class LikeView(ViewSet): def retrieve(self, request, pk): try: user_like = UserLike.objects.get(pk=pk) serializer = UserLikeSerializer(user_like) return Response(serializer.data) except UserLike.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) def list(self, request): user_likes = UserLike.objects.all() verse = request.query_params.get('verse', None) user = request.query_params.get('user', None) if verse is not None: user_likes = user_likes.filter(verse_id=verse) if user is not None: user_likes = user_likes.filter(user_id=user) serializer = UserLikeSerializer(user_likes, many=True) return Response(serializer.data) def update(self, request, pk): user_like … -
TypeError: Cannot read properties of undefined (reading 'params') Django + React
Uncaught TypeError: Cannot read properties of undefined (reading 'params') Unabel to navigate to id can anyone help? i am woriking on django as backend and react as frontend class ArticleDetail extends React.Component{ state={ article:{} } componentDidMount(){ const id = this.props.match.params.id; axios.get(`http://127.0.0.1:8000/api/${id}`) .then(res =>{ this.setState({ article:res.data }); console.log(res.data) }) } render(){ return( <Card title={this.state.article.title} > <p>{this.state.article.content }</p> </Card> ) } }``` TypeError: Cannot read properties of undefined (reading 'params') Unabel to navigate to id can anyone help? i am working on react + django. My data from server in list is showing but when i try to navigate to particular data id it shows error -
How to add validators and constraints on Django admin form with bulk inline data
I have 3 simple Django models to create a reservation system class User(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Activity(models.Model): title = models.CharField(max_length=255) category = models.CharField(max_length=255) start_reservation = models.DateTimeField() end_reservation = models.DateTimeField() max_capacity = models.IntegerField() def clean(self): if self.start_reservation > self.end_reservation: raise ValidationError("Start date must be before end date") class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) class Meta: unique_together = ['user', 'activity'] My admin forms look like this @admin.register(User) class UserAdmin(admin.ModelAdmin): pass class ReservationAdmin(admin.TabularInline): model = Reservation extra = 0 @admin.register(Activity) class ActivityAdmin(admin.ModelAdmin): inlines = [ReservationAdmin] When I save an ActivityAdmin form, how can I ensure, that the number of reservations for a specific activity does not go over the max_capacity? I tried using the clean method on the reservation like this: class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) class Meta: unique_together = ['user', 'activity'] def clean(self): print(self.activity.reservation_set.count()) if self.activity.reservation_set.count() >= self.activity.max_capacity: raise ValidationError("Max capacity reached") But in the console, it prints the amount of reservations before any of the form data is saved to the DB. For example when I create a brand new activity (max_capactiy = 2) and I add 3 inline reservations, the console says: 0 0 0 even though … -
How to use import Geopackage data to my Django RESTful API?
I want to create a full-stack web application to let users query parks and greenspace in the UK, something like this: https://www.barnet.gov.uk/directories/parks. I want to build a Django RESTful API to query parks and greenspaces data. I am still a beginner and I am still learning. I have never imported large amounts of data to my app/database before. Usually, I manually input the data one by one for my RESTful APIS. This time, I don't want to manually input all the data. I want to build a project that is based on real-world data. Therefore, I found a public dataset for parks and greenspace (?), https://www.data.gov.uk/dataset/4c1fe120-a920-4f6d-bc41-8fd4586bd662/os-open-greenspace. I find it hard to understand what is the page about. I downloaded the Geopackage/gpkg file and I don't know how to use it. Here are some questions I have in mind: Is this the data I am looking for? Does the data contains info about the park, such as the park name? Or does it only store the geo location of the park? What I want to do is somehow transform this gpkg file into data I can play with in my Django RESTful API. And then I will write some API endpoints … -
django adding extra data to IntegerChoices
I need to add extra data to enum Class IntegerChoice in django. I have carefully read the answer here How to add extra data to TextChoices? but it does not seem to work. the definition of my enum type is : class FabricType (models.IntegerChoices): """an enumeration class with type, subclass and key words added first item is the code, second is translated verbose name, third is choice specific help, third is Group fourth is a list of keywords anychange in the number will require migration but adding new keywords will not """ CASTON = (1, _('Caston'), _('Basic'), []) JERSEY = (2, _('Jersey'), _('Basic'), []) TUBULAR = (3, _('Tubular'), _('Basic'), []) def __new__(cls, value, label, group, keywords, ): obj = int.__new__(cls, value) obj._value_ = value obj.group = group obj.keywords = keywords obj.help = help return obj def help_dict(cls): """help_dict for the FabricType""" help_dict = {'CASTON': _('the first few rows of a knit'), 'JERSEY': _('help_text'), 'TUBULAR': _('help text') return help_dict I have declared the EnumMixin as follows : class EnumMixin: ''' an Enum which Converts a DB value back to its Choices value''' def __init__(self, *args, enum=models.Choices, **kwargs): self.__enum = enum self.help_dict = kwargs.get('help_dict', None) kwargs.pop('help_dict', None) # it sets choices for … -
How to set the current proper date and time to "DateField()" and "TimeField()" respectively as a default value by "TIME_ZONE" in Django Models?
The doc says below in DateField.auto_now_add. *I use Django 4.2.1: Automatically set the field to now when the object is first created. ... If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateField: default=date.today - from datetime.date.today() For DateTimeField: default=timezone.now - from django.utils.timezone.now() So, I set timezone.now and date.today to datetime's DateTimeField() and date1's DateField() respectively and I also set current_date which returns timezone.now().date() and current_time which returns timezone.now().time() to date2's DateField() and time's TimeField() respectively as shown below: # "models.py" from django.db import models from datetime import date from django.utils import timezone def current_date(): return timezone.now().date() def current_time(): return timezone.now().time() class MyModel(models.Model): datetime = models.DateTimeField(default=timezone.now) # Here date1 = models.DateField(default=date.today) # Here date2 = models.DateField(default=current_date) # Here time = models.TimeField(default=current_time) # Here Then, I set 'America/New_York' to TIME_ZONE in settings.py as shown below: # "settings.py" LANGUAGE_CODE = "en-us" TIME_ZONE = 'America/New_York' # Here USE_I18N = True USE_L10N = True USE_TZ = True But, date1's DateField() and time's TimeField() show UTC(+0 hours)'s date and time on Django Admin as shown below: Next, I set 'Asia/Tokyo' to TIME_ZONE in settings.py as shown below: # "settings.py" LANGUAGE_CODE = "en-us" TIME_ZONE = 'Asia/Tokyo' # Here … -
SyntaxError: Unexpected token '*' error when i try to load my javascript
i am getting this error SyntaxError: Unexpected token '*'. import call expects exactly one argument. when i load my javascript file in my django project. this is my code btw import * as THREE from 'three'; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000); const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector("#bg"), }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth,window.innerHeight); camera.position.setZ(30); renderer.render(scene,camera); const geometry = new THREE.OctahedronGeometry(1,0); const color = new THREE.Color(134, 0, 255); const mat = new THREE.MeshBasicMaterial({color: color,wireframe: true}); const torus = new THREE.Mesh(geometry,mat); scene.add(torus); function animate(){ requestAnimationFrame(animate); renderer.render(scene,camera); } animate() i have already tried: looking if i have the correct javascript version that supports import i have and looking if i load the file correctly and triple checking if i have installed three correctly aswell. but for some reason it just does not work. -
IN DRF, how to create a POST serializer where I can add multiple values of a Foreign Key field
These are 2 models I have: class Skill(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name + " - ID: " + str(self.id) class Experience(models.Model): consultant = models.ForeignKey("Consultant", related_name="experience", on_delete=models.CASCADE) project_name = models.CharField(max_length=100) company = models.CharField(max_length=100) company_description = models.TextField(null=True, blank=True) from_date = models.DateField() to_date = models.DateField() project_description = models.CharField(max_length=100) contribution = models.TextField() summary = models.TextField() is_pinned = models.BooleanField(default=False) role = models.CharField(max_length=100, null=True) skill = models.ForeignKey("Skill", related_name="experience", on_delete=models.CASCADE) I want to do something that is quite common but apparently not possible out of the box with DRF: I want to have an endpoint /experience/ with a POST method where I can send a LIST of skill ids (skill field, ForeignKey). For example: { "project_name": "Project AVC", "company": "XYZ Company", "company_description": "Description of XYZ Company", "from_date": "2022-01-01", "to_date": "2022-12-31", "project_description": "Description of Project ABC", "contribution": "Contributions to Project ABC", "summary": "Summary of Experience", "is_pinned": false, "role": "Consultant", "skills_ids": [1,2,3], "consultant": 1 } If there are Skill records in the DB with ids 1,2,3 then it will create 3 records in the experience table (one for each skill ofc) . If there's no skill with such id, then during validation it should return an error to the user informing so. The name of the … -
i need help in django views and date
I'm new to Django and trying to do something here. Even if it is out of date, you cannot edit it because less than 1 hour is left. i get the error Thanks for your help. if shop.manager != user: messages.error(request, "You are not the manager.") return redirect('home') shop_datetime = timezone.make_aware(datetime.combine(shop.date, shop.hour)) if shop_datetime <= now: messages.error(request, "You cannot edit it because it is out of date.") return redirect('shopdetail', slug=slug) if last_edit_time >= now: messages.error(request, "You cannot edit this as there is less than 1 hour left.") return redirect('shopdetail', slug=slug) if request.method == "POST": form = ShopUpdateForm(request.POST, instance=shop) if form.is_valid(): if form.cleaned_data['date'].date() < date.today(): form.add_error('date', 'You cannot add anything to the previous date') else: etkinlik = form.save(commit=False) etkinlik.slug = slug etkinlik.save() return redirect('shopdetail', slug=slug) else: form = ShopUpdateForm(instance=shop) data = create_calendar(year, month) return render(request, 'shop/edit_shop.html', {'form': form, **data}) -
Search query when the search sentence is less than characters
Good afternoon. A question. How can such a search be implemented in Django ORM(or SQL query) There is an arbitrary table with the field name "description". There is one entry, and the value of the field "description" is python. How to formulate a database search query to get this record if the incoming sentence looks like this: python-is a great programming-language. Thank you. Requests of the form ` Entry.objects.get(headline__icontains="Lennon") are not suitable because there are fewer characters in the searched sentence -
Styles in css file not showing on html template
css not linking in django iam trying to create an ecommerce website for my project and made a css file and linked it to the base template. But those results are not to be seen. settings.py STATIC_URL = "static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static"),] Base template css linking <link rel="stylesheet" type="text/csss" href="{% static '/css/custom.css' %}"> CSS body{font-family: 'Roboto', sans-serif; background-color:#D3D3D3; } .text-center{ font-family:roboto; } .card-title{ font-weight:bold; font-family:'Roboto', sans-serif; } /*footer*/ .foot{ background-color:blue; position:fixed; bottom:0; left:0; height:10px; width:100%; } h2{ font-family:'roboto',sans-serif; } /*cart-icons*/ .custom_icon{ margin:7px; font-size:20px; color:blue; } /*invoice*/ .inv{ display:block; } urls.py from django.urls import path from cart import views app_name='cart' urlpatterns=[ path('cart_view',views.cart_view,name='cart_view'), path('add_cart/<int:p>',views.add_cart,name='add_cart'), path('add_cart/<int:p>',views.add_cart,name='add_cart'), path('minus/<int:p>',views.minus,name='minus'), path('delete/<int:p>',views.delete,name='delete'), path('order',views.order,name='order'), path('invoice',views.invoice,name='invoice'), ] I linked the css to base template, but not seeing any results, inline styling is working though. project structure -
Get value of a field from a foreigKey in Django Models
I have two classes in my Database in Django class Test(models.Model): sequenzaTest = models.ForeignKey("SequenzaMovimento", null=True, on_delete=models.SET_NULL) class SequenzaMovimento(models.Model): nomeSequenza = models.CharField(max_length=50, blank=False, null=False) serieDiMovimenti = models.TextField(blank=False, null=False, default="") Now, every Test object created can be associated with just one SequenzaMovimento object. Different Test objects can have the same SequenzaMovimento Now, I know the primary key of my Test. How do I find the serieDiMovimenti inside the SequenzaMovimento object which is linked to the Test object? I can get the sequenzaTest from the Test object with testo_sequenza = Test.objects.get(pk=idObj) testo_sequenza.sequenzaTest but I can't find to understand how access serieDiMovimenti -
Access json field's dict value which is inside list using queryset
I have django model named Blog with fields title, data class Blog(models.Model): title = models.CharField(max_length=100) data = models.JSONField(default=dict) I have about ten of instances with data field value like Instance 1 [ { "name": "random" } ] Instance 2 [ { "name": "fact" } ] Instance 3 [ { "name": "fact" } ] Instance 1 [ { "name": "random" } ] Instance 1 [ { "name": "random" } ] And I am trying to sort the the blogs based on data field name key is used, and show it like random, 3 fact, 2 and I am intending it to do it more efficiently with database functions. top_used_names = Blog.objects.annotate( name=RawSQL("REGEXP_REPLACE("data", '^.\*\\"name\\": \\"(.\*?)\\".\*$', '\\\\1')", params=\[\]) ).values('name').annotate( count=Count('name') ).order_by('-count')\[:5\] but It showed me errors. then I tried using top_used_names = Blog.objects.annotate( name=Cast(KeyTextTransform("name", "data"), output_field=TextField()) ).values("name") it also showed me errors. I have spent hours but it is still showing the error Any help would be much Appreicated. -
Dynamic django inline_formset using pure javascript
I was searching on working examples for django inline_formset with javascript and found this post Add a dynamic form to a django formset using javascript in a right way. In the process, I tried to convert the Jquery portion into pure javascript? I have tried const btnAddMoreImg = document.querySelector('#add-image-button'); btnAddMoreImg.addEventListener('click', (evt) => { evt.preventDefault(); let count = document.querySelector('#item-images').children.length; let tmplMarkup = document.querySelector('#images-template').innerHTML; let compiledTmpl = tmplMarkup.replace(/__prefix__/g, count); $('#item-images').append(compiledTmpl); // how to convert this to pure javascript? // update form count document.querySelector('#id_images-TOTAL_FORMS').setAttribute('value', count + 1); }) This works but there is still this jquery code $('#item-images').append(compiledTmpl) which I tried to change to document.querySelector('#item-images').append(compiledTmpl), but the end result would be a string of html tags instead of a new form added. -
Django - INTEGRITY ERROR on column that no longer exists
I am getting this error: IntegrityError at /register/ null value in column "total_daily_mission_progress" violates not-null constraint DETAIL: Failing row contains (363, 0, 374, free, 0, null, unranked, 0, , odifj@gmail.com, 0, f, [], 0, {}, {}, t, null, null, null, null, null, {}, null, null, No phone number set, This user has not set a description yet., /static/images/profilepictures/defaultavatar.png, {}, {}, {}, {}, {}, 0). However, the column total_daily_mission_progress no longer exists in my UserDetail model. I deleted it a while ago and migrated. However, this issue comes up every time I try to create a new UserDetail model. Why is this occuring? I don't have the total_daily_mission_progress anywhere in my code. And how can I fix it? EDIT: Here is my output after running python3 manage.py showmigrations --verbosity 2 [X] 0001_initial (applied at 2022-12-29 19:39:10) [X] 0002_logentry_remove_auto_add (applied at 2022-12-29 19:39:10) [X] 0003_logentry_add_action_flag_choices (applied at 2022-12-29 19:39:10) auth [X] 0001_initial (applied at 2022-12-29 19:39:09) [X] 0002_alter_permission_name_max_length (applied at 2022-12-29 19:39:11) [X] 0003_alter_user_email_max_length (applied at 2022-12-29 19:39:11) [X] 0004_alter_user_username_opts (applied at 2022-12-29 19:39:11) [X] 0005_alter_user_last_login_null (applied at 2022-12-29 19:39:12) [X] 0006_require_contenttypes_0002 (applied at 2022-12-29 19:39:12) [X] 0007_alter_validators_add_error_messages (applied at 2022-12-29 19:39:12) [X] 0008_alter_user_username_max_length (applied at 2022-12-29 19:39:12) [X] 0009_alter_user_last_name_max_length (applied at … -
Django Application not getting registered in admin site
I have created new application in Django project but it is not showing in admin page . I have updated the admin.py file as well I am looking for solution to get my app registered in admin page . I have tried everything I could find in google . admin.py file from django.contrib import admin # Register your models here. from .models import * admin.site.register(packagedrop) Modle class packagedrop(models.Model): pkgID = models.AutoField(primary_key=True) envname = models.CharField(max_length=64) CreatedDate = models.DateField(auto_now_add=True) product = models.CharField(max_length=64) prodhier = models.CharField( max_length=25) prodversion = models.CharField( max_length=40) initiator = models.CharField(max_length=100) Description = models.TextField(max_length=200) Status = models.CharField(max_length=100, default='Submitted' ) updated_time = models.DateTimeField(auto_now_add=True) -
Deploying Django Web App with GPU-Intensive Deep Learning Models?
What is the recommended approach for deploying my Django web application that includes multiple components (database, views, authentication) alongside GPU-intensive Deep learning models (e.g., deezer/spleeter and pyannote/speaker-diarization)? Should I deploy everything on a single server with a powerful GPU, or is it better to separate the deep learning models and deploy them on a dedicated server with a powerful GPU while deploying the web application on a traditional server (e.g., DigitalOcean, Heroku) within a Docker container, and then call the models from the web app? Please give me recommandations about the bests (cheapest) GPU servers providers. -
django: allow allowed_hosts to work with debug = True also
I have a requirement that my django app ALLOWED_HOSTS=["somedomain.com"] work when DEBUG=True Because it only works for DEBUG=False Can anyone suggest how to achieve this. -
Why django-social-auth in djoser don't find client_id in authorization_url if client_id is provided
Why django-social-auth in djoser don't find client_id in authorization_url if client_id is provided I trying authenticate user with djoser + django-social-auth(front: Vue, back: django). When I request to http://127.0.0.1:8000/auth/o/google-oauth2?redirect_uri=http://localhost:8080, url response with client_id=None in authorization_url. Here are my settings and response. AUTHENTICATION_BACKENDS = [ 'fapp.auth_backend.AuthWithEmailAndPasswordOnly', 'social_core.backends.google.GoogleOAuth2', ] DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': [ 'http://localhost:8080', 'http://localhost:8000' ], 'SOCIAL_AUTH_GOOGLE_OAUTH2_CLIENT_ID': '***' } And response "authorization_url": "https://accounts.google.com/o/oauth2/auth?client_id=None&redirect_uri=http://localhost:8080&state=dpcVJ92tDbxvxMvmn4m3wiCOTw5b0Pcx&response_type=code&scope=openid+email+profile" After this response I tried go to authorization_url with changed client_id to SOCIAL_AUTH_GOOGLE_OAUTH2_CLIENT_ID and it's work fine. -
How to filter data on many to many fields and apply ANY and OR operators in Django
I have 3 Models defined in my code Day, AllocationType and EmployeeAllocation. I am trying to solve a problem for following scenarios. Scenario 1: If person A is allocated to project P1 from 01-06-2023 to 30-06-2023 for dyas M,T,W,T,F. If end user try to allocate person A in that date period or days then end user should get a validation error. Person A is allocated. Scenario 2 If person B is allocated to project P2 from 01-06-2023 to 30-06-2023 for days M,W,F. If end user try to allocated person B than end user should able to allocated Person B between 01-06-2023 and 30-06-2023 for days T,T. I am novice in Django and not able to figure out how to write a condition for checking above scenarios. Model Definitions class Day(models.Model): Name = models.CharField(max_length=10) def __str__(self): return self.Name class AllocationType(models.Model): Name = models.CharField(max_length = 100) ColorCode = models.CharField(max_length = 50) def __str__(self): return self.Name class EmployeeAllocation(models.Model): Employee= models.ForeignKey(Employee, null=False, on_delete= MY_PROTECT, related_name='employee_allocation') Project= models.ForeignKey(Project, null=False, on_delete=MY_PROTECT, related_name='employe_allocation_project') AllocationType = models.ForeignKey(AllocationType, null=False, on_delete=MY_PROTECT, related_name="employee_allocation_type") StartDate = models.DateField() EndDate = models.DateField() Days = models.ManyToManyField(Day, null=False, blank=False, related_name='emoloyee_allocation_day') Comments = models.CharField(max_length=200, null=True, blank=True) def get_absolute_url(self): return reverse('employee-allocation-list') def __str__(self): return self.Employee.FirstName