Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate solidjs and django
I want to set up a web application which in backend uses django and in front end uses solidjs. In the development phase how do I integrate solidjs into django? I have a directory called project which contains directory called: back (django-admin startproject back) front (npx degit solidjs/templates/ts front) -
Django rest framework, can not logout
I am using django restframework with TokenAuthentication. So if I go for example to this api call: http://192.168.1.67:8000/api/categories/ Then the user has to login. But when I trigger the logout button. the logout doens't work. And I see in the terminal. That there are two api calls are triggered when the user triggers the logout button: [18/May/2023 10:42:14] "GET /api-auth/logout/?next=/api/categories/ HTTP/1.1" 302 0 [18/May/2023 10:42:15] "GET /api/categories/ HTTP/1.1" 200 32866 So this is the urls.py: urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('logout/',views.LogoutView.as_view(), name='logout'), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views. ManageUserView.as_view(), name='me'), path('login/', obtain_auth_token, name='login' ) ] and settings.py: LOGOUT_REDIRECT_URL = "/" ACCOUNT_LOGOUT_REDIRECT_URL = "/" REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_SCHEMA_CLASS':'drf_spectacular.openapi.AutoSchema', 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'SWAGGER_SETTINGS' : { 'LOGIN_URL': 'rest_framework:login', 'LOGOUT_URL': 'rest_framework:logout' } } and views.py: class AnimalViewSet(viewsets.ModelViewSet): """ This API endpoint allows viewing animal descriptions. - To view a specific animal, append the url with its [/id](/api/animal/1/). - To view all the animals in a category, use [/category/id](/api/categories/1/). """ queryset = Animal.objects.all().order_by('name') serializer_class = AnimalSerializer permission_classes = ( IsAuthenticated, ) class CategoryViewSet(viewsets.ModelViewSet): """ This API endpoint allows for the viewing of animal categories. All categories include their direct subcategories and animals. - To view a specific category, … -
Django annotate SUM of the field from ForeignKey model
I write code on Django and have a problem. I have 2 models. class Statistic(models.Model): campaign_id = models.CharField(max_length=255) adgroup_id = models.CharField(max_length=255) ad_id = models.CharField(max_length=255) campaign_name = models.CharField(max_length=255) adgroup_name = models.CharField(max_length=255) ad_name = models.CharField(max_length=255) date = models.DateField() spend = models.DecimalField(max_digits=10, decimal_places=2, default=0.0, ) impressions = models.IntegerField(default=0) clicks = models.IntegerField(default=0) conversion = models.IntegerField(default=0) class Tonic(models.Model): tiktok_statistic = models.ForeignKey(Statistic, on_delete=models.SET_NULL, null=True, related_name='tonic_statistic') campaign = models.ForeignKey(Campaigns, on_delete=models.CASCADE) date = models.DateField(max_length=256) keyword = models.CharField(max_length=255) clicks = models.IntegerField(default=0) revenueUsd = models.DecimalField(max_digits=9, decimal_places=2, default=0) id_campaign = models.CharField(max_length=255) id_adgroup = models.CharField(max_length=255) id_ad = models.CharField(max_length=255) I created endpoint in Rest Framework. class StatisticViewSet(ReadOnlyModelViewSet): queryset = Statistic.objects.all().values('campaign_name').prefetch_related( 'tonic_statistic').annotate( spend=Sum('spend', distinct=True), impressions=Sum('impressions', distinct=True), clicks=Sum('clicks', distinct=True), conversions=Sum('conversion', distinct=True), revenue_tonic=Sum('tonic_statistic__revenueUsd'), revenue_cross=Sum('cross_statistic__revenue') ).order_by('-spend') When I annotated SUM of spend, impressions, clicks and conversions I got values that are 100-200 times greater than required. For example, the SPEND should be 4,000 and I get 900,000. I think this is because somehow values from related models are pulled up. I can set distinct=True and then the values become close to correct, but in this case some data is lost. Can you tell me how to fix it? Maybe I can set SPEND and other fields only from the current model, something like "self__spend"? -
I am facing issue in Django
When I work in Vs Code, install the extension Django, they stop working html abbreviation, tag short cut and many other property. I try to install extension of HTML and CSS. and try so many things. But, in build property not working. -
javascript/python/otree: Slider Input Check AttributeError
I have been using the code by Vincent van Pelt https://www.accountingexperiments.com/post/sliders/ to implement a slider in my otree experiment and it works nicely besides that if I try to follow his tutorial on the slider input check, I always get the following error: "AttributeError: type object 'Player' has no attribute 'check_keep'". Here is the template/html and javascript code: {{ block content }} <input type="hidden" name="check_keep" value="" id="id_check_keep"/> <p id="feedback_one"><br></p> <input type="range" name="keep" value="None" step="1" style="width:500px" min="0" max="10" id="id_keep" class="form-control"> <script> $(document).ready(function () { $('input[name=keep]').on('input change', function () { $('input[name=keep]').addClass('myclass'); }); $('input[name=keep]').on('input', function() { document.getElementById("feedback_one").innerHTML = `You keep €`+$(this).val()+' for yourself.' + ' The other participant thus receives €' + (10 - ($(this).val())) + '.'; $('#check_keep').val(1); }); }); </script> <style> .myclass::-webkit-slider-thumb { box-shadow: 1px 1px 1px #000000, 0px 0px 1px #007afe; border: 1px solid #000000; height: 21px !important; width: 10px !important; border-radius: 0px !important; background: #ffffff !important; cursor: pointer !important !important; -webkit-appearance: none !important; margin-top: -7px !important; } input[name=keep] { -webkit-appearance: none; margin: 18px 0; width: 100%; } input[name=keep]:focus { outline: none; } input[name=keep]::-webkit-slider-runnable-track { width: 100%; height: 8.4px; cursor: pointer; animate: 0.2s; {#box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;#} background: #007afe; border-radius: 0px; border: 0.0px solid #ffffff; } … -
The empty path didn’t match any of these
I am very new in Django & trying to run my first project. But stucked in the error "The empty path didn’t match any of these." as mentioned above. In my app urls I have the following code from django.urls import path from . import views urlpatterns=[ path('members/',views.members,name='members'), ] And in my project urls I have the following code. from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('members.urls')), path('admin/', admin.site.urls), ] I read a number of answers of this question & found suggestion that not working for me.Seeking help to dig into the error. -
How to connect a IP camera to a Face Recognition attendance web application using Django?
Currently this my first experience on developping a face recognition web application. My application is working fine using the webcom in my laptop. However, I would like to deploy it and I would like to use an IP Camera for face recognition records in each entrance. The question is, how do we connect the IP camera to the production server? Do we need extra code for these IP camera to be connected to the server? Here is my scan code: def scan(request): global last_face known_face_encodings = [] known_face_names = [] profiles = Profile.objects.all() for profile in profiles: person = profile.image image_of_person = face_recognition.load_image_file(f'media/{person}') person_face_encoding = face_recognition.face_encodings(image_of_person)[0] known_face_encodings.append(person_face_encoding) known_face_names.append(f'{person}'[:-4]) video_capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) face_locations = [] face_encodings = [] face_names = [] process_this_frame = True while True: ret, frame = video_capture.read() small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) rgb_small_frame = small_frame[:, :, ::-1] if process_this_frame: face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings( rgb_small_frame, face_locations) face_names = [] for face_encoding in face_encodings: matches = face_recognition.compare_faces( known_face_encodings, face_encoding) name = "N\'existe pas" face_distances = face_recognition.face_distance( known_face_encodings, face_encoding) best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = known_face_names[best_match_index] profile = Profile.objects.get(Q(image__icontains=name)) if profile.present == True: pass else: profile.present = True profile.save() if last_face != name: last_face = … -
Django test suite sees/affects populated production database instead of empty test database
When I run my Django testsuite, a message is printed reporting that a test database is being created before the tests and destroyed after the tests: $ python manage.py test myapp Found 3 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). ... ---------------------------------------------------------------------- Ran 3 tests in 25.560s OK Destroying test database for alias 'default'... It is my understanding that this test database is supposed to be empty. However, my test case code is "seeing" the normal production database containing whatever objects are there prior to starting the test. Also, any changes that my test cases make as part of the test permanently affect the contents of the production database. My tests use Selenium. My test cases are defined as follows: from selenium import webdriver from django.test import LiveServerTestCase class MyTest(LiveServerTestCase): def test_something(self): driver = webdriver.Chrome() # Selenium test cases here # They work fine, but they see the production database rather than the test database # ... I also tried this because I read something that seemed to indicate that I need to derive from unittest.TestCase to use the test database (same result: I see the production database) import unittest from selenium import … -
I am new in Python and Django, need some help.. How to display a simple form data to another page using Django?
In Index.html page I have a simple form for only NAME input with a Submit button, and in the next page Details.html I want to display that NAME. Please suggest how to do that.. I've tried with dictionary, but do not know the process of how to get that form data. -
On python function the dictionary is not return the full value of the key?😢
App view code: def home(request): # return HttpResponse("<h1> This is Home Page </h1>") text1 = "Example Name" temp_dict = {'txt1': text1, 'txt2': 'Your Name'} return render(request, 'Second2_app/index.html', context=temp_dict) index html code: <div> <label for="name">User name</label> <input id="name" type="text" placeholder={{txt1}} name="name" required /> </div> url I define on project file urlpatterns = [ path('admin/', admin.site.urls), path('', include('Second_app.urls')), path('Customers/', include('Second_app.urls')), ] I am expecting why my desire output is not shown in the html file....... -
How to pass id (a variable) from one html page to another html?
I can't figure it out for a few days, please help. I have several html pages, I need to transfer {{ region.id }} from Test page to add_department page. I tried to use {% block action_block %} action="/add_department/{{ region.id }}" {% endblock action_block %}, but only action="/add_department/ without region.id is passed, why is this happening and how to fix it? base.html: {% load static %} <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static '/css/all.css' %}"> <link rel="stylesheet" href="{% static '/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static '/css/main.css' %}"> {% block title %} {% endblock %} </head> <body> <aside> <h3>Menu</h3> <ul> <a href="{% url 'home' %}"><li>Main page</li></a> <a href="{% url 'Test' %}"><li>Test page</li></a> </ul> </aside> <main> {% block page %} {% endblock page %} </main> {% include 'add_department.html' %} <script type="text/javascript" src="{% static '/js/jquery-3.6.4.min.js' %}"></script> <script type="text/javascript" src="{% static '/js/bootstrap.min.js' %}"></script> <script type="text/javascript" src="{% static '/js/script.js' %}"></script> </body> </html> Test.html: {% extends 'base.html' %} <html> <head> {% block title %} <title>Test page</title> {% endblock %} </head> <body> {% block page %} <div class="features"> <nav> <div class="nav nav-tabs justify-content-center" role="tablist"> {% for region in regions %} {% if region.id == 7 %} {% for department in departments %} {% … -
It is necessary to create a django form with the ability to specify a place on the map
I need your help. It is necessary to create a django form with which you can make a mark on the map, give it a name and make a description of this place. How to implement it? I tried googling but didn't find anything useful. -
'Workbook' object has no attribute 'get'
'Workbook' object has no attribute 'get' import openpyxl from openpyxl import Workbook from openpyxl.worksheet.datavalidation import DataValidation from .models import YourModel def generate_excel_with_dropdowns(self): workbook = Workbook() worksheet = workbook.active # Retrieve data from the database using Django ORM or appropriate library data = YourModel.objects.values_list('category', flat=True) # Write data to the worksheet for index, item in enumerate(data, start=1): worksheet.cell(row=index, column=1, value=item) # Create a data validation object for the desired cells dropdown = DataValidation( type="list", formula1='"Sheet1"!$A$1:$A$%d' % len(data), showDropDown=True ) # Add the data validation to the desired cells worksheet.add_data_validation(dropdown) dropdown.add('B1:B10') # Example: Apply dropdown to B1 to B10 range return workbook This is my code when i am trying to run the code i am getting this error ('Workbook' object has no attribute 'get') Thanks in advance -
Configure Nginx static and Django site
im trying to configure nginx to listen so that my subdomain "subdomain.exemple.com" listen to my server site (Django), and that my domain "exemple.com" to run some static site that doesnt require the server, so I tried to configure this way: installed cartbot and generated the ssl certificate `sudo certbot certonly --manual -d example.com -d *.example.com --email your.email@example.com cd /etc/nginx/sites-available/ nano mydjangosite server { listen 80; server_name django.exemple.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name django.exemple.com; ssl_certificate /etc/letsencrypt/live/exemple.com-0001/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/exemple.com-0001/privkey.pem; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }` after did I saved the file and did the nano staticsite with this config server { listen 7080; server_name exemple.com *.exemple.com; location / { root /home/jamelaumn/portfolio; index index.html; } } just to that you know the port 7080 I chose randonly I dont know if it's alright I utilise linux and I dont know much if its okay to choose a random "port number" etc after that I enabled both sites I did sudo ls -l /etc/nginx/sites-enabled/ and I checked that both were enabled, I did nginx -t and it returned that everything was okay I went to my … -
Installing packages with pip on my centos server times out with an warnings and error
This is the error i get. Am using python3 pip install django Collecting django Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out. (read timeout=15)",)': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out. (read timeout=15)",)': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out. (read timeout=15)",)': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out. (read timeout=15)",)': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out. (read timeout=15)",)': /simple/django/ Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django -
Update database partially by patch, django rest framework
I have my CustomUser model which extend AbstractUser class CustomUser(AbstractUser): detail = models.JSONField(default=dict) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pass then now I want to update only detail column. in javascript through patch request like this below. var formData = new FormData(); var status = { fileObj:this.fileObj.id } console.log("syncdata to user table",status); console.log("syncdata for user:",request); formData.append("detail",JSON.stringify(status)); axios.patch( `/api/customusers/3/`,formData,{ } ).then(function (response) { console.log("syncdata customuser is saved:",response); }) .catch(function (response) { console.log("syncdata customuser failed:",response); }); this through <QueryDict: {'detail': ['{"fileObj":19}']}> as request.data in views.py class CustomUserViewSet(viewsets.ModelViewSet): serializer_class = s.CustomUserSerializer queryset = m.CustomUser.objects.all() def update(self,request,*args,**kwargs): print("custom user update") print(request.data) // <QueryDict: {'detail': ['{"fileObj":19}']}> instance = self.get_object() serializer = self.get_serializer(instance,data = request.data) if serializer.is_valid(): self.perform_update(serializer) return Response(serializer.data) else: print(serializer.errors) // check error. However serializer returns the error, {'username': [ErrorDetail(string='This field is required.', code='required')]} What I want to do is just update the detail field only, but it require the username. Where am I wrong? -
Static image not updating on website development and production
Static image not updating on website Edit: FIXED! I forgot I had the old logo in realestatesite/realestatesite/static/img/logo.png and only copied it to realestatesite/static/img once I did python manage.py collectstatic. All I had to do was update it there and run the command again to fix it. Original post: I'm following this guide that shows how to edit the admin panel layout and I added a logo for testing initially, but now I've deleted the old one and added the new; it doesn't update on the site. The old logo is gone, the new one has the exact same name and location. .../templates/admin/base_site.html: {%extends 'admin/base.html'%} {%load static%} {%block branding%} Admin Area {%endblock%} I tried migrating, restarting and clearing cache. -
Can't register a new user react/django/redux
I'm working on registering a user through my frontend. This is my first time using django and redux on a project so I was following a guide on Udemy (pretty lost at this point since it hasn't been really up to date). I keep getting a 400 (Bad Request) error. Hope someone can spot the mistake/what is wrong. user_views.py from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from django.contrib.auth.models import User from base.serializers import ProductSerializer, UserSerializer, UserSerializerWithToken from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from django.contrib.auth.hashers import make_password from rest_framework import status class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) serializer = UserSerializerWithToken(self.user).data for i, j in serializer.items(): data[i] = j return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer @api_view(['POST']) def registerUser(request): data = request.data try: user = User.objects.create( first_name=data['name'], username=data['email'], email=data['email'], password=make_password(data['password']) ) serializer = UserSerializerWithToken(user, many=False) return Response(serializer.data) except: message = {'detail': 'User with this email already exists'} return Response(message, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) @permission_classes([IsAuthenticated]) def getUserProfile(request): user = request.user serializer = UserSerializer(user, many=False) return Response(serializer.data) @api_view(['GET']) @permission_classes([IsAdminUser]) def getUsers(request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) userActions.js import axios from "axios"; import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, USER_LOGOUT, … -
Convert django template object to javascript object
I am using django and frontend javascript react. I am passing accesses to index.html of frontend_react/templates/index.html(react top page) in urls.py from . import views from django.urls import path,include from rest_framework import routers import defapp.views as views urlpatterns = [ path('', views.index, name='index'), in views.py def index(request: HttpRequest) -> HttpResponse: return render(request, 'index.html') settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.normpath(os.path.join(BASE_DIR, 'frontend_react/templates')), os.path.normpath(os.path.join(BASE_DIR, 'defapp/templates')), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] then in index.html convert django template object to javascript object to reuse in other javascript pages. <script> var request = {}; var urls = {}; urls['login'] = "{% url 'login' %}"; urls['loout'] = "{% url 'logout' %}"; {% if request.user.is_authenticated %} request['is_authenticated'] = true; request['user'] = "{{request.user}}"; request['user_id'] = "{{request.user.id}}"; {% else %} request['is_authenticated'] = false; {% endif %} </script> It works. However, I am thinking this might not be good behaivor, or it's not good for security???? It looks a bit clumsy. Is so, is there any best practice to convert the django templates object to javascript object? -
How to synchronize requested data in Django
Assuming I have requested test18 and requested test17 Request test18 to execute first, request test17 to execute later. However, request test18 will complete the data update first, and request test17 to complete the data update later This will cause the result of request test17 to overwrite the result of test18 How can I ensure that the results of test17 do not overwrite the results of test 18 Here is my django code def test17(request): obj = Book.objects.filter(id=1)[0] obj.book_name = 'history' obj.save() return HttpResponse("Success!") def test18(request): obj = Book.objects.filter(id=1)[0] obj.num = 2 # Ensure that test17 is processed first time.sleep(2) obj.save() return HttpResponse("Success!") Source sql data: id:1 book_name match num:0 SQL data after request id:1 book_name match num:2 I hope the data from test18 will not overwrite the data from test17. During the data processing period of test18, test17 completed the data update. How should I handle this situation -
Buttons are not redirecting DJANGO/HTMX/PYTHON
I'm making a website and I'm managing to create accounts without being duplicated or with errors, but when logging off, the button simply doesn't interact, the code runs without errors, it just doesn't do what I'm trying to do, which would beenter image description hereenter image description hereenter image description here to do log off the account and go to the home page enter image description here views enter image description here urls enter image description here login.html enter image description here the buttons who doesnt work tried adding request before user.is_authentication and adding the hx- to custom html attributtes(where i don't know where it is now) -
What is a good way to filter a model and display that as a table in Django?
I have been struggling on finding a simple method for displaying a filtered model on a Django webpage. I am using DataTables for my tables. Here is some code for my view that filters a value and creates a serialized json. I am not sure of another method to do this, but intuitively it made sense to transform the filtered model and send it over to the webpage in the 'context' parameter. def site(request, site_name): filtered = Participant.objects.filter(site_name=site_name).all() serialized = json.loads(serialize('json', filtered)) return render(request, 'site.html', context={'site': site_name, 'filtered': serialized}) Here's my javascript: $(document).ready(function() { $('#my-table').DataTable( { data: JSON.parse(filteredData), lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]], pageLength: 50, responsive: true, processing: true, serverSide: false, bSearchable: true, columns: [ {"data": "some_data"}, ], } ); } ); And here's where I pass the in the filteredData variable in my HTML: <script> filteredData = "{{filtered}}" </script> This does not work as I am not really sure how DataTables handles JSON files. I presume that the solution is simple, but I am quite new to Django. Thank you! -
Django Query to Check if 2 records have the same set of related records
For each Message, I need to generate a query that annotates whether or not there are a conflicts with the annotations. Annotations are conflicting for a message if they don't all have the same text, urgency, and label_set. Note that for label_set I am not looking for the Annotations to reference the exact same objects. I am looking for each annotation to have a set of labels with the same names and topics (e.g. all annotations need 2 labels. One with name = 'A' and topic_id = 5, and one with name = 'B' and topic_id = 7). There can be an arbitrary number of annotations per message and an arbitrary number of labels per annotation. class Message(models.Model): text = models.CharField() class Annotation(models.Model): message = models.ForeignKey(to=Message) user = models.ForeignKey(to=User) text = models.CharField() reviewed = models.BooleanField() urgency = models.ForeignKey(to=Urgency) class Label(models.Model): annotation = models.ForeignKey(to=Message) topic = models.ForeignKey(to=Topic) name = models.CharField() Here is what I have so far. Note that there are other checks for unrelated things in the Case statement hence why I am using strings for the annotation value and not just a boolean for conflict/no conflict. messages = Messages.objects.filter([arbitrary filter]).annotate( status = Case( When(GreaterThan( Count('annotation__urgency', filter=Q(annotation__reviewed=True), distinct=True), Value(1)) | … -
Custom Django form not posting
I am very new to Django and was creating a small project to learn it. I am trying to make a form that users can add text and submit it to create a post, sort of like a tweet. The CSRF_token shows up in the url bar and so does the text that I want posted, meaning it's being sent like a GET request for some reason. Here is my code so far, I've commented out a bunch of things that I was testing or don't work: views.py: def home(response): userInfo = response.user rants = userRants.objects.all() # form = makeRant(response.POST) print("response is type:" + response.method) # print(datetime.datetime.now().strftime("%x")) print(response.POST) if response.method == "POST": # if form.is_valid(): print(response.POST.get(rantTextArea)) inpRantDate = datetime.datetime.now() # t = userRants(username = userInfo.username, rantText = inpRantText, rantDate = inpRantDate) # t.save() # response.user.userRants_set.create(username=userInfo.username, rantText=inpRantText) # print(inpRantText + " " + inpRantDate + " " + userInfo.username) redirect('/') else: return render(response, "main/home.html", {"userInfo":userInfo, "userRants":rants}) home.html (form excerpt): <form type="POST" action="/home/" class="form"> {% csrf_token %} <div class="middleBarContainer"> <div class="rantHeader"> <span class="rantHeaderText"> @{{userInfo.username}} </span> </div> <div class="rantBody"> <textarea name="rantTextArea" id="rantTextArea" class="rantBodyTextInput" style="resize:none" placeholder="Enter RANT..."></textarea> </div> <div class="rantDate"> <button type="submit" class="btn btn-danger" name="submitRant">RANT!</button> </div> </div> </form> models.py (excerpt): class userRants(models.Model): username = … -
pycairo required even if I don't have it in my requirements.txt
I have a pycairo issue when I upload my Django project to Railway (which uses AWS) #11 35.61 Building wheel for pycairo (pyproject.toml): finished with status 'error' #11 35.62 error: subprocess-exited-with-error #11 35.62 #11 35.62 × Building wheel for pycairo (pyproject.toml) did not run successfully. #11 35.62 │ exit code: 1 #11 35.62 ╰─> [15 lines of output] #11 35.62 running bdist_wheel #11 35.62 running build #11 35.62 running build_py #11 35.62 creating build #11 35.62 creating build/lib.linux-x86_64-cpython-38 #11 35.62 creating build/lib.linux-x86_64-cpython-38/cairo #11 35.62 copying cairo/__init__.py -> build/lib.linux-x86_64-cpython-38/cairo #11 35.62 copying cairo/__init__.pyi -> build/lib.linux-x86_64-cpython-38/cairo #11 35.62 copying cairo/py.typed -> build/lib.linux-x86_64-cpython-38/cairo #11 35.62 running build_ext #11 35.62 Package cairo was not found in the pkg-config search path. #11 35.62 Perhaps you should add the directory containing `cairo.pc' #11 35.62 to the PKG_CONFIG_PATH environment variable #11 35.62 No package 'cairo' found #11 35.62 Command '['pkg-config', '--print-errors', '--exists', 'cairo >= 1.15.10']' returned non-zero exit status 1. #11 35.62 [end of output] #11 35.62 #11 35.62 note: This error originates from a subprocess, and is likely not a problem with pip. #11 35.62 ERROR: Failed building wheel for pycairo #11 35.62 Failed to build pycairo #11 35.62 ERROR: Could not build wheels for pycairo, …