Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Method Not Allowed (submit form with jQuery in Django)
I want to submit my "contact us" form on my Django website with jQuery. I'm working on development server. The error I receive in the browser and Django shell is: Method Not Allowed (POST): / Method Not Allowed: / [01/May/2023 17:08:34] "POST / HTTP/1.1" 405 0 This is my view: def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def submit_contact_form(request): if is_ajax(request=request): sender_name = request.POST.get('sender_name') sender_email = request.POST.get('sender_email') message_subject = request.POST.get('message_subject') message_body = request.POST.get('message_body') remote_addr = request.META.get('REMOTE_ADDR') remote_host = request.META.get('REMOTE_HOST') context = { 'from': sender_name, 'email': sender_email, 'subject': message_subject, 'message': message_body, 'IP': remote_addr, 'HOST': remote_host, } html_message = render_to_string('homepage/submit.contact.form.html', context) send_mail( f'Contact Form Submission: {message_subject}', f'{message_body}', 'myemail@mydomain.com', ['myemail@mydomain.com', ], html_message=html_message, ) return JsonResponse({}, status=200) else: return redirect('homepage:index') This is the jQuery code stored in a js file: $('#contact-form').submit(function(e) { e.preventDefault(); $('#sent-message').css("display", "none"); $('#loading').css("display", "block"); $.ajax({ type: "POST", url: "/submit-contact-form/", data: { sender_name: $('#name').val(), sender_email: $('#email').val(), message_subject: $('#subject').val(), message_body: $('#message').val(), csrfmiddlewaretoken: csrfToken, datatype: "json", }, success: function(){ $('#loading').css("display", "none"); $('#sent-message').css("display", "block"); $('#contact-form').trigger('reset'); $('#sent-message').delay(3000).fadeOut("slow"); }, error: function(){ $('#loading').css("display", "none"); $('#error-message').css("display", "block"); $('#error-message').append("An error has occured. Please try again later."); } }); }); As far as I can tell, this should work. I'm sure I'm making some stupid mistakes somewhere. Please assist. -
ModuleNotFoundError: No module named after docker-compose build
I am learning and I am following article https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ ,please do not hate me on win10, hopefully will have some $ for smth else later this year, my **Dockerfile **is FROM python:3.9 RUN apt update -y && apt upgrade -y ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/app RUN pip install --upgrade pip COPY ../requirements.txt . RUN pip install -r requirements.txt COPY . .``` **my docker-compose.yml is** version: '3.4' services: web: build: ./ command: python manage.py runserver 0.0.0.0:8000 volumes: - ./:/usr/src/app ports: - 8000:8000 env_file: - ./envs/.env proj tree is \[shelter_v11\]/ ├── envs/.env ├── \[shelter_v11\]/ │ ├── Dockerfile │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── docker-compose.yml ├── requirements.txt └── manage.py The full err message that I get from the docker is > 2023-05-01 15:12:02 Traceback (most recent call last): 2023-05-01 15:12:02 File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv 2023-05-01 15:12:02 self.execute(\*args, \*\*cmd_options) 2023-05-01 15:12:02 File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 74, in execute 2023-05-01 15:12:02 super().execute(\*args, \*\*options) 2023-05-01 15:12:02 File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute 2023-05-01 15:12:02 output = self.handle(\*args, \*\*options) 2023-05-01 15:12:02 File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 81, in handle 2023-05-01 15:12:02 if not settings.DEBUG and not settings.ALLOWED_HOSTS: 2023-05-01 15:12:02 File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 92, in __getattr__ 2023-05-01 15:12:02 self.\_setup(name) … -
Heroku deployment failed yet the build has passed
I am facing this error on Heroku but I don't know the issue : Traceback (most recent call last): File "/app/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? But my requirements.txt file is fine : asgiref==3.6.0 cachetools==5.3.0 certifi==2022.12.7 chardet==3.0.4 charset-normalizer==2.1.1 dj-database-url==1.2.0 Django==3.2 django-bunny-storage==0.1.2 django-countries==7.5.1 django-extensions==3.2.1 django-phone-auth==0.3.1 django-phonenumber-field==7.0.2 django-storages==1.13.2 djangorestframework==3.14.0 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==5.2.2 google-api-core==2.11.0 google-auth==2.17.3 google-cloud-core==2.3.2 google-cloud-storage==2.8.0 google-crc32c==1.5.0 google-resumable-media==2.5.0 googleapis-common-protos==1.59.0 gunicorn==20.1.0 idna==2.10 isort==5.12.0 phonenumbers==8.13.5 Pillow==9.4.0 protobuf==4.22.3 psycopg2-binary==2.9.5 pyasn1==0.5.0 pyasn1-modules==0.3.0 pycountry==22.3.5 PyJWT==1.7.1 python-dateutil==2.8.2 python-dotenv==0.15.0 pytz==2022.7.1 requests==2.28.1 rsa==4.9 six==1.16.0 sqlparse==0.4.3 twilio==6.63.2 typing_extensions==4.4.0 urllib3==1.26.12 uuid==1.30 whitenoise==6.4.0 Here's my Procfile : web: gunicorn pixsar.wsgi --log-file - release: python manage.py migrate and my gitlab.yml : image: name: docker/compose:1.25.4 entrypoint: [""] services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 stages: - deploy-stag deploy-stag: stage: deploy-stag image: ruby:latest before_script: - gem install dpl - wget -qO- https://cli-assets.heroku.com/install-ubuntu.sh | sh script: - dpl --provider=heroku --app=$HEROKU_APP_NAME --api-key=$HEROKU_API_KEY - export HEROKU_API_KEY=$HEROKU_API_KEY … -
Django Q object - Is it possible to put those two queries together even if one depends from another?
Does anyone knows if is possible to put together two Q object queries in only one. Is the first time I need to use it and I am quite lost. First query: vendors = Vendor.objects.filter(Q(is_approved=True, user__is_active=True), user_profile__location__distance_lte=(pnt, D(km=1)) ).annotate(distance=Distance("user_profile__location", pnt)).order_by("distance") Second query: vendors = vendors.filter(Q(vendor_max_delivery_distance__gte=Distance("user_profile__location", pnt))) Can i make a function like a helper so I could call it whenever needs? Is it better to do it in models or contextprocessors? Thank you very much in advance!!! -
One db call when a ManyToManyField relationship is involved
I wish to implement an endpoint which returns a student's subjects, but only if they are not attending a private school. This is how I plan to do it: class Subject(Model): students = model.ManyToManyField() class Student(Model): subjects = model.ManyToManyField() school = model.ForeignKey(School) class School(Model): is_private = model.BooleanField() is_private = Student.objects.select_releated("school").get(student_id).is_private if is_private: raise Http403 return Subject.objects.filter(students__pk=student_id) So I am calling the database twice. Is it possible to do this in django by calling the database once and would it be more efficient to do so? Is there a use case for prefetch_related here? -
How to build an application that has a load balancer and 2 different servers
I have been stuck for a long and decided to ask for a advice I have to built an application that needs to have a load balancer and 2 servers. People want to know how to set up and test this application. My question is that if I run 2 Ec2 instances where I run this app, then do people need to create AWS account to test this application? If so, I would prefer them running this application in local environment where they use 2 servers How can I do this if I am using Django as tech stack? I am new and have been stuck forever but need an advice asap -
Improve performance of qs with multiple filters and exclude statements
I'm writing an app that has "social media capabilities". You can block someone you can wave to someone etc... I have get_queryset for getting all users you didn't see on the app or blocked them with multiple exclude and filter statements that look like this. def get_queryset(self): current_id = self.request.user.id blocked_users = Blocked.objects.filter(user__id=current_id).values('blocked_user') users_taken_action = UserWave.objects.filter(user__id=current_id).values('waved_user') users_not_taken_action = Profile.objects.exclude(user__in=users_taken_action) \ .exclude(user__in=blocked_users).exclude(user__id=current_id) return users_not_taken_action I'm new to optimization and when I see this function I get a feeling that this is not too efficient. Im wrong or is there a better way to handle this? models from django.contrib.auth.models import User class UserWave(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="current_user") waved_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="waved_user") class Blocked(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_thats_blocking") blocked_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blocked_user") class Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) -
Django inheriting from base.html not displaying content on child page
I have a base.html file: {% load static %} {% load custom_tags %} <!DOCTYPE html> <html lang="en"> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> {% comment %} <script type="text/javascript" src="{% static 'dashboardscript.js' %}" defer></script> {% endcomment %} <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script> <title>Codera | Dashboard</title> </head> <body> {% block nav %} <div class="nav-container"> <img src="{% static 'levelstatic/assets/coderalogo.svg' %}" style="margin: 0 auto; width: 80%; margin-bottom: 25px;" alt="CODERA"> <div class="nav-links"> <div class="nav-link nav-active"> <img src="{% static '/dashimages/learn.svg' %}" > <a>LEARN</a> </div> <div class="nav-link"> <img src="{% static '/dashimages/review.svg' %}" > <a>REVIEW</a> </div> <div class="nav-link"> <img src="{% static '/dashimages/progress.svg' %}" > <a>PROGRESS</a> </div> <div class="nav-link"> <img src="{% static '/dashimages/compete.svg' %}" > <a>COMPETE</a> </div> </div> </div> {% endblock %} </body> </html> And I inherit from the base.html file on my dashboard.html file: {% extends "base.html" %} {% load static %} {% block content %} <h1>Hello World!</h1> {% endblock %} However, the <h1> does not show up and instead all that is displayed is the content from the base.html. Could someone possibly help me with this? Why is the <h1> not displaying? -
django-allauth twitter oauth2 Missing valid authorization header
Trying to setup a Django 4.2 app with django-allauth for Twitter using OAuth2. The user gets presented the Twitter Authorize page with the correct logo an account name but after the user clicks on the "Authorize App" button the following message is shown: Details: unknown, Error: Error retrieving access token: b'{"error":"unauthorized_client","error_description":"Missing valid authorization header"}' Any ideas on how to fix the Missing valid authorization header? The package versions are: django 4.2 django-allauth 0.54.0 The settings.py INSTALLED APPS 'allauth.socialaccount.providers.twitter_oauth2', I think settings in the Twitter API are setup properly as this Twitter App is being used successfully for non-Django operations (collect, tweet, etc). I've also double-checked the callback url which is the standard https://domain/accounts/twitter_oauth2/login/callback/ The Twitter docs https://developer.twitter.com/en/docs/authentication/oauth-2-0/user-access-token say for confidential clients (which this is, as it is a simple web app) the header should have Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== I think the error message from Twitter is saying the request does not have the Authorization: Basic info . And I do not know how to set this up. Any help is appreciated. Cheers, Kevin -
HTML code won't load correctly using Django or Flask
Using the exact steps listed here, https://realpython.com/get-started-with-django-1/ and separately following tutorials for flask, I am able to run websites but the website itself always includes extra html codes, instead of simply "Hello, World!" On the website it says: <!doctype html> <h1>Hello, World!</h1> Why? I am saving my html file in a template folder. Using Django what is "translating the below"? Is it render? hello_world.html <!doctype html> <h1>Hello, World!</h1> I tried moving from flask to Django but same problem occurs. -
NoReverseMatch at / Reverse for 'new_url' with no arguments not found. 1 pattern(s) tried: ['new/(?P<spk>[0-9]+)/\\Z']
Can't resolve this error. The idea is that after the form that the user fills out, he goes to the page by PK, where the data that he entered is located views.py # Form class GetUser(FormView): form_class = PersonForm success_url = reverse_lazy('new_url') template_name = 'party/home.html' def post(self, request, *args, **kwargs): if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): cd = form.cleaned_data pc = Person(name=cd.get('name'), last_name=cd.get('last_name')) pc.save() return redirect(self.success_url) # DetailView class UserNew(DetailView): model = Person template_name = 'party/show.html' context_object_name = 'new_user' def get_queryset(self): return Person.objects.filter(pk=self.kwargs['pk']) models.py class Person(models.Model): name = models.CharField(max_length=150, verbose_name='Імʼя') last_name = models.CharField(max_length=150, verbose_name='Прізвище') created_at = models.DateTimeField(auto_now_add=True, verbose_name='created_at') def __str__(self): return f'{self.name} {self.last_name}' def get_absolute_url(self): return reverse('person', kwargs={'pk': self.pk}) class Meta: verbose_name = 'Person' verbose_name_plural = 'Person' ordering = ['-created_at'] html <body> <div> <h1>Привіт</h1> </div> <form action="{% url 'home_url' %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary btn-block">Let`s go</button> </form> </body> I tried rewriting views.py, urls.py, but nothing works -
Unable to get list of selected data in django rest framework
I am trying to list of all selected items from a react application in my django backend.I am not understanding what the received data format is.here is the code: def post(self,request,pk=None): print(request.data) //returns <QueryDict: {'selectbut': ['service1', 'service2', 'service3'], 'selecttext': ['hello guys']}> for i in request.data.get("selectbut"): print(i) //prints only the last data in the value here it prints service3 I want to obtain a list with all the values of selectbut in a list or tuple or iterator here is my react code: import axios from 'axios'; function App() { const submitform=(e)=>{ e.preventDefault() const formdata=new FormData(e.target) for (const i of formdata.values()){ console.log(i) } axios.post("http://127.0.0.1:8000/api/customer/resources/",formdata).then( (response)=>console.log(response) ) } return ( <div className="App"> <form onSubmit={submitform}> <input type='checkbox' name="selectbut" value="service1"/>service1 <input type='checkbox' name="selectbut" value="service2"/>service2 <input type='checkbox' name="selectbut" value="service3"/>service3 <input type='checkbox' name="selectbut" value="service4"/>service4 <input type='text' name="selecttext" />service4 <input type='submit' value="submit"></input> </form> </div> ); } export default App; -
django-tenants postgis with multischema
How can i install postgis extension for 2 shema? shema_1 and shema_2, my commands: CREATE SCHEMA IF NOT EXISTS shema_1 AUTHORIZATION admin; CREATE SCHEMA IF NOT EXISTS shema_2 AUTHORIZATION admin; SET search_path = shema_1, shema_2, public; CREATE EXTENSION IF NOT EXISTS postgis; Its install only for shema_1, and command CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA schema_2; says postgis already exists. In settings.py set ORIGINAL_BACKEND = "django.contrib.gis.db.backends.postgis" -
How to mock Django View methods?
I'm looking for a way I can mock methods in my view including create, update, partial_update. Also, during the process of create, I make external calls where I'm uploading data to cloud, which I want to bypass during tests. So, in addition to mocking create method, I need to mock 2 internal methods: _can_upload_file _upload_file_to_r2 I guess I need to use patch, but not sure how exactly I should use it in this context. Kindly let me know how to achieve this. thanks view class DatasetViewSet(viewsets.ModelViewSet): def create(self, request, format=None): data = request.data.dict() userid = request.user.id serializer = DatasetSerializer(data=request.data) data = self._process_dataset(data, request) serializer = self.get_serializer(data=data) if serializer.is_valid(): serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response({"error": str(serializer.errors)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def _process_dataset(self, data, request): r2_endpoint_public_url = getattr(settings, "R2_ENDPOINT_PUBLIC_URL", None) r2_dataset_folder = getattr(settings, "R2_DATASET_FOLDER", "datasets") size = 0 files = request.FILES.getlist('files') files_info = [] userid = request.user.id for file in files: file_info = {} file_info["filename"] = file.name filesize_check_result = self._can_upload_file(file.size, request.user.id, request.user.customer_id) # this makes external calls if filesize_check_result != "valid": return Response( {"error": filesize_check_result}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) self._upload_file_to_r2(data["label"], file) #this method uploads data to cloud size = size + file.size files_info.append(file_info) data["dataset_details"] = files_info data["size"] = size return data -
Django update_or_create() throws 'already exists'
here is my models.py. Note that for the Capacity model: 'year', 'month', 'employee' are unique_together. class Employee(models.Model): last_name = models.CharField('Nachname', max_length=200) first_name = models.CharField('Vorname', max_length=200) address = models.CharField('Strasse und Hausnummer', max_length=200) zip_code = models.IntegerField('PLZ', default=4000) place = models.CharField('Wohnort', max_length=200) birth_date = models.DateField('Geburtsdatum') entry_date = models.DateField('Startdatum') email = models.CharField(max_length=200) phone = models.CharField(max_length=15, blank=True) ahv_no = models.CharField('AHV Nummer', max_length=200, blank=True) HEBAMME = 'HEBAMME' PFLEGEFACHFRAU = 'PFLEGEFACHFRAU' JOB_CHOICES = [ (HEBAMME, 'Hebamme'), (PFLEGEFACHFRAU, 'Pflegefachfrau'), ] job = models.CharField( max_length=20, choices=JOB_CHOICES, default=HEBAMME, ) workload = models.IntegerField('Pensum', validators=[MaxValueValidator(100)], default=100) active = models.BooleanField(default=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE ) services = models.ManyToManyField( 'customers.Service', default=1, blank=True ) def __str__(self): return self.first_name + ' ' + self.last_name class Capacity(models.Model): employee = models.ForeignKey( Employee, blank=True, null=True, on_delete=models.CASCADE ) number_wobe = models.IntegerField( 'Anzahl Wochenbett', default=0 ) year_choices = ( (2023, '2023'), (2024, '2024'), (2025, '2025'), ) month_choices = ( (1, 'Januar'), (2, 'Februar'), (3, 'März'), (4, 'April'), (5, 'Mai'), (6, 'Juni'), (7, 'Juli'), (8, 'August'), (9, 'September'), (10, 'Oktober'), (11, 'November'), (12, 'Dezember'), ) year = models.IntegerField( 'Jahr', choices=year_choices) month = models.IntegerField( 'Monat', choices=month_choices) class Meta: unique_together = ('year', 'month', 'employee') views.py Note that my filter kwargs are year, month and employee (unique_together) and the item to be … -
i wanna change the default ordering of django api
my code is its ordering by title but has a problem that ordering is default by lexicographic i want to order first with alphabet and after that with integer in the title. my model class: class Product(models.Model): """ A model representing a product with its details, price, and inventory. """ title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) introduction = models.TextField(null=True, blank=True) unit_price = models.DecimalField( max_digits=20, decimal_places=0, validators=[MinValueValidator(1)]) inventory = models.IntegerField(validators=[MinValueValidator(0)]) last_update = models.DateTimeField(auto_now=True) group = models.ForeignKey(Group, on_delete=models.PROTECT, related_name='products') promotions = models.ManyToManyField(Promotion, blank=True) class Meta: ordering = ['group__id', 'title'] def __str__(self) -> str: """ Returns a string representation of the product. """ return self.title my serializer class: class ProductSerializer(serializers.ModelSerializer): images = ProductImageSerializer(many=True, read_only=True) attributes = ProductAttributesSerializer(many=True, read_only=True) class Meta: model = Product fields = ['id', 'title', 'description', 'introduction', 'attributes', 'slug', 'inventory', 'unit_price', 'group', 'images', 'attributes'] my view class: class ProductViewSet(ModelViewSet): queryset = Product.objects.prefetch_related('images', 'attributes').all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter search_fields = ['title', 'description'] ordering_fields = ['unit_price', 'last_update', 'id'] def get_permissions(self): return [IsAdminOrReadOnly()] def get_serializer_context(self): return {'request': self.request} def delete(self, request, pk): product = get_object_or_404(Product, pk=pk) if product.orderitems.count() > 0: return Response({'error': 'Product cannot be deleted because it is associated with an order … -
Sending multiple mails to different recipients from Django Backend
I will do my best to explain the system clearly. Please read through the entire description, and if you have any questions, feel free to ask in the comments. The system I am building allows registered users to send invitations to multiple recipients with a single click of the submit button. In the invitation form, users can enter multiple recipients as a comma-separated string. When they click the submit button, they will immediately receive a notification indicating that the invitations were sent successfully. The backend will then communicate with the user through web sockets to update the status of each recipient's invitation from 'pending' to 'delivered.' (I have learned that a message queue or service worker is required in the backend to complete the email sending task asynchronously.) When the user submits the request, my view will create an invitation instance for each comma-separated recipient and call a function for the email sending task. Please take a look at my code for a better understanding. My views.py file: class InvitationCreateView(generics.CreateAPIView): queryset = Invitation.objects.all() serializer_class = InvitationSerializer def create(self, request, *args, **kwargs): title = request.data.get('title') message = request.data.get('message') recipients = request.data.get('recipients').split(',') invitation_ids = [] for recipient in recipients: recipient = recipient.strip() … -
How can I get only one field from Django Serializer?
Hi I am new to Django and I have a question about serializers. I have a Company Model and a Logo Model that is related to company and I also am using two serializers. The problem is my response comes as an object within an object, but I just want the logo URL. class Company(models.Model): company_name = models.CharField(max_length=200, null=True) class Logo(models.Model): company = models.OneToOneField(Company, on_delete=models.SET_NULL, null=True) user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) class CompanySerializer(serializers.ModelSerializer): logo = LogoSerializer() class Meta: model = Company fields = '__all__' class LogoSerializer(serializers.ModelSerializer): class Meta: model = Logo fields = ['logo'] This is my current return object, the problem is it is nesting logo inside another property called logo. "logo": { "logo": "www.s3bucket.com/url" }, But I am looking to have something like this. "logo": "www.s3bucket.com/url" Thanks in advance for looking at this. Any help is appreciated. -
Get email of the current logged in user in Django and filter with it to get specific statistics
When a doctor is logged in with his email and password, his dashboard shows him some statistics: the number of his patients, the number of his appointments (including past and future appointments) I need to filter by the email of the doctor (to get the appointments/patients of that specific doctor), but I couldn't get a result of any of the three filters. I tried with request.user.id and request.user.username I didn't get anything. Here's my code : views.py: def Home(request): if not request.user.is_active: return redirect('loginpage') g = request.user.groups.all()[0].name if g=='Patient': return render(request, 'homepagePatient.html') elif g=='Doctor': nbrAp=Appointment.objects.all().filter(emailDoctor=request.user).count() nbrPastAp = Appointment.objects.all().filter(emailDoctor=request.user, dateAp__lt=timezone.now()).order_by('-dateAp').count() nbrFutAp = Appointment.objects.all().filter(emailDoctor=request.user, dateAp__gte=timezone.now()).order_by('dateAp').count() mydict={ 'nbrAp':nbrAp, 'nbrPastAp':nbrPastAp, 'nbrFutAp':nbrFutAp, } return render(request, 'homepageDoctor.html', context=mydict) models.py: class Appointment(models.Model): nameDoctor= models.CharField(max_length=50) namePatient= models.CharField(max_length=50) emailDoctor = models.CharField(max_length=60) emailPatient = models.CharField(max_length=60) dateAp = models.DateField() timeAp = models.TimeField() status = models.BooleanField() def __str__(self): return self.namePatient + " will have an appointment with Dr. "+self.nameDoctor class Doctor(models.Model): name= models.CharField(max_length=50) email = models.EmailField(unique=True) password = models.CharField(max_length=16) def __str__(self): return self.name class Patient(models.Model): name = models.CharField(max_length=50) email = models.EmailField(unique=True) password = models.CharField(max_length=16) def __str__(self): return self.name Thank you for your help ! I tried to filter by email to get the number of patients, future/past/total number of appointments of a … -
Django/Wagtail static assets return 404 only when logged in but worked logged out
After upgrading Wagtail and supporting packages, I'm having a strange problem where all the static assets (CSS, JS, fonts, etc..) return a 404 error when logged into the Wagtail admin, ie. the sessionid is valid and set in the browser. However, the are accessible when not logged in (no sessionid cookie). This is true for the public facing site as well as /admin The site is running: Django==4.1.8 wagtail==4.2.2 whitenoise==6.4.0 Python==3.11.2 hosted via heroku. Both production and dev (currently locally) are set using STATICFILES_STORAGE = whitenoise.storage.CompressedManifestStaticFilesStorage and STATIC_URL = "static/". collectstatic has also been run. I've tested this a couple of ways: Using curl No Cookie: curl -I http://127.0.0.1:8000/static/wagtailadmin/js/vendor.610e8c3f47d9.js HTTP/1.1 200 OK Date: Mon, 01 May 2023 06:11:55 GMT Server: WSGIServer/0.2 CPython/3.11.2 Content-Type: text/javascript; charset="utf-8" Cache-Control: max-age=315360000, public, immutable Access-Control-Allow-Origin: * Vary: Accept-Encoding, Cookie Last-Modified: Mon, 01 May 2023 03:59:51 GMT ETag: "644f3937-41103" Content-Length: 266499 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin X-Frame-Options: DENY With Cookie: curl -I http://127.0.0.1:8000/static/wagtailadmin/js/vendor.610e8c3f47d9.js -H "Cookie: csrftoken=fPp7Oq2lR90jkilUiPDRHTOPTsu2lMZm;sessionid=his9jbjahqa3j86hjueeop0lno8pb4a9" HTTP/1.1 404 Not Found Date: Mon, 01 May 2023 06:15:53 GMT Server: WSGIServer/0.2 CPython/3.11.2 Content-Type: text/html; charset=utf-8 Content-Length: 2761 Vary: Cookie Invalid sessionid: à la sessionid=thisisnotvalid returns assets fine Setting full URL for STATIC_URL This is where it gets … -
How to see the relation type in django diagram?
My django model contains many-to-many, foreign-key and other types of relations, yet I'm unable to see that relations in the diagram? ./manage.py graph_models crm \ --layout=dot \ --arrow-shape normal \ --disable-abstract-fields \ --exclude-models BaseModel \ --disable-fields \ -o crm_diagram.png \ What must I do in order to see edge labels showing e.g. One-to-one, many-to-many, one-to-many etc.? pygraphviz is installed -
Django_filter function attribute aren't showing on html page. Object is showing but not the form fields aren't showing
I am using Django_filter for the search operation. I created filters.py to create django filter and then inherited it into views to use it. I created myFilter object and send it to the forms. and if I use {{myFilter}} then it shows the <std_registration.filters.StudentFilters object at 0x000001538F850370> but if I use {{myFilter.form}} then it shows nothing instead of input fields. and it's not showing any error. Code: models.py: from django.db import models # Create your models here. class Student(models.Model): full_name=models.CharField(max_length=200,default="") gender=models.CharField(max_length=20) dob=models.DateField() address=models.TextField() state=models.CharField(max_length=100) image=models.ImageField(null=True,upload_to='std_registration/images/',default='') filters.py import django_filters from .models import Student class StudentFilters(django_filters.FilterSet): model=Student fields='__all__' exclude=['dob', 'gender', 'image'] views.py def display_view(request): student=Student.objects.all().order_by('full_name') myFilter=StudentFilters(request.GET,queryset=student) student=myFilter.qs return render(request,'std_registration/display.html',{'student':student,'myFilter':myFilter}) display.html <div class="row"> <div class="col"> <div class="card card-body" style="color: rgb(223, 255, 248);border: 5px;border-color: black;opacity:0.9;background-color: rgba(53, 53, 53, 0.4);"> <form method="get"> {% csrf_token %} {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> </div> </div> </div> remaining student record showing code.... I am using django_filter for search functionality but instead of showing input fields it showing only search button which is html code. it shows nothing on html page but if I call {{myFilter}} object then it shows text of the objectObject but not showing anything for {{myFilter.form}} -
djangosaml2idp logout throwing ServiceError exception: 'str' object has no attribute 'destination'
I am trying to implement SAML in Django and I have two servers example.com and idp.example.com. On the IDP server, I am using djangosaml2idp. I have been able to implement the login functionality successfully, but the logout is failing on the IDP server. Checking logs on idp.example.com reveals the following issue: ServiceError: 'str' object has no attribute 'destination' {'status': 400} Traceback (most recent call last): File "/home/user/env/lib/python3.9/site-packages/djangosaml2idp/views.py", line 394, in get hinfo = idp_server.apply_binding(binding, resp.__str__(), resp.destination, relay_state, response=True) AttributeError: 'str' object has no attribute 'destination' The logout response is as follows: <?xml version="1.0"?> <ns0:LogoutResponse xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ns1="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" ID="id-ut92BEZeWf4Bymt5n" InResponseTo="id-Jw2GziOSEBcu0T0xF" Version="2.0" IssueInstant="2023-05-01T06:17:12Z" Destination="https://example.com/saml2/ls/post/"><ns1:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://idp.example.com/idp/metadata/</ns1:Issuer><ns2:Signature Id="Signature1"><ns2:SignedInfo><ns2:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ns2:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ns2:Reference URI="#id-ut92BEZeWf4Bymt5n"><ns2:Transforms><ns2:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ns2:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ns2:Transforms><ns2:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ns2:DigestValue>9FfKP4MG0dA+5qyvrQlImjVjTSo=</ns2:DigestValue></ns2:Reference></ns2:SignedInfo><ns2:SignatureValue>nJcmrDFNtsp/ngbHxxltj7A+KFfuDj4iM7myN9ZO0QmfkX1iwIu+i6+0JZ3j58m8 XJuMk3da2+DMiV9hnTTIyz/aMNWZmPvsxL7gUoSSyqtC6QDUcQcqubRjuA5pwJNW b/kG5WxpAwWp5IF/suLCrbP00F+to633bGij/WHvz5EnO93YBcjNcLGJIw3lD+Uw v6uKsT/dh/qV08b84VnBXZYJN7qOz9/YZ4cA4DeApgEn1Yl7PC/sSSoiwXt7mr3Y xVqsJjbxVNBHES+AQUd6/paO6cc6qgoQIsmHOnz9//tyPMgU3xOZ1P5nYvcOjX0K 5baIISRe0IGcQfoib7FJWg==</ns2:SignatureValue><ns2:KeyInfo><ns2:X509Data><ns2:X509Certificate>MIIDGzCCAgOgAwIBAgIUd0aRekN/sTmINbOXE7IragHy5UwwDQYJKoZIhvcNAQELBQAwHTEbMBkGA1UEAwwSaWRwLnJlZ2V4cGxvcmUuY29tMB4XDTIzMDQyMDEwNTkxN1oXDTMzMDQxNzEwNTkxN1owHTEbMBkGA1UEAwwSaWRwLnJlZ2V4cGxvcmUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvzdfnFfUhoTmuRpqBLabIBiWUjRZZ2OwxfJlRki1eyOjmi/lySbCY3/PSQG+KZ47mpxiz2+gTkdj6hTilRGvvCpXsJuHvNWE4w2yS6n8Weps40Rpb9uEihfljhCL2h/ImRakXohPd8x/0FXbozZZLLwudyhEpBFcRjnHoFgxmnVFQyox2+M6tpBOOg6sRTVpcX6eVpfxKPXg+Anp5xWQtyXI0+gGRqB6bTh/BZVLIgCNj/KpoU4f7AjcFVALe6GfakXPlAjPvN1W0GJhIwfDLGtYgNA5cAW5GebBIlDOvZjRFet9+sJ6XiqR5RZnZQHe/NEpS5TrQXLhM3y60x6lrQIDAQABo1MwUTAdBgNVHQ4EFgQUXhIrqxid+CLwzXs6xkjNtAob3mQwHwYDVR0jBBgwFoAUXhIrqxid+CLwzXs6xkjNtAob3mQwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAfrCNy+9OHbGGWKDM6KIzsw+q+rUlq55mKENR/E57UiJn+RauNx2rneXKSVcDuNVD+Gk5nXc3wqzbmuCKxvjF5Sdb/E4uwhI1ohw0tieAqQu5k1juMuCeGVeAMClFtoc681b3nUsKS5LyUJBtO8rxLEMC6MT70JB3xxqVgzCe1Q5VhwUfPiyEAXsH4WfjolPCKogZF1dE/dRA2o3Iw4J/yb+RiMf6cukELogibQfHom0No7YzH0xsSsnFAPaukySJdpuW6DUwRVDTSPaYPDFDadqY2FrlzWPvSy6p2KkcclPWmsj/kjAfXmI4MrXJ7t5WUzQUFw2mfab/rKBSn8i4uA==</ns2:X509Certificate></ns2:X509Data></ns2:KeyInfo></ns2:Signature><ns0:Status><ns0:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></ns0:Status></ns0:LogoutResponse> -
Django Bootstap Modals cant render modal content
im trying to create a simple popup with Django Bootstrap Modal. but I can't get linked content at modals body, and when im trying to access a content its there. im so confused why my linked content cant render at modals body base.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <title>Hello, world!</title> </head> <body> <a href="{% url 'form_view' %}" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Open Form Modal </a> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Form Modal</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <!-- Your form goes here --> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- Bootstrap JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> </body> </html> <!-- Bootstrap CSS --> form_view.html <form method="post" action="{% url 'form_submit' %}"> {% csrf_token %} <div class="form-group"> <label for="{{ form.name.id_for_label }}">Name:</label> {{ form.name }} </div> <div class="form-group"> <label for="{{ form.email.id_for_label }}">Email:</label> {{ form.email }} </div> <div class="form-group"> <label for="{{ form.message.id_for_label }}">Message:</label> {{ form.message }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> views.py from .forms import MyForm from django.shortcuts import render, redirect … -
How to run tasks in django?
I have a Simple algorithm for testing that takes 2 numbers as an input and returns the sum as an output. I usually just write the algorithm in the view but i want to try an execute the algorithm as a task using ThreadPoolExecutor. My example: from concurrent.futures import ThreadPoolExecutor from django.views.decorators.csrf import csrf_exempt executor = ThreadPoolExecutor(max_workers=2) def my_algorithm(a, b): c = a + b return c async def run_algorithm_async(a, b): loop = asyncio.get_event_loop() result = await loop.run_in_executor(executor, my_algorithm, a, b) return result @api_view(['GET']) @csrf_exempt async def processTest(request): a = 1 b = 5 c = await run_algorithm_async(a, b) return Response(c) When i run it i get this error message: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>` What's seems to be the issue? and can i use the method for for more consuming dynamic programming algoritms?