Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How is a django date time field saved in a database?
Is the format of a django datetime in a SQLite database converted to text to be an ISO-8601 string? -
Alternative package for mysqlclient
i want to use mysql for database of django project When deploying on cpanel,pip cannot install mysqlcient any one can help me? pip install mysqlclient -
Django - Query on overridden save() method cached or something
I am overriding the default save() method of my model in Django 4. The problem is that I am making queries related to an instance of the model with the overridden save() method, but the queries seem not to be updated during the method execution. Example: class Routine(models.Model): exercises = models.ManyToManyField(Exercise) def save(self, *args, **kwargs): e = self.exercises.all() # 3 exercises returned super().save(*args, **kwargs) # I call to super deleting 1 exercise and adding a new one e = self.exercises.all() # same 3 exercises returned, not updated with the previous save() call Once all the code has been executed the routine.exercises have been properly updated, the problem is that I am not being able to get this query updated during the save() override. -
ModuleNotFoundError: No module named 'crispy_bootstrap5', crispy forms django
I am new to Django and I am trying to learn/use crispy forms to create a registration/login form. however i keep getting a ModuleNotFound error on the 'crispy_bootstrap5'. I am using intellij and have created a new project and I have installed crispy forms and crispy-bootstrap5 (pip install crispy-bootstrap5) screenshot of pip freeze on the virtual environment. I have also updated the settings.py file to include it in the INSTALLED_APPS Screenshot of installed apps in settings.py file. However when i run the server it gives me ModuleNotFoundError: No module named 'crispy_bootstrap5' error. I also tried to install the crispy tailwind but it also gave me the same errors. I have searched the stack overflow forums but I cannot find a solution. Here is my requirements.txt file. Here is my install of crispy bootstrap. -
Celery error when a chord that starts a chain has an error in the group
I have a Chord. After the chord, we chain another task. If one of the tasks in that group of that chord raises an exception, I get a mess of an exception that looks like a bug in celery or django_celery_results. I am using amqp as my task queue and django_celery_results as my results backend. My Tasks: @shared_task(bind=True) def debug_task(self): print(f'Request: debug_task') @shared_task(bind=True) def debug_A(self, i): print(f'Doing A{i}') @shared_task(bind=True) def debug_broke(self): print(f'OH NO') raise Exception("Head Aspload") @shared_task(bind=True) def debug_finisher(self): print(f'OK, We did it all') def launch(): from celery import group g = [debug_A.si(i) for i in range(5)] g.append(debug_broke.si()) r = group(g) | debug_finisher.si() | debug_A.si(-1) r.apply_async() The results when I run this: [2023-03-08 18:19:52,428: INFO/MainProcess] Task topclans.worker.debug_A[c652e39a-8cf5-4ac8-924d-3bce32c190f8] received [2023-03-08 18:19:52,429: WARNING/ForkPoolWorker-1] Doing A0 [2023-03-08 18:19:52,434: INFO/MainProcess] Task topclans.worker.debug_A[c1b8ed9c-a9e0-4960-8b9b-1ecd5b2254a3] received [2023-03-08 18:19:52,436: INFO/MainProcess] Task topclans.worker.debug_A[a4478640-a50a-42a2-a8f0-8e6b84abab90] received [2023-03-08 18:19:52,439: INFO/MainProcess] Task topclans.worker.debug_A[d4c9d249-98dd-4071-ab03-70a350c7d171] received [2023-03-08 18:19:52,439: INFO/MainProcess] Task topclans.worker.debug_A[41c4bdb0-8993-40b0-90bd-2d6c642cb518] received [2023-03-08 18:19:52,462: INFO/ForkPoolWorker-1] Task topclans.worker.debug_A[c652e39a-8cf5-4ac8-924d-3bce32c190f8] succeeded in 0.03368515009060502s: None [2023-03-08 18:19:52,465: INFO/MainProcess] Task topclans.worker.debug_broke[de4d83d9-1f5b-4f02-ad9e-1a3edbedd2f8] received [2023-03-08 18:19:52,466: WARNING/ForkPoolWorker-1] Doing A1 [2023-03-08 18:19:52,481: INFO/ForkPoolWorker-1] Task topclans.worker.debug_A[c1b8ed9c-a9e0-4960-8b9b-1ecd5b2254a3] succeeded in 0.015777542954310775s: None [2023-03-08 18:19:52,483: WARNING/ForkPoolWorker-1] Doing A2 [2023-03-08 18:19:52,500: INFO/ForkPoolWorker-1] Task topclans.worker.debug_A[a4478640-a50a-42a2-a8f0-8e6b84abab90] succeeded in 0.017103158170357347s: None [2023-03-08 18:19:52,501: WARNING/ForkPoolWorker-1] Doing A3 [2023-03-08 18:19:52,515: INFO/ForkPoolWorker-1] Task topclans.worker.debug_A[d4c9d249-98dd-4071-ab03-70a350c7d171] … -
In Wagtail, how to prevent page deletion by editors, or set a minimum number of pages of a kind
The site we developed has 2 type of pages, let's call them... "Static" ones: Home, Contact, About us, the general Catalog page, the general Blog page... "Dynamic" ones: each Collection in the catalog, each Blog entry. We, as developers, provide the final customer with all the structure for the Static ones, meaning they don't have to create them at all. There are many reasons for it but mainly because the site structure counts on these pages to always exist (in a Published state btw, but let's leave that aside). And we let and teach the client's editor to do, among other stuff.. Just edit the existing "static"pages. Create, edit and delete child pages in Catalogue and Blog. But we want to prevent them from deleting any of the other pages. Things might blow up, like, the Home shows some information collected from some of the other sections etc... but mainly because it doesn't make sense in our situation, that is: the only case in which they might delete one of the "static" pages is by accident. If they really want to delete any of these pages, that's a decision design that will involve other people (managers, designers and developers) and … -
How do i fix Reverse for 'viewStudents' with arguments '('',)' not found. 1 pattern(s) tried: ['schedule/(?P<year_id>[0-9]+)\\Z']?
So I am creating auto-generating school schedule app in django. I try to make a list on a page where user can choose different years of classes (For example if someone want to check groups of 4th year) and now i am facing reverse link problem. Here is the code: views.py #adding students def addStudent(request): if request.method == "POST": year = request.POST["year"] faculty = request.POST["faculty"] number = request.POST["group_number"] f = Students(group_year = year, group_title = faculty, group_number = number) f.save() return render(request, "app/AddingForms/addStudents.html") #viewing def viewStudents(request, year_id): arr = Students.objects.filter(group_year = year_id) context = {"year_id":year_id, 'students':arr} return render(request, "app/AddingForms/Studentslist.html", context) models.py class Students(models.Model): group_year = models.IntegerField() group_title = models.CharField(max_length= 10) group_number = models.IntegerField() lessons = models.ManyToManyField(Lesson) def __str__(self): return self.group_title urls.py: #FOR CORE APP app_name = "scheduleapp" urlpatterns = [ path("", views.index, name = 'index'), path("profile/", views.index, name = "profile"), path("about/", views.about, name = "about"), path("add/", views.addingMenu, name = "adding"), path("add-student/", views.addStudent, name = "addStudent"), path("add-lesson/", views.addLesson, name = "addLesson"), path("add-teacher/", views.addTeacher, name = "addTeacher"), path("add-student/<int:year_id>", views.viewStudents, name = "viewStudents") ] html link <ul class="list-group"> <li class="list-group-item active" aria-current="true">Currently Active Groups:</li> <a href = "{% url 'scheduleapp:viewStudents' year_id %}"><li class="list-group-item">1st Year</li></a> </ul> What should I do in order to fix … -
Unabled to edit - Django
I'm creating a simple rest api Right now the result from groups is this: My result from devices right now [ { "id": "8079bf12-bb58-4ea0-a810-58a223d84be7", "name": "Cozinha" } ] my models.py from uuid import uuid4 from django.db import models class Options(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Groups(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Devices(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) options = models.ManyToManyField(Options) group = models.ForeignKey(Groups, on_delete=models.CASCADE, default="") viewsets from rest_framework import viewsets from devices.api import serializers from devices import models class DevicesViewsets(viewsets.ModelViewSet): serializer_class = serializers.DevicesSerializer queryset = models.Devices.objects.all() class OptionsViewsets(viewsets.ModelViewSet): serializer_class = serializers.OptionsSerializer queryset = models.Options.objects.all() class GroupsViewsets(viewsets.ModelViewSet): serializer_class = serializers.GroupsSerializer queryset = models.Groups.objects.all() def perform_create(self, serializer): serializer.save() serializers from rest_framework import serializers from devices import models class OptionsSerializer(serializers.ModelSerializer): class Meta: model = models.Options fields = '__all__' class GroupsSerializer(serializers.ModelSerializer): class Meta: model = models.Groups fields = '__all__' class DevicesSerializer(serializers.ModelSerializer): group = GroupsSerializer() options = OptionsSerializer(many=True) class Meta: model = models.Devices fields = '__all__' def create(self, validated_data): group_data = validated_data.pop('group') options_data = validated_data.pop('options') group, _ = models.Groups.objects.get_or_create(**group_data) options … -
Docker Django staticfiles are not copied to STATIC_ROOT
I am generating static files for my Django app inside a Docker environment. In the logs, the static files are 'copied'. 173 static files copied. However, the static files are not present inside the volume. I print my settings to see this... #settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') print('STATIC_ROOT:', STATICFILES_DIRS) print('FILES:', os.listdir(STATIC_ROOT)) The STATIC_ROOT is empty. STATIC_ROOT: '/usr/src/app/staticfiles' FILES: [] I am using a named volume for the static files. I also execute the collecstatic in here. version: "3.9" services: api: container_name: api build: dockerfile: ./api/Dockerfile command: > sh -c "python manage.py wait_for_database && python manage.py migrate && python manage.py collectstatic --no-input --clear && python manage.py loaddata fixtures/initial.json && gunicorn api.wsgi:application --bind 0.0.0.0:8000" volumes: - application:/usr/src/app - static_volume:/usr/src/app/staticfiles ports: - "8000:8000" env_file: - test-prod.env nginx: container_name: nginx build: dockerfile: ./nginx/Dockerfile volumes: - static_volume:/usr/src/app/staticfiles ports: - "80:80" depends_on: - api restart: always volumes: application: static_volume: In my Dockerfile, I create the directory for the staticfiles and copying the source code to the volume. FROM python:3.9-bullseye WORKDIR /usr/src/app ... ... RUN mkdir /usr/src/app/staticfiles COPY api /usr/src/app I do not get where the static files are copied. I know they're not in the correct directory where I specified STATIC_ROOT since no … -
How to convert Neomodel relationship data into JSON for passing it to Cytoscape.js
I am trying to display Neo4J graph data in my Django template. For querying I am using neomodel, and Cytoscape.js for graph visualization. I am able to convert nodes data in the form of JSON that cytoscape.js requires, but for edges I don't have idea how to do it. This are my Models class Player(StructuredNode): name = StringProperty(required=True) age = IntegerProperty(required=True) height = IntegerProperty(required=True) number = IntegerProperty(required=True) weight = IntegerProperty(required=True) team = RelationshipTo('Team', 'PLAYS_FOR', model=PlayerTeamRel) @property def serialize(self): return { 'data': { 'id': self.id, 'name': self.name, 'age': self.age, 'height': self.height, 'number': self.number, 'weight': self.weight, } } class Team(StructuredNode): name = StringProperty(required=True) players = RelationshipFrom('Player', 'PLAYS_FOR') coach = RelationshipFrom('Coach', 'COACHES') @property def serialize(self): return { 'data': { 'id': self.id, 'name': self.name, 'players': self.players, 'coach': self.coach } } class Coach(StructuredNode): name = StringProperty(required=True) coach = RelationshipTo('Team', 'COACHES') @property def serialize(self): return { 'data': { 'id': self.id, 'name': self.name, 'coach': self.coach } } serialize() method is used get JSON format. That relationship attribute(team) is of type ZeroToOne when I try to print it in the console. I want the JSON in the below format, specifically relationship(edges) data as I am able to serialize and display node data. { data: { id: 'a' } … -
How to rename choose file button in Django administration
I have a problem with the translation of the file selection button (specifically pictures). The entire interface of the admin panel is in Ukrainian, that is, as it should be. But only this button (see photo) is in Russian. How can I translate it into Ukrainian? enter image description here I found answers about how to add a button through changing the admin templates, but I could not find how to rename a specific button. I couldn't find where this button is. -
Pycharm virtual environment only displays html of my project, no CSS
I've managed to set up a virtual environment in Pycharm in order to edit my Django app, and the associated website that it interacts with. The interpreter recognizes Django, and I can make edits to my app, but for some reason it can't seem to find my css files that are in my 'static_files' directory. Here are the instructions in my settings.py file, which Django should be able to access:STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_files') Here are my directories in my project, maybe something is in the wrong place? I've tried adding STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_files'),], and still nothing changes, can't find CSS. Not sure what to do about this, Pycharm seems to run into consistently run into problems that don't exist on my regular server for hosting my site and app. -
How to Create a Profile to an user
im relative new to django, before i only created simple applications that did not require any user stuff, now however i need to create a website with users, for now i created user register, log in and log out, but im struggling to create the profile for the user, should i create an app only for profile ? or maybe put the profile together on the models inside the user app where is the user authentication is, how do i go about the views on this matter ? if someone has a simple example that even a dumb person like me can understand i would appreciate a lot, thanks in advance. For now i tried to create an App for profile and make a model for profile with the OnetoOne Field: user = models.OneToOneField(settings.AUTH_USER_MODEL, null = True, on_delete= models.CASCADE) However im having a trouble where the profile does not start with the user, meaning that the user will have to create the profile and then when he wants to change he needs to go on the other option called edit, which is a bit awkward -
Django - get model instance from a custom field
For a new project I defined a custom field EncryptedField. In this field, I use the methods get_prep_value and from_db_value. In these methods, I have access to the value of the field, so I can encrypt and decrypt it. I also need the value of another field of the model where EncryptedField is used for the encryption/decryption. So is it possible to have access to the instance of the model that calls my custom field EncryptedField. Like that I can have access to the other field value. Or there is an other way to get the other field value in these methods? I tried to use contribute_to_class but it seems to not be adapted to get the model instance. Thanks for your help -
Django Rest Framework different image size for different account tiers 3 build in and possibility to make new
#a link to a thumbnail that's 200px in height - Basic #a link to a thumbnail that's 400px in height - Basic and Intermediate #a link to the originally uploaded image - Basic, Intermediate and Premium class Profile(models.Model): MEMBERSHIP = ( ('BASIC', 'Basic'), ('PREMIUM', 'Premium'), ('ENTERPRISE', 'Enterprise') ) user = models.OneToOneField(User, on_delete=models.CASCADE) membership = models.CharField(max_length=10, choices=MEMBERSHIP, default='BASIC') def __str__(self): return f'{self.user.username} {self.membership} Profile' The only way I know how to do 3 build in tiers are like above. I don't know how to do more memberships with different image sizes that can be added from admin panel. I want to have them as one model and add it as necessary to make a new user. -
JS fetch doesn't exclude from Cart via DRF API
Models: class AbstractProductContainer(AbstractContainer): """ Abstract container for products. """ products = models.ManyToManyField('Product') def toggle(self, product): if self.products.all().contains(product): self.products.remove(product) return False else: self.products.add(product) return True class Cart(AbstractProductContainer): """ Product container for purchasing products. """ pass class Account(AbstractBaseUser, PermissionsMixin): favourite = models.OneToOneField( Favourite, verbose_name=("Favourite products"), on_delete=models.CASCADE, unique=True, default=Favourite.get_new, ) cart = models.OneToOneField( Cart, verbose_name=("Product cart"), on_delete=models.CASCADE, unique=True, default=Cart.get_new, ) DRF Views class ProductViewSet(viewsets.ModelViewSet): serializer_class = serializers.ProductSerializer queryset = Product.objects.filter(sellable=True) @action(methods=['post', 'put', 'delete'], detail=True, permission_classes=[permissions.IsAuthenticated], url_path='toggle-cart', url_name='toggle_cart') def toggle_cart(self, request, *args, **kwargs): product = self.get_object() request.user.cart.toggle(product) return Response() API Test class ProductViewSetTest(TestCase): def testToggle(self): c = self.client u = Account.objects.all()[0] c.login(username="testUser A", password="testPassword123") p = Product.objects.all()[0] url = reverse('api:product-toggle_cart', None, [p.pk]) resp = c.post(url, secure=False) self.assertEqual(resp.status_code, 200, f'Error code: {resp.status_code}') self.assertTrue(u.cart.products.all().contains(p), f"Cart contains: {u.cart.products.all()}, must cantain Product A") resp = c.post(url, secure=False) self.assertFalse(u.cart.products.all().contains(p), f"Cart contains: {u.cart.products.all()}, must be empty") JS Function const removeFromContainer = async btn => { let csrf = new DOMParser().parseFromString(`{% csrf_token %}`, 'text/html').querySelector('input').value; let id = btn.parentElement.parentElement.querySelector('input[name="id"]').value; await fetch(`/api/product/${id}/toggle-cart/`, { method: "PUT", headers: { 'X-CSRFToken': csrf} }) // You are not interested in this part let span = document.querySelector('.in-container span'); span.textContent = Number(span.textContent) - 1; span = document.querySelector('.total span'), span.textContent = (Number(span.textContent) - Number(btn.parentElement.parentElement.querySelector('.price').textContent)).toFixed(2); btn.parentElement.parentElement.remove(); } Product model doesn't matter, … -
Problems with mod-wsgi Windows
I'm new IT and programming; I been struggling to install mod_wsgi with pip Example in cmd: pip install mod_wsgi I'm using Apcache 24 and my PC is windows 10, 64bits My python is 3.7.9 and Django is 3.2.16 Error : Building wheels for collected packages: mod-wsgi Building wheel for mod-wsgi (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi creating build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server creating build\lib.win-amd64-3.7\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management creating build\lib.win-amd64-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.7\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\docs creating build\lib.win-amd64-3.7\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.7\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension error: [WinError 2] El sistema no puede encontrar el archivo especificado [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mod-wsgi Running setup.py clean for mod-wsgi Failed to build mod-wsgi Installing collected packages: mod-wsgi Running setup.py install for mod-wsgi ... error error: subprocess-exited-with-error In advance thank you … -
Replace labels in networkx graph according to translation given by list of tuples
I have a MultiDiGraph, G with the following edges: [('SP', 'LU', 0), ('SP', 'KI', 0), ('LU', 'PC', 0), ('LU', 'LR', 0), ('LU', 'LR', 1), ('PC', 'LI', 0), ('PC', 'HT', 0), ('PC', 'HT', 1), ('LI', 'TE', 0), ('TE', 'GB', 0), ('TE', 'BL', 0), ('GB', 'LR', 0), ('GB', 'ST', 0), ('LR', 'KI', 0), ('LR', 'SP', 0), ('LR', 'PC', 0), ('KI', 'HT', 0), ('KI', 'PC', 0), ('HT', 'SI', 0), ('HT', 'LU', 0), ('HT', 'LU', 1), ('SI', 'BL', 0), ('SI', 'LI', 0), ('BL', 'ST', 0), ('BL', 'TE', 0), ('ST', 'SP', 0)] I would like to translate the labels according to this list of tuples, replacing all LU with 肺 etc. [('LU', '肺', 'Lung'), ('LI', '大腸', 'Large Intestine'), ('ST', '胃', 'Stomach'), ('SP', '脾', 'Spleen'), ('HT', '心', 'Heart'), ('SI', '小腸', 'Small Intestine'), ('BL', '膀胱', 'Bladder'), ('KI', '腎', 'Kidney'), ('PC', '心包', 'Pericardium'), ('TE', '三焦', 'Triple Energizer'), ('GB', '膽', 'Gallbladder'), ('LR', '肝', 'Liver')] A simple function like this converts the list of tuples to what I want: def translate_labels(G): """Translate labels from standard ID to Chinese.""" edges = G.edges convert = [('LU', '肺', 'Lung'), ('LI', '大腸', 'Large Intestine'), ('ST', '胃', 'Stomach'), ('SP', '脾', 'Spleen'), ('HT', '心', 'Heart'), ('SI', '小腸', 'Small Intestine'), ('BL', '膀胱', 'Bladder'), ('KI', '腎', 'Kidney'), ('PC', … -
Multiselect Dropdown List With Checkboxes – multiselect.js how to set placeholder
I am using multiselect.js/css from https://www.cssscript.com/multiselect-dropdown-list-checkboxes-multiselect-js/#google_vignette and creating one select dropdown for Categories. <select name="categoryFilter" id="categoryFilter" aria-label="Category" required multiple > {% for category in categories %} <option value="{{category.id}}">{{ category }}</option> {% endfor %} </select> my JQuery code : document.multiselect('#categoryFilter') .setCheckBoxClick("checkboxAll", function(target, args) { console.log("Checkbox 'Select All' was clicked and got value ", args.checked); }) .setCheckBoxClick("1", function(target, args) { console.log("Checkbox for item with value '1' was clicked and got value ", args.checked); }); document.multiselect('#categoryFilter', { texts: { placeholder: 'Select options', } }); I am not able to set placeholder for my Category option. please suggest where I am wrong. -
Unable to create new objects of a model after referencing a field on another model as FK - django
I have overrided django auth model to a custom one, where I declare the USERNAME_FIELD as phone_number. OTPLog model is intended to keep a log record of the messages sent to the clients. To remove duplication of keeping phone numbers in db, I referenced the phone_number field in OTPLog to phone_number field in User as FK. class User(AbstractUser): phone_number = models.CharField( unique=True, max_length=11, validators=[RegexValidator(regex=consts.PHONE_REGEX_PATTERN)] ) USERNAME_FIELD = 'phone_number' class OTPLog(models.Model): created_at = models.DateTimeField(auto_now_add=True) expiry_date = models.DateTimeField(default=default_otp_duration) phone_number = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='phone_number', on_delete=models.DO_NOTHING, db_index=True) Now making an object of OTPLog with phone_number is not possible any more, as the following exception is risen: otplog = OTPLog.objects.create(phone_number='01145279126') will give ValueError: Cannot assign "'01145279126'": "OTPLog.phone_number" must be a "User" instance. After making an object of User and calling otplog = OTPLog.objects.create(phone_number=user) the object is created successfully, but that is not the way I expect it work. I would simply need a FK constraint, where if a user with a given phone_number does not exist, the otplog object could not be created. How would I resolve the issue? -
Bad Gateway error when using Google Cloud Speech API in a Django application that is running on nginx and waitress
I've been working on a Django project using Google's speech-to-text api. It works fine on my local as well as a standalone application. However, when I deploy it to the production that has nginx working with waitress, it doesn't work and gives Bad Gateway error and the nginx server stops running. This is where it happens. from google.cloud import speech_v1 .... .... client = speech_v1.SpeechClient() Here is my nginx-waitress configuration: #Finally, send all non-media requests to the Django server. location / { proxy_pass http://localhost:8080; #proxy_set_header Host $host; #proxy_set_header X-Forwarded-For $remote_addr; } I tried with that $host and $remote_addr lines, still no luck. Here is the credentials json file that is working fine in both local django server and standalone application. { "type": "service_account", "project_id": "my_project_id", "private_key_id": "my_private_key_id", "private_key": "my_private_key", "client_email": "my_client_email", "client_id": "my_client_id", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/speechtoblog-service%40yt2blog-377413.iam.gserviceaccount.com" } Is there any other configurations that I need to do in the nginx server side? I would highly appreciate your help. -
Django Tailwind theme refresh - won't load
I have successfully installed [django tailwind][1] on my project. The problem is with the preview. As the installation guide advised, i tried 'python manage.py tailwind start', but the usual port http://127.0.0.1/ says: This site can’t be reached. If I start with my usual command of 'python manage.py runserver 127.0.0.1:8080', I can see the site and the new css, but it does not reload the page with reload-worker.js If I try to reload the browser with the button, it just goes into a spinning icon in the tab, never reloads and i have to restart the browser and also the server. So i can't really see the css changes, which is very annoying. What am i missing here? Reload listener seems to be working: HTTP GET /static/django-browser-reload/reload-listener.js 200 [0.01, 127.0.0.1:52032] HTTP GET /static/css/dist/styles.css 200 [0.01, 127.0.0.1:52031] HTTP GET /static/django-browser-reload/reload-worker.js 200 [0.00, 127.0.0.1:52031] -
How make a superuser after signup a user?
This is my model and I just want to All Publisher users become superuser too, but I don't know How to do it?? class User(AbstractUser): email = models.EmailField() is_publisher = models.BooleanField(default=False) and This is my View def signup(response): form = SignUpForm() if response.method == "POST": form = SignUpForm(response.POST) if form.is_valid(): form.save() return redirect("/home") else: form = SignUpForm() return render(response, "registration/signup.html", {"form":form}) -
Django Token on test case return an error 'Authentication credentials were not provided'
I'm loggin inside the TestCase, creating another superuser for the test, but wen i send the token generated for this user, every call I send return me the error: {'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')} I printed my headers: {'Authorization': 'Token 5e4bd809ef42a4f17043a73eec10692382cd78d9'} test.py class CreditCardTestCase(APITestCase): def setUp(self): self.user = User.objects.create_superuser(username='test.case', email='test.case@gmail.com', password='123456') if self.user is not None: try: self.token = Token.objects.get(user=self.user) except: self.token = Token.objects.create(user=self.user) self.headers = {'Authorization': 'Token ' + self.token.key} def test_credit_card_with_invalid_number(self): print(self.headers) response = self.client.put('/api/v1/credit-card', { 'exp_date': '02/2028', 'holder': 'Olivia Johnson', 'number': '1234567891231234', 'cvv': '999' }, **self.headers) print(response.data) self.assertDictEqual({ 'message': 'Invalid Credit Card Number' }, response.data) view.py class CreditCardView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get(self, request, key): credit_card = CreditCardModel.objects.get(pk=key) serializer = CreditCardSerializer(credit_card) private_key = read_keys('private') serializer_data = serializer.data serializer_data['number'] = decrypt_credit_card_number( private_key, credit_card.number) return Response({ 'credit_card': serializer_data }, status=HTTP_200_OK) def put(self, request): try: params = request.data credit_card = CreditCard(params['number']) response = basic_info_verifier(params, credit_card) brand_obj = CreditCardBrand.objects.get( description__icontains=response['brand']) public_key = read_keys('public') print(public_key) encrypted_number = encrypt_credit_card_number( public_key, params['number']) credit_card = CreditCardModel( exp_date=response['expiration_date'], holder=params['holder'], number=encrypted_number, cvv=params['cvv'] if params['cvv'] else '', brand=brand_obj ) credit_card.save() return Response({ 'message': 'Credit card registered with success', 'card_id': credit_card.id }, status=HTTP_201_CREATED) except BrandNotFound: return Response({ 'message': 'Brand Not Found' }, status=HTTP_400_BAD_REQUEST) except … -
Slice on the queryset argument of a Django Prefetch object and got "Cannot filter a query once a slice has been taken."
I did a slice on the queryset argument of a Django Prefetch object and got "Cannot filter a query once a slice has been taken." from django.db.models import Prefetch queryset = SomeModel.objects.filter(some_field=some_value).order_by('id')[:5] prefetch_obj = Prefetch('related_field', queryset=queryset) some_queryset.prefetch_related(prefetch_obj) Is there any way to slice only the first 5 query sets to be cached by prefetch?