Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Raise_exception not working with token base authentication
I'm trying to run my tests on status codes while i'm not providing token on POST request So viewset looking like this: class TopicViewSet(viewsets.ModelViewSet): serializer_class = TopicSerializer permission_classes = (IsOwnerOrReadOnly, ) pagination_class = TopicPagination def get_queryset(self): queryset = Topic.objects.all().select_related( 'owner', ) return queryset Permission class i'm using: class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user Test itself: @pytest.mark.django_db def test_topic_post_method_is_not_allowed_unauthenticated_user(api_client, topics_url): response = api_client.post(topics_url, data={'name': 'hello', 'slug': 'hello'}) assert response.status_code == 401 So all i want is just a simple response like: { "detail": "Authentication credentials were not provided." } But i'm getting html django generated page(screenshot from Postman): -
where should i put the instance in django?
I am modifying a table with stored procedures, I made an instance but I need to call it inside the request, where should I put the instance? def modificartarea(request, id): tarea = get_object_or_404(Tarea, id=id) data = { 'tarea': CrearTareaForm(instance=tarea) } if request.method=="POST": if request.POST.get('nombre') and request.POST.get('descripcion') and request.POST.get('inicio') and request.POST.get('termino') and request.POST.get('repetible') and request.POST.get('activo') and request.POST.get('estado') and request.POST.get('creador') and request.POST.get('tarea_anterior'): tareaupdate= Tarea() tareaupdate.nombre=request.POST.get('nombre') tareaupdate.descripcion=request.POST.get('descripcion') tareaupdate.inicio=request.POST.get('inicio') tareaupdate.termino=request.POST.get('termino') tareaupdate.repetible=request.POST.get('repetible') tareaupdate.activo=request.POST.get('activo') tareaupdate.estado=EstadoTarea.objects.get(pk=(request.POST.get('estado'))) tareaupdate.creador=Empleado.objects.get(rut=(request.POST.get('creador'))) tareaupdate.tarea_anterior=Tarea(pk=(request.POST.get('tarea_anterior'))) cursor=connection.cursor() cursor.execute("call SP_modificar_tarea('"+tareaupdate.nombre+"','"+tareaupdate.descripcion+"', '"+tareaupdate.inicio+"', '"+tareaupdate.termino+"', '"+tareaupdate.repetible+"', '"+tareaupdate.activo+"', '"+str(tareaupdate.estado.id)+"', '"+str(tareaupdate.creador.rut)+"', '"+str(tareaupdate.tarea_anterior.id)+"')") messages.success(request, "La tarea "+tareaupdate.nombre+" se edito correctamente ") return render(request, 'app/modificartarea.html', data) else: return render(request, 'app/modificartarea.html', data) -
Is there a way in the django views to make a css transform?
I apologize I am new to Django and trying to wrap my head around some stuff at the moment. I currently have a page that has a central card that when a button is clicked it flips the card all through CSS. I am now also redirecting the page back to its self in views.py is there a way to have the views redirect to the back of the card not the front. I know I could use java-script to achieve this but was wondering if there was a way with out. View.py: from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views import View from django.contrib.auth.forms import UserCreationForm class login_register(View): def get(self, request): form = UserCreationForm() if "sign-in" in request.GET: username = request.GET.get("username") password = request.GET.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('/admin') else: messages.info(request, 'Login attempt failed.') return redirect('login_register') return render(request, 'index.html', {'form': form}) def post(self, request): if "sign-up" in request.POST: form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request, 'Account has been created succesfully') return redirect('login_register') else: messages.error(request, form.errors) return redirect('login_register') return render(request, 'index.html') HTML … -
how do i create one room for two users in Django channels
so I'm building a listing website that will have a messaging feature, the way i have built the create room function when a user is initiating a conversation is that it's going to collect the current user as a and the listing agent as b then add their IDs, how do i fetch the room for the two users without creating new room again when the agent is the one initiating the conversation. a = str(request.user.id_user) b = str(listing.agent.id_user) room = a[0:13] + "-" + b[0:13] if request.user.is_realtor: if not Room.objects.filter(room_name=room).exists(): Room.objects.create(room_name=room, user1 = request.user, user2 = listing.agent) room = Room.objects.get(room_name=room) else: if not Room.objects.filter(room_name=room).exists(): Room.objects.create(room_name=room, user1 = listing.agent, user2 = request.user) room = Room.objects.get(room_name=room) -
May anyone help me with this problem? Whenever I going to deploy my Django project on heroku.com, I am getting this error. How should I fix it?
(myenv) D:\EventManagementProject\Event_Management_System>git push heroku master Enumerating objects: 352, done. Counting objects: 100% (352/352), done. Delta compression using up to 4 threads Compressing objects: 100% (349/349), done. Writing objects: 100% (352/352), 10.81 MiB | 96.00 KiB/s, done. Total 352 (delta 46), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 1ca3c9649e1582c82164c7773829c2dad2837277 remote: ! remote: ! We have detected that you have triggered a build from source code with version 1ca3c9649e1582c82164c7773829c2dad2837277 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to eventmanagementbydipu. remote: To https://git.heroku.com/eventmanagementbydipu.git ! [remote rejected] master … -
AttributeError: 'RegisterPatientView' object has no attribute 'object'
When ever I am running the project and try to create register the patient or doctor it is showing this error. error and below it is showing error in return HttpResponseRedirect(self.get_success_url()) and if I try to visit login page it is not rendering. Below is my code. views.py class RegisterPatientView(CreateView): """ Provides the ability to register as a Patient. """ model = User form_class = PatientRegistrationForm template_name = 'accounts/patient/register.html' success_url = '/' extra_context = { 'title': 'Register' } def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated: return HttpResponseRedirect(self.get_success_url()) return super().dispatch(self.request, *args, **kwargs) def post(self, request, *args, **kwargs): form = self.form_class(data=request.POST) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get("password1") user.set_password(password) user.save() return redirect('accounts:login') else: return render(request, 'accounts/patient/register.html', {'form': form}) urls.py from django.urls import path from .views import * from appointment.views import * app_name = "accounts" urlpatterns = [ path('patient/register', RegisterPatientView.as_view(), name='patient-register'), path('patient/profile/update/', EditPatientProfileView.as_view(), name='patient-profile-update'), path('doctor/register', RegisterDoctorView.as_view(), name='doctor-register'), path('doctor/profile/update/', EditDoctorProfileView.as_view(), name='doctor-profile-update'), path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout'), ] models.py from accounts.managers import UserManager GENDER_CHOICES = ( ('male', 'Male'), ('female', 'Female')) class User(AbstractUser): username = None role = models.CharField(max_length=12, error_messages={ 'required': "Role must be provided" }) gender = models.CharField(max_length=10, blank=True, null=True, default="") email = models.EmailField(unique=True, blank=False, error_messages={ 'unique': "A user with that email already … -
ModuleNotFoundError: No module named 'django_heroku' even after installation
I set up a Django project in a venv and installed django_heroku in the root folder of my project. When I run 'python manage.py runserver' I get the following error: ../settings.py", line 15, in <module> import django_heroku ModuleNotFoundError: No module named 'django_heroku' This is my requirements.txt, all of these are installed: asgiref==3.5.2 dj-database-url==1.0.0 Django==4.1 django-extensions==3.2.0 django-heroku==0.3.1 gunicorn==20.1.0 psycopg2==2.9.3 psycopg2-binary==2.9.3 python-dateutil==2.8.2 six==1.16.0 sqlparse==0.4.2 whitenoise==6.2.0 Relevant parts of settings.py: import os import django_heroku ... ALLOWED_HOSTS = ['*'] ... STATIC_ROOT = os.path.join(BASE_DIR, 'static') django_heroku.settings(locals()) This is my Procfile: web: gunicorn twatsite.wsgi I have tried changing my Procfile I have checked the venv/lib/site-packages folder and found django_heroku This is the structure of my folders: I have also tried moving the files in Twatter/twatsite/twatsite/.. one folder higher to Twatter/twatsite/.. This did not work and I moved the files back. Any pointers on how to solve or troublehsoot this issue are very welcome. -
Django listview filter related field lookup by date
I want to fetch only the elements of my VM model related to my Hypervisor model based on the current date, but when it finds them I fetch all the elements related to the parent model My Models class Hypervisor(models.Model): name = models.CharField(max_length=200) class VM(models.Model): hypervisor = models.ForeignKey(Hypervisor, on_delete=models.CASCADE) name = models.CharField(max_length=200) cpu = models.CharField(max_length=200) ram = models.CharField(max_length=200) disk = models.CharField(max_length=200) date = models.DateField(null=True) My view class vm(LoginRequiredMixin, ListView): model = Hypervisor template_name = 'vm_list_original.html' ordering = ['name'] def get_queryset(self, *args, **kwargs): return Hypervisor.objects.filter(vm__date=datetime.today().strftime('%Y-%m-%d')).distinct() DDBB sqlite> select * from budget_vm; 280|TC-CLINDE1-HARD001|4|8192|80|2022-09-01|254 281|TC-CLINDE1-HARD001|4|8192|80|2022-09-02|251 My Template <tbody> {% for hyper in object_list %} <tr> <td>{{ hyper.name }}</td> <td> {% for vm in hyper.vm_set.all %} {{ vm.name }} {% endfor %} </td> </tr> {% endfor %} </tbody> The Result -
How may I convert a Many to Many field into JSON Format in Django
I am working with APIs based in REST Architecture. I know Django has a framework to work with this APIs but my homework is do it from scratch. I got an API of a movies site where users can go and search information about a bunch of movies and i am trying to get the data into JSON format from the model Movie which has a Many-to-Many relationship whith the Actor model. I am using Class-based views for this. The code from my models.py and views.py files is nested below: class Actor(models.Model): full_name = models.CharField(max_length=125) role = models.CharField(max_length=125) def __str__(self): return self.full_name class Movie(models.Model): ACTION = 'AC' DRAMA = 'DR' COMEDY = 'CM' SCIENCE_FICTION = 'SF' THRILLER = 'TR' RELIGIOUS = 'RG' GENRE_CHOICES = [ (ACTION, 'Accion'), (DRAMA, 'Drama'), (COMEDY, 'Comedy'), (SCIENCE_FICTION, 'Ciencia Ficcion'), (THRILLER, 'Triler'), (RELIGIOUS, 'Religioso') ] title = models.CharField(max_length=155, blank=False) synopsis = models.TextField(max_length=1000, blank=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, default='', blank=False) tag = models.JSONField(default=dict, blank=True) actors = models.ManyToManyField(Actor, related_name='movies', blank=True) def __str__(self): views.py from django.views import View from django.http.response import JsonResponse from .models import Movie from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt import json class MovieView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def … -
CORS Problem using Django backend with Angular app
I'm using Django REST as a backend for my Angular app. When I make a call to API, I get CORS error. I set up all the CORS configuration in backend side. In settings.py file like: CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = list(default_methods) CORS_ALLOW_HEADERS = list(default_headers) + [ 'Access-Control-Allow-Origin', 'app-version' ] My CORS origin whitelist url is my angular app url and port = https://localhost.com:8002 Also I added corsheaders to INSTALLED APPS and middleware too. Here is my angular request: const url = 'https://local-django-api.com:8004/get-data'; return this.http.get<GetResponseInterface<any>>(`${url}`, { headers: { 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json', }, }); Note: When I try to make an API call using Postman to the same url, it successfully returns a value. Does anyone have an idea about this problem. Thanks in advance for any help. -
Django template does not output datetime
I'm currently on my way of learning some django version is 4.1. I created a simple page which displays all objects inside a database table. Everything works as wanted, but only on my local machine. On the remote machine only pages without any objects/models which contain at least one datetime database field work. So my question is, how do i find out the error. From the "host" I only get the following response if I use any datetime in the template (first part always changes but the "esponse" part is always the same): ��esponse received from application On the local machine I get a correct list of objects with their attributes. I use the same database, so all schema and data is the same. I tried around like 3 hours now and I'm out of ideas. The /admin page also does not work on the webhost only when I visit the localhost it can display output (my guess is also datetime). The ONLY thing I found out by now is, that if I get an object with a datetime field and I use the following code, I can get the view to render the following: obj = Example.objects.first() field_value = … -
xhtml2pdf Django how to make a grid
I am trying to make a pdf with a grid system of 4x5 on each page. The problem is the amount of text on each tile can vary, and what I've noticed when using a table is when there's little text the table's columns will shrink, and when there's too much text the table's columns will expand onto another page. I need the columns to be a fixed size and preferably for the text in columns to shrink to fit. Any ideas? Thanks. -
Django login messages not being delivered as expected
I'm building a Django project and I have a Django app for the login, which I called members. The project is behind the login, so all the URLs redirect to the login page if the user is not logged. If the user inputs an existing user and password, the user can access to the site. This workd OK. If the credentials are wrong, I want the app to send back a message to the user, something like "Your credentials are wrong, try again", but I'm not getting this to work, even if I copied and pasted from the official documentation. My view: def login_user(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) else: messages.error(request, 'Credenciales inválidas.') My base template, which other template extends: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Mapa Primera Infancia: Login</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="{% static 'login.css' %}" /> </head> <body> <div class="msg"> {% for message in messages %} <div class="alert alert-info">{{message}}</div> {% endfor %} </div> {% block content %} {% endblock %} </body> </html> URLs of the members app: urlpatterns = [ path('login_user/', views.login_user, name='login'), ] I don't know … -
How to run Django in a Docker container with a remote PostgreSQL database?
I'm trying to compose a Django container that connects a remote PostgreSQL database with sslmode=require on port 25060. Everything looks fine during the build and the container is running with its peers. However, when I try to migrate the Django models it throws an error : $ docker-compose exec django python manage.py migrate [...] psycopg2.OperationalError: could not connect to server: Connection timed out Is the server running on host "db-postgresql-fra1-controller-do-user-12355871-0.b.db.ondigitalocean.com" (164.92.230.148) and accepting TCP/IP connections on port 25060? I exposed port 25060 in the docker-compose.yml and opened the port in the Docker host with sudo ufw allow 25060 but it keeps saying the same message. In parallel, the container of the Celery worker output is: Waiting for PostgreSQL to become available... Finally, I deactivated the /start command that wait until the database is ready before launching the container, just to check, but it doesn't change. How can I do that ? settings.py DATABASES = { "default": { "ENGINE": 'django.db.backends.postgresql', "NAME": os.environ.get("PSQL_DATABASE"), "USER": os.environ.get("PSQL_USER"), "PASSWORD": os.environ.get("PSQL_PASSWORD"), "HOST": os.environ.get("PSQL_HOST"), "PORT": os.environ.get("PSQL_PORT"), "OPTIONS": {'sslmode': 'require'}, } } .env PSQL_DATABASE=defaultdb PSQL_USER=username PSQL_PASSWORD=password PSQL_HOST=db-postgresql-fra1-controller-do-user.db.ondigitalocean.com PSQL_PORT=25060 docker-compose.yml version: '3.8' services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: controller command: /start volumes: - .:/app ports: - 8011:8000 … -
How to execute code whenever a Stripe session has been paid
I am using Stripe to integrate payments in my e-commerce website and Django as a web framework and I would like to create a custom administration site to manage the store, therefore I want to create a Command model whenever a stripe session has been paid. from .models import Command # I have a Command model class CommandView(views.APIView): def post(self, request, format=None): try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': 'some price id', 'quantity': 1, }, ], mode='payment', success_url='http://localhost:3000/success/{CHECKOUT_SESSION_ID}', cancel_url='http://localhost:3000/store', billing_address_collection='auto', ) if checkout_session['payment_status'] == 'paid': # this will never work because the status in this view is always unpaid return Response({'url': checkout_session['url']}) except Exception as e: return Response({'error': e}) The solution I found is to execute the code in the success_url view but I'm wondering if it's possible to pay and to avoid getting into this url like immediately closing the tab... And maybe my solution of creating a Command model to see details of a command in the administration like color of product... is wrong, can you give some advices. -
Best practice how to send Django app logs to phone
I would like to send my logs from my Django app to my phone. I thought of using slack mail integration to send mails to a dedicated channel but this is only available in the paid slack version. Do you have any ideas with what kind of setup I could achieve this? I don't want to use plain mail since this is too spammy... Discord is also not working well with the webhook since it only pushed all 30 mins. Thanks and all the best -
Django search in one to one field
Wanna do search field by multiple fields from different classes in models. So I have model 1 class Man(models.Model): name = models.CharField(max_length=80) date = models.DateField() And model 2 class Data(models.Model): man = models.OneToOneField( Man, on_delete=models.CASCADE, primary_key=True ) data = models.JSONField(null=False) And I'm trying to create search for field Man.name and then for some fields from JSON blob. My views.py class DataList(generics.ListAPIView): search_fields = ['man.name'] filter_backends = (filters.SearchFilter, ) queryset = Data.objects.all() serializer_class = DataSerializer But when I'm trying to run it I have an error cause it can't access field man.name. So how can I acces it for searching? -
Activate account HTML email in Django
I have a Django App that lets users to register to the system. After the user register via a form receive a email with an activation link. The app works very well, but I want to send the user an HTML mail, not only plain text. I use an template to provide fields to be filled. The problem I face is how to provide the uuid and token in an HTML template in an activate link. I've reading about the send_mail() function, but I don't understand how to use for my purpose. I'm using Django 3.2.8. Show my code: myApp/urls.py path('registro/<str:usuario>', views.registro, name='registro'), path('activate/<uidb64>/<token>/', views.activate, name='activate'), path('esperaconfirmacionregistro/', views.esperaConfirmacionRegistro, name='esperaconfirmacionregistro'), path('confirmacionregistro/<str:status>', views.confirmacionRegistro, name='confirmacionregistro'), acc_active_email.html {% autoescape off %} Saludos, {{user.first_name}} {{user.last_name}}. Por favor da click en el enlace para confirmar tu registro, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} views.py def registro(request,usuario): if request.method == 'POST': form = FormularioAutoRegistro(request.POST, initial={'usuario':usuario}) if form.is_valid(): user = form.save() current_site_info = get_current_site(request) mail_subject = 'Activar cuenta de usuario' message = render_to_string('myApp/acc_active_email.html', { 'user': user, 'domain': current_site_info.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() form = FormularioAutoRegistro(initial={'usuario':''}) return redirect('esperaconfirmacionregistro') else: form = FormularioAutoRegistro(initial={'usuario':usuario}) return render(request, … -
How to change default text in django form?
I would like you to help me change the default text in the forms created by django in the foreign key fields for a custom text. Description of part of the content of Models.py class Historial(models.Model): id_historial=models.AutoField(primary_key=True) id_equipo=models.ForeignKey("Equipo", on_delete=models.CASCADE, verbose_name="Numero Serial de la computadora") id_usuario=models.ForeignKey("Usuario", on_delete=models.CASCADE, verbose_name="Nombre del usuario") fecha_entrega = models.DateField ('Fecha de entrega', auto_now=True , auto_now_add=False) fecha_devolucion = models.DateField('Fecha de devolucion', auto_now=True , auto_now_add=False) qr_code = models.ImageField(upload_to="CodigosQR") recibido=models.BooleanField(default=False) class Meta: verbose_name="Historial" verbose_name_plural="Historial" def __str__(self): return f"{self.id_equipo}" Description of part of the content of Forms.py class HistorialForm(forms.ModelForm): id_equipo = forms.ModelChoiceField(queryset=Equipo.objects.filter(Prestado=False).filter(basura_electronica=False)) id_usuario = forms.ModelChoiceField(queryset=Usuario.objects.filter(allow=True).filter(activo=True)) def __init__(self, *args, **kwargs): super(HistorialForm, self).__init__(*args,**kwargs) self.fields['id_equipo'].widget.attrs['class'] = 'form-control' self.fields['id_equipo'].widget.attrs['placeholder'] = 'Numero serial de la computadora' self.fields['id_usuario'].widget.attrs['class'] = 'form-control' self.fields['id_usuario'].widget.attrs['placeholder'] = 'Nombre del usuario' class Meta: model = Historial fields = [ "id_equipo", "id_usuario", ] labels={ "id_equipo":"Numero serial de la computadora", "id_usuario": "Nombre del usuario", } Description of part of the content of Views.py class ListadoHistorial(ListView): model=Historial form_class=HistorialForm template_name="prestamos/listar_prestamos.html" context_object_name="prestamos" queryset=None def get_queryset(self): return self.model.objects.all() def get_context_data(self, **kwargs): contexto={} contexto["prestamos"]=self.get_queryset() contexto["form"]=self.form_class return contexto def get(self, request, *args,**kwargs): return render(request, self.template_name, self.get_context_data()) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() return redirect("equipo:listar_prestamos") Description of part of the content of prestamo.html {% extends "index.html" %} … -
Django - poll - listing choices based on login user detail
Hy, I created a poll and the page of the poll can be accesed only if the user have a magiclink(made with django-sesame). After open that page using that maginlink i know witch user is, because when link is generated it incorporate the user information and include in that link. The obtions/choices (participanti) of the poll contain name and departemnt (dep_participant)field/value. The users also has and departemnt value (departament). So, the issue/question : in that page o the poll i want to show the name and departemnt for all obtions/choices (participanti) exept the obtions/choices (participanti) with the same department as the login user. I don't know how to make the query in view or forloop in template with that rule. With another words: if the user logged in is from department "hr" i want to show in the template all the choices/options from that poll for all department except those from "hr". Please help me with a solution. Thank you Below find my settings users models.py class UserVot(AbstractUser): departament = models.CharField(max_length=100, null=True, blank=True) rol = models.CharField(max_length=100, null=True, blank=True) poll models.py class Campanie(models.Model): ..... class Participanti(models.Model): campanievot = models.ForeignKey(Campanie, on_delete=models.CASCADE) nume_participant = models.CharField(max_length=200, verbose_name='nume') dep_participant = models.CharField(max_length=200, verbose_name='departament') votes = models.IntegerField(default=0) … -
How to get a list of objects using several model relationships in Django?
I have the following models : class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=16, unique=True, db_index=True) # ... class UserProfile(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) # ... class UserFollow(models.Model): follower = models.ForeignKey(User, related_name="follow_follower", on_delete=models.CASCADE) following = models.ForeignKey(User, related_name="follow_following", on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, editable=False) # ... I want to get the list of UserProfile of a user's followers from a username How can I accomplish this while optimizing database queries ? I use rest framework. -
connection refused django gunicorn nginx
I am getting following error when running search feature on my site (search feature makes api request to my api server): 2022/08/31 21:01:56 [error] 726#726: *23 connect() failed (111: Connection refused) while connecting to upstream, client: 11.111.111.111, server: api.mydomain.com, request: "GET /dividends/IBM/3/5 HTTP/1.1", upstream: "http://127.0.0.1:8001/dividends/IBM/3/5", host: "api.example.com", referrer: "example.com/" The supervisord gunicorn is up, the mongodb is up, and nginx is up I have the following /etc/nginx/sites-available/stocks_backend: upstream stocks_backend { server 127.0.0.1:8001 fail_timeout=4s; } server { server_name api.example.com www.api.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/stocks_backend; } location / { include proxy_params; proxy_pass http://unix:/etc/systemd/system/gunicorn.socket; proxy_ssl_server_name on; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by C> ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by> include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = api.example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name api.example.com www.api.example.com; return 404; # managed by Certbot access_log /root/stocks_backend/log/nginx-access.log; error_log /root/stocks_backend/log/nginx-error.log; } I have tried things from Django gunicorn nginx (111: Connection refused) while connecting to upstream but when I remove http:// from the proxy_pass to … -
Django raises "django.db.utils.IntegrityError: duplicate key value violates unique constraint " after adding new field
After adding another field with parameter unique to my UserProfile model I get the following error when submitting the signup form which requires that field: django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_userprofile_pseudonym_key" DETAIL: Key (pseudonym)=() already exists. I flushed the entire database, deleted all migrations files and migrated everything entirely new and clean from scratch which didn't help. Everything worked well before adding pseudonym as additional field to the model. # html <form hx-post="{% url 'signup' %}" hx-swap="outerHTML" class="form shadow-2xl min-w-[360px] max-w-[360px] p-4 bg-surface rounded-lg text-white" > {% csrf_token %} <!-- form headline --> <h1 class="form-headline text-2xl text-surface-dark text-center mb-2">Create a new account</h1> {% if form.errors %} <div class="error-wrapper mb-2 p-2 bg-error rounded text-white"> <div class="errors text-center">{{ form.errors.pseudonym }}</div> <div class="errors text-center">{{ form.errors.email }}</div> <div class="errors text-center">{{ form.errors.password2 }}</div> </div> {% endif %} <div class="username-wrapper field-wrapper mb-2"> <div class="tag name-tag p-1 text-sm">{{ form.pseudonym.label }}*</div> <div class="input text-woys-purple text-surface-dark">{{ form.pseudonym }}</div> </div> ... </form> # forms.py class SignUpForm(UserCreationForm): pseudonym = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': tailwind_class})) email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'class': tailwind_class})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) class Meta: model = get_user_model() fields = ('email', 'password1', 'password2') # models.py class UserProfile(AbstractBaseUser, PermissionsMixin): # Unique identifier id = models.UUIDField(primary_key=True, … -
No 'Access-Control-Allow-Origin' header is present on the requested resource CORS error only for certain endpoints - React/DRF
I'm getting the following CORS error: Access to fetch at 'https://___backend.herokuapp.com/api/tickets/21/' from origin 'http://___frontend.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I believe all my django-cors-header settings are correct: CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ["https://____frontend.herokuapp.com"] CSRF_TRUSTED_ORIGINS = ["https://____frontend.herokuapp.com"] CORS_ALLOW_HEADERS = DEFAULT_HEADERS #this list includes Access-Control-Allow-Origin CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] The cors headers middleware is on top of the list and it's in installed apps. The weird part is that I'm only getting this error for 2 endpoints even though I'm using the exact same request options on the frontend: const requestOptions = { method: 'GET', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Authorization': `Token ${localStorage.getItem('token')}` } } I'm really confused as to how API calls to other endpoints can work fine but not for these 2. -
Django IIS is giving me a bad gateway error http platform handler
hello i am trying to deploy my Django app on IIS. I am trying to use http platform handler after being told that wfastCGI is deprecated. after changing my config file i tried to run my website on localhost it loads for a long while and gives me a bad gateway error. I am following this tutorial: https://medium.com/@akshay.mewada7/host-flask-and-django-web-application-with-windows-iis-httpplatformhanlder-83e831ce91bc <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <httpPlatform startupTimeLimit="10" startupRetryCount="10" stdoutLogEnabled="true" processPath="C:\Python310\python.exe" arguments="manage.py runserver"> <environmentVariables> <environmentVariable name="foo" value="bar" /> </environmentVariables> </httpPlatform> </system.webServer> <location path="" overrideMode="Deny"> <system.webServer> </system.webServer> </location> <location path="" overrideMode="Allow"> <system.webServer> <handlers> <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> </location> </configuration> is there something i can do to fix this