Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updated data don't seem in DRF api response
The updated data doesn't seem in api response. When I add or update some data in admin panel it doesn't affect to api response. To fix it i must write docker-compose restart. How can i fix this problem I supposed that this problem comes from caches issue. Therefore i add cache configuration in settings like this: `CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } }` But it doesn't fix problem -
how to add Comment form inside a post detailed
Is there any way I can add a comment form inside a post's details? I have a view that shows a model object, and I want to allow users to comment on that view. I have tried to use this method, but using that method, a user should leave a post's details and add their comment somewhere else rather than doing it inside a post's details? I have try to do that using the method below, but it gives me an error every time I clicked on submit button: TypeError at /video-play/so-da-shakuwa/ Field 'id' expected a number but got <Video: videos/DJ_AB_-_Masoyiya_Official_Video_9UfStsn.mp4>. views: def play_video(request, slug): play = get_object_or_404(Video, slug=slug) if request.method == 'POST': comments = request.POST['comments'] new_comment = Comment.objects.create( comments=comments, post_id=play ) new_comment.user = request.user new_comment.save() return redirect('Videos') context = { 'play':play } return render(request, 'video/play_video.html', context) template: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="container"> <div class="row"> <div class="col-md-9"> <form action="" method="post"> {% csrf_token %} <div class="input-group"> <textarea name="comments" id="comment" cols="10" class="form-control" placeholder="write your comment"></textarea> <button class="btn btn-primary" type="submit">submit</button> </div> </form> </div> </div> </div> models: class Video(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=70) video = models.FileField(upload_to='videos') created_on = models.DateTimeField(auto_now_add=True) banner = models.ImageField(upload_to='banner') slug = models.SlugField(max_length=100, unique=True) class Comment(models.Model): user … -
Wrong Routing Django
I have a Django project with this layout in baseApp views.py def Home(request): rooms = Room.objects.all() context = {'rooms':rooms} return render(request,'base/home.html',context) def room(request,pk): room = Room.objects.get(id=pk) context = {'room':room} return render(request,'base/room.html',context) def createRoom(request): context= {} return render(request,'base/room_form.html',context) in baseApp urls.py urlpatterns = [ path('', views.Home, name="home page"), path('<pk>/', views.room, name="room"), path('create-room/',views.createRoom, name="create-room"), ] in the base/temp/home.html <h2> <a href="{% url 'create-room' %}">Create Room</a></h2> it supposed to go to to this url : 172.0.0.1:8000/create-room/ " to room_form.html" but it goes to : 172.0.0.1:8000/room/create-room with error Field 'id' expected a number but got 'create-room' I am Expecting it supposed to go to to this url : 172.0.0.1:8000/create-room/ showing room-form.html -
Creating a fully functional website that can be used [closed]
I need help, can someone please help me in finishing creating a website, it is a project I am supposed to be done with by Wednesday, I need help making the links active and functional where after clicking a website it directs you to a webpage with information also, the buttons to be made functional The website should be responsive and active and can be used the website currently looks like this: https://afia.azurewebsites.net/ourhospital/ the github repo link is: https://github.com/abayomiabiodun/AFIA-MBELE.git PLEASE HELP THANKS SOMEONE TO KINDLY HELP IN FINISHING THE WEBSITE -
Django query __in filter on subquery joined over multiple fields without foreignkey
Short: This is the SQL I try to achieve in django: with start_dates as ( select m2.person_id, min(m2.date_current) as start_date from my_table m2 where [...] group by person_id ) select * from my_table m inner join start_dates sd on m.person_id = sd.person_id and m.date_current >= sd.start_date ; Long: There is a table which I need to access twice. The table constists of activities of people. Each people has multiple activities so multiple rows in this table. 1) First access is to find for a set of given filters (like the name of the acitivity and the age of the person) which persons activities fit the filters and per person what is its oldest acitivity fitting the filters. I call that oldest-date "start_date". On SQL this could look like: select m2.person_id, min(m2.date_current) as start_date from my_table m2 where [...] group by person_id With this query I found a sub-set of people with their oldest filtered-activity (so there may be also older activities which do not fit the filters above) Sample A sample would be to find all people ever did taking drugs plus the date when it happened first. 2) Second access is to get for every person found all its … -
login with LinkedIn: Django REST and React.js
I've got problems with authentication with LinkedIn. In my React app, I created LoginButton component following documentation for react-linkedin-login-oauth2. import { useLinkedIn } from 'react-linkedin-login-oauth2'; import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png'; function Login() { const { linkedInLogin } = useLinkedIn({ clientId: '78j5bjwgkxxxxx', redirectUri: 'http://127.0.0.1:8000/dj-rest-auth/linkedin/', onSuccess: (data) => { console.log(data) }, onError: (e) => { console.log(e) } }); return ( <img onClick={linkedInLogin} src={linkedin} /> ); } export default Login That button is kinda working. As far as I'm understanding, 'redirect_URI' should point backend view, it redirects me to http://127.0.0.1:8000/dj-rest-auth/linkedin/ with code and state. But backend doesn't log me in automatically and manually (I'm trying to paste "code" form URL to "code" in form below. Then I'm getting that: My backend should work (I did everything following documentation for dj-rest-auth and allauth) from allauth.socialaccount.providers.linkedin_oauth2.views import LinkedInOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from dj_rest_auth.registration.views import SocialLoginView class LinkedinLogin(SocialLoginView): adapter_class = LinkedInOAuth2Adapter client_class = OAuth2Client callback_url = 'http://127.0.0.1:8000/dj-rest-auth/linkedin/' from django.urls import path from . import views urlpatterns = [ path('accounts/', include('allauth.urls')), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/linkedin/', views.LinkedinLogin.as_view(), name='linkedin_login'), ] Next issue is, after login with button from frontend, I'm getting "user closed the popup" error, I'm not closing or unfocusing anything, in other worlds onError is running, … -
How to deal with Django Cascade deleted objects in django-simple-history?
I have a problem with django-simple-history when I use cascade deletion on objects. I have several tables in my database that inherit from other tables, so I’ve set the deletion to cascade. The problem is that when I want to query Historical Objects generated by django-simple-history, I do have the one in the parent table, but for objects in the children table, that were automatically deleted by Django, I this error : MyApp.models.parentTable_object.DoesNotExist: parentTable_object matching query does not exist. If I understand the problem, django-simple-history tried to create a Historical object for my deleted object but failed because it needed the parent object it inherited and that no longer exists at this point. I can’t do without cascading so I hope it’s possible because django-simple-history has met all my expectations so far. Thanks you for your help My environment: OS: Windows 10 Browser: Firefox Django Simple History Version: 3.1.1 Django Version: 4.0.3 Database Version: django's integrated SqLite3 -
AttributeError: type object 'object' has no attribute 'id'
I am trying to add permissions to my Django Rest Framework Project, but i get an error: AttributeError: type object 'object' has no attribute 'id' My permissions.py file looks like this: from rest_framework import permissions class UpdateOwnProfile(permissions.BasePermission): """Allow users to edit their own profile""" def has_object_permission(self, request, view, obj): """Check user is trying to edit their own profile""" if request.method in permissions.SAFE_METHODS: return True return object.id == request.user.id My views.py class for the UserProfile looks like this: class UserProfileViewSet(viewsets.ModelViewSet): """Handle creating and updating profiles""" serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.objects.all() authentication_classes = ( TokenAuthentication, ) permission_classes = ( permissions.UpdateOwnProfile, ) My serializers.py file: class UserProfileSerializer(serializers.ModelSerializer): """Serializes a user profile object""" class Meta: model = models.UserProfile fields = ("id", "email", "name", "password") extra_kwargs = { "password": { "write_only": True, "style": { "input_type": "password" }, } } def create(self, validated_data): """Create and return a new user""" user = models.UserProfile.objects.create_user( email=validated_data["email"], name=validated_data["name"], password=validated_data["password"], ) return user def update(self, instance, validated_data): """Handle updating user account""" if "password" in validated_data: password = validated_data.pop("password") instance.set_password(password) return super().update(instance, validated_data) The traceback of the error: Traceback (most recent call last): File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 145, in _get_response response = … -
Choice field validation DRF
Hi all I have my model and its serializer, what I discovered when testing is that serializer is saved no matter what I have in my choice field but in Django admin choice field is empty when the data is wrong and when the data is right I can see the correct option so, -> wrong choice data -> saved regardless -> nothing in django admin -> correct choice data -> saved -> correct value in django admin How can I return validation error if I detect that user posted incorrect data? what I was trying out is topic = serializers.ChoiceField(choices=School.topic) and I don't think that iterating over each tuple and searching for a string is correct or efficient code 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) 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}') 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: … -
Can i use django.db.transaction.atomic with ThreadPoolExecutor?
I have a large set of Projects to validate and update with transaction in 1 perform. If 1 project failed it need to rollback all projects. but when i use ThreadPoolExecutor it got stuck with no log ERROR or WARNING even with max_workers=1. from concurrent.futures import ThreadPoolExecutor, wait @transaction.atomic def update_projects() projects = Project.objects.filter(...) items = [(project, auth) for project in projects] with ThreadPoolExecutor(max_workers=MAX_WORKER) as executor: futures = [executor.submit(validate_and_update, *item) for item in items] wait(futures) def validate_and_update(project, auth): # get other data and validate with project. project.save() i tried multiprocessing instead of threading but it got other error like: "no results to fetch" "pop from empty list" pool = multiprocessing.Pool(processes=2) for item in items: pool.apply_async(validate_and_update, *item) # close the pool pool.close() # wait for all tasks to complete pool.join() -
Why is Source Control (VScode) asking to commit every single file on my computer to git?
I am trying to create project using Python and Django, using a virtual environment. This is how I set up the project in terminal: cd MyProject python3 -m venv env source env/bin/activate pip install django django-admin startproject (projectname) When I go to open the file in VSCode, source control scans and prompts to commit every single file on my computer (including files in the trash) to Git, to the point where it says "Too many changes were detected. Only the first 10000 changes will be shown below". Why is this happening? I tried right clicking and doing 'discard changes' but it ended up deleting files. -
issue when using django(daphne) and scrapy together
Im having issues getting my scrapy spider to work with django when using daphne. i noticed that when i use the normal wsgi server ie. without adding daphne to the list of installed apps, everything works fine as expected. but with daphne, my spider gets stuck after initial requests and never gets to parse. i have made a minimalistic reproduction of the issue , and would be very greatful with anyone can explain why this issue occurs and how to go about it resolving it. thanks PS: this is just a reproduction of the issue, as for why i need daphne, my project uses django channels project structue daphne_scrapy/ ├── daphne_scrapy │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── spiders.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── db.sqlite3 └── manage.py settings.py (these were the only changes made to the settings.py file, added daphne and asgi_app) INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] WSGI_APPLICATION = 'daphne_scrapy.wsgi.application' ASGI_APPLICATION = 'daphne_scrapy.asgi.application' spider.py note: i need to do the django setup because my spider needs to made use of django models in the real project im working on. import scrapy from scrapy.crawler import CrawlerProcess … -
Docker python: can't open file 'manage.py': [Errno 2] No such file or directory
I have two questions at once (Main)I'm trying to deploy a Django project on Docker and I get a python error: can't open file '/backend/manage.py': [Errno 2] No such file or directory Can I use env_file instead of environment for Postgres ? Project structure films -backend -config -__init__.py -asgi.py -settings.py -urls.py -wsgi.py -manage.py -venv -.env -docker-compose.yml -Dockerfile -requirements.txt enter image description here Dockerfile FROM python:3.10 COPY requirements.txt /temp/requirements.txt WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN pip install -r /temp/requirements.txt COPY . . docker-compose.yml version: '3.7' services: web: build: . container_name: films command: > sh -c "python manage.py migrate && python manage.py runserver" ports: - "8000:8000" depends_on: - db env_file: - .env db: image: postgres container_name: db_film environment: - POSTGRES_DB=films - POSTGRES_USER=username - POSTGRES_PASSWORD=password -
Getting an error No module named 'learning_logs' when running application in Heroku
I am working on the Django tutorial from Python Crash Course and unable to get the Learning Log application to run from Heroku.I have tried all the possibilities but still not being able to get it to run. Below is the log data : 2023-04-23T23:52:40.244383+00:00 app[web.1]: File "", line 688, in _load_unlocked 2023-04-23T23:52:40.244383+00:00 app[web.1]: File "", line 883, in exec_module 2023-04-23T23:52:40.244384+00:00 app[web.1]: File "", line 241, in _call_with_frames_removed 2023-04-23T23:52:40.244384+00:00 app[web.1]: File "/app/learning_log/learning_log/wsgi.py", line 18, in 2023-04-23T23:52:40.244384+00:00 app[web.1]: application = get_wsgi_application() 2023-04-23T23:52:40.244384+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2023-04-23T23:52:40.244384+00:00 app[web.1]: django.setup(set_prefix=False) 2023-04-23T23:52:40.244385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/init.py", line 24, in setup 2023-04-23T23:52:40.244385+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2023-04-23T23:52:40.244385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate 2023-04-23T23:52:40.244385+00:00 app[web.1]: app_config = AppConfig.create(entry) 2023-04-23T23:52:40.244385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/config.py", line 193, in create 2023-04-23T23:52:40.244386+00:00 app[web.1]: import_module(entry) 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module 2023-04-23T23:52:40.244386+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "", line 1050, in _gcd_import 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "", line 1027, in _find_and_load 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "", line 1004, in _find_and_load_unlocked 2023-04-23T23:52:40.244387+00:00 app[web.1]: ModuleNotFoundError: No module named 'learning_logs' 2023-04-23T23:52:40.244482+00:00 app[web.1]: [2023-04-23 23:52:40 +0000] [7] [INFO] Worker exiting (pid: 7) 2023-04-23T23:52:40.339083+00:00 app[web.1]: [2023-04-23 23:52:40 +0000] [8] [ERROR] Exception in worker process 2023-04-23T23:52:40.339084+00:00 app[web.1]: Traceback (most recent call last): … -
Django daphne: Apps aren't loaded yet
When i try to run daphne -p 8001 messanger.asgi:application I get this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. If i run server without daphne, I get this error: Listen failure: Couldn't listen on 127.0.0.1:8000: [Errno 48] Address already in use. This is my settings .py: INSTALLED_APPS = [ "channels", "chat", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django_extensions', ] ASGI_APPLICATION = "messanger.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get("REDIS_URL", "redis_url")], }, }, } This is my asgi.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "messanger.settings") django_asgi_app = get_asgi_application() django.setup() application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": django_asgi_app, # WebSocket chat handler "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter(chat.routing.websocket_urlpatterns) ) ), }) This is my consumer.py: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = "chat_%s" % self.room_name # Join room group channel_layer = get_channel_layer() async_to_sync(channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] author_id = text_data_json["a"] chat_id = text_data_json["chat"] message_create = Message(content=message, author_id=author_id, chat_id=chat_id) message_create.save() print("message:", message, "author_id:", author_id, "chat_id:", chat_id) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( self.room_group_name, { "type": "chat_message", "message": message, "author_id": author_id, "chat_id": chat_id } ) def chat_message(self, event): message = event["message"] author_id = event["author_id"] author_username = User.objects.get(id=author_id).username chat_id = event["chat_id"] self.send(text_data=json.dumps({ "type": "chat", … -
How do I compare the values gotten from html checkbox to id of same values in database?
I am fairly new to Django and I use the 4.2 version. This is my problem. I am building a blog website, I was trying to add multiple values(tags) for each blog post, from the HTML template checkbox input to my database, which is PostgreSQL. In that database, I already have pre-stored values of items in a Tags table. This table has a ManyToMany relationship with the main Blogpost class. But I am having problems with this particular process. I am trying to add tags for each blogpost created, from the tags already set in the Tags table. The idea is that a user selects the tags they want to include in their blogpost and in the manytomany table, the ids of the tags and the blogpost are set, when the blogpost is saved. I understand that I am to get the id of the values I am trying to add from my database where they exist and include them in the blogpost but I don't exactly know how to do this. This is what my code looks like: models.py class BlogPost(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key='True', editable=False) post_title = models.CharField(max_length=300, blank=True, null=True, verbose_name='Title of blog post') post_image = models.ImageField(upload_to='posts/%Y/%m/%d', … -
comment remonter ce problème : Erreur d'intégrité Échec de la contrainte UNIQUE : account_user.username
j'ai crée mon view de login quand je me connecte il m'affiche cette erreur voila view coresspand -
django Warning 302 in post from UpdateView
"Hello, what I need is to add a record in one model (Historico) and update the status of a record in another model (Factura) in the same form. However, I am getting a 302 error in the console. [23/Apr/2023 18:02:40] "POST /facturas/actualizar/1 HTTP/1.1" 302 0 This is my form: class FormActualizarFactura(forms.ModelForm): comentario = forms.CharField(widget=forms.Textarea) class Meta: model = Factura fields = ('estado', 'etapa', 'email', 'comentario') This is my view: class ActualizarFactura(UpdateView): model = Factura form_class = FormActualizarFactura template_name = 'facturas/fac_actualizar.html' success_url = reverse_lazy('facturas:listaFacturas') def post(self, request, *args, **kwargs): try: if super().post(request, *args, **kwargs): historico = Historico() historico.factura = isinstance(self.object, Factura) and self.object or None historico.estado = self.object.estado historico.user = request.user historico.comentario = request.POST.get('comentario') historico.save() else: # Se produjo un error al actualizar la factura messages.error(request, f'Error al actualizar la factura: {self.object.NFactura}') except Exception as e: # Se produjo un error general messages.error(request, f'Error general: {e}') return redirect('facturas:listaFacturas') Can you help me or should I implement another method to have two separate forms (but validated in a single HTML form) and each one perform its function in a TemplateView?" Update the status of a record in one model and add it to the Historico table, all from the same form. -
How to assertRaises(ValidationError) against Django Rest Framework APIView?
eg. I have my view: class MyView(APIView): def post(...): ... raise ValidationError('blah') And to my test def test_myview(...): factory = APIRequestFactory() request = factory.post('/myview', data=...) with self.assertRaises(ValidationError): MyView.as_view()(request) I get AssertionError: ValidationError not raised I tried to call it and print the result of the call: def test_myview(...): factory = APIRequestFactory() request = factory.post('/myview', data=...) resp = MyView.as_view()(request) print(resp) it's <Response status_code=400, "text/html; charset=utf-8">, so it's kind of correct if I want to test the response code etc, but what should I do if I want to assertRaises instead? -
Cannot access my phpMyAdmin DB - neither any related configuration file
I've been using a phpMyAdmin SQL DB in the past two years, which was pretty transparent to me. I inherited it from a guy that set it up for my team, and I actually got nothing but a username, password, and a Django web project that's linked to that database. Until today, any interaction with that DB was either via Django's ORM, or via the web UI of the phpMyAdmin site. Today, suddenly, for the first time, I got the following error: And that's it. I've been googling this error, and read some stack overflow threads, but they all suggest editing some configuration files in /etc, but again, I have no clue what's that about and how or where do I access those file - all I know is my username and password to the website, and my Django project's ORM queries (I know it's sad, but that's the reality). I'm the only one in the team that uses the DB, so nobody touched nothing for sure. What can I do to fix that, or to start understanding what happened here? Thanks in advance! -
nginx throws Bad Request (400)
I get this error when I attempt to access my site at: http://exhibit.technology **The Webconfs header check tool shows the following. HTTP/1.1 400 Bad Request => Server => nginx/1.14.0 (Ubuntu) Date => Sun, 23 Apr 2023 20:24:50 GMT Content-Type => text/html Connection => close X-Content-Type-Options => nosniff Referrer-Policy => same-origin** The IP address of the above URL is 192.81.211.160. When I enter it directly it works. My site loads. http://192.81.211.160 The Webconfs header check tool shows: HTTP/1.1 200 OK => Server => nginx/1.14.0 (Ubuntu) Date => Sun, 23 Apr 2023 20:23:35 GMT Content-Type => text/html; charset=utf-8 Content-Length => 6857 Connection => close X-Frame-Options => DENY Vary => Cookie X-Content-Type-Options => nosniff Referrer-Policy => same-origin The nginx error log (the lines around the report of the HTTP 400 error) is shown below (I can provide more if needed). I do not see why the IP address access works but the name access does not. Also, I do not know how to infer the problem from the log. Any help appreciated. The DNS and hosting is on Digital Ocean. The app. is written in Django and has Debug=False and ALLOWED_HOSTS populated in settings.py nginx log: 023/04/23 20:42:39 [debug] 13352#13352: *2 http upstream … -
Can you help me with connecting database models in django?
I am making a website with Django that is fed by a database that is refreshed every 3 hours, the problem is that when I want to remove a client from the database, mysql workbench does not let me because the client model is related to notes and user. How can I do so that when a client is deleted, its related classes are automatically deleted? I tried adding " on_delete=models.CASCADE" but it didn't work, also removing the foreign keys but I need to create notes from the clients. can you help me please? :c from django.db import models # Create your models here.from django.db import models from django.contrib.auth.models import User from django.utils import timezone SATISFACCION_CHOICES = ( ('<i class="fas fa-smile fa-2x" style="color:green"></i>', 'Satisfecho'), ('<i class="fas fa-meh fa-2x" style="color:rgb(255, 187, 0)"></i>', 'Intermedio/no atendió'), ('<i class="fas fa-frown fa-2x" style="color:red"></i>', 'Insatisfecho'), ) CAMBIOS_CHOICES = ( ('No hubo cambios', 'No hubo cambios'), ('Hubo cambios', 'Hubo cambios'), ) class Cliente(models.Model): fecha = models.DateTimeField(db_column='Fecha') # Field name made lowercase. vencimiento = models.DateTimeField(db_column='Vencimiento') # Field name made lowercase. saldo = models.FloatField(db_column='Saldo') # Field name made lowercase. comprobante = models.TextField(db_column='Comprobante') # Field name made lowercase. corredor = models.TextField(db_column='Corredor') # Field name made lowercase. grupo = models.TextField(db_column='Grupo') # … -
What can i use to embbed video conferencing in my Django website?
How can I add video conferencing and audio calls to my Django website? I have seen a lot of people talking about agora but I don't have tried it.is it better? -
Django form with dynamic number of items depending on other model
I'm trying to generate a dynamic form for the models below (some fields removed for brevity): class BreakfastOption(CreatedUpdatedByMixin, TimeStampedModel): """Option for breakfast, e.g. white bread, brown bread, tea, coffee""" name = models.CharField(max_length=30, unique=True) BREAKFAST_CATEGORY_CHOICE = ( ('food_week', 'Food during week'), ('food_weekend', 'Food during weekend'), ('drinks', 'Drinks'), ) category = models.CharField(max_length=32, choices=BREAKFAST_CATEGORY_CHOICE, ) class BreakfastOptionChoice(CreatedUpdatedByMixin, TimeStampedModel): """Option for breakfast along with its desired quantity, e.g. 2 slices of white bread and one tea""" breakfast_option = models.ForeignKey(BreakfastOption, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() class BreakfastPreference(CreatedUpdatedByMixin, TimeStampedModel): """Person's choice for breakfast, e.g. 2 slices of white bread and 1 tea, along with comments""" person = models.ForeignKey(Person, on_delete=models.CASCADE) start_date = models.DateField(default=datetime.date.today) # Used for tracking changes choices = models.ManyToManyField(BreakfastOptionChoice) comments = models.TextField(blank=True, null=True) What I'd like to have is a form for BreakfastPreference where the user can see the whole list of available BreakfastOptions (which are about 8) and can enter a quantity for those, along with overall comments. Example form: Person: (prefilled through URL) "White bread slices" quantity: 2 "Brown bread slices" quantity: 0 "Tea" quantity: 1 "Coffee" quantity: 0 Comments: person wants breakfast as early as possible In the above example, rows 2 to 5 are dynamically generated (i.e. there could be 4, but … -
How to override id field Django model
I'm looking for way to override id field mb with models.AutoField or something like that But the main problem that i want to have specific id field For example: I want id field for user to start with number 0 and after that it might contains number or specific letters and this id will look like this : 0123456ABC and all of this should be unique How can i do that? Should i override models.AutoField? models.py class User(models.Model): id = models.AutoFields() user/0123456ABC