Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python-Django project : errors when i run (python manage.py runserver)
`Watching for file changes with StatReloader `Exception in thread django-main-thread:` `Traceback (most recent call last):` File "C:\\Users\\Elite\\AppData\\Local\\Programs\\Python\\Python310\\lib\\threading.py", line 1009, in \_bootstrap_inner` self.run() `File "C:\\Users\\Elite\\AppData\\Local\\Programs\\Python\\Python310\\lib\\threading.py", line 946, in run self.\_target(\*self._args, \*\*self.kwargs) `File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\utils\\autoreload.py", line 64, in wrapper fn(\*args, \*\*kwargs)` File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\core\\management\\commands\\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\utils\\autoreload.py", line 87, in raise_last_exception raise exception\[1\]` `File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\core\\management_init_.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\utils\\autoreload.py", line 64, in wrapper fn(\*args, \*\*kwargs) File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\__init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\apps\\registry.py", line 116, in populate app_config.import_models() File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\apps\\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File AppData\\Local\\Programs\\Python\\Python310\\lib\\importlib\__init_.py", line 126, in import_module` `return \_bootstrap.\_gcd_import(name\[level:\], package, level) File "\<frozen importlib.\_bootstrap\>", line 1050, in \_gcd_import File "\<frozen importlib.\_bootstrap\>", line 1027, in \_find_and_load File "\<frozen importlib.\_bootstrap\>", line 1006, in \_find_and_load_unlocked File "\<frozen importlib.\_bootstrap\>", line 688, in \_load_unlocked File "\<frozen importlib.\_bootstrap_external\>", line 883, in exec_module File "\<frozen importlib.\_bootstrap\>", line 241, in \_call_with_frames_removed` File "C:\\Users\\Elite\\Desktop\\medical_web\\medproject\\main\\models.py", line 81, in \<module\> class UserInfo(models.Model): File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\db\\models\\base.py", line 192, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Users\Elite\Desktop\medical_web\env\lib\site- packages\django\db\models\base.py", line 369, in add_to_class value.contribute_to_class(cls, name) File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\db\\models\\fields\\related.py", line 1917, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model( File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\db\\models\\fields\\related.py", line 1284, in create_many_to_many_intermediary_model "verbose_name": \_("%(from)s-%(to)s relationship") File "C:\\Users\\Elite\\Desktop\\medical_web\\env\\lib\\site- packages\\django\\utils\\functional.py", … -
Stripe Subscription and How to save card details using Stripe Elements for React and Django Backend
I have implemented a stripe subscription flow for frontend and backend as follows : Backend urls : app_name = 'payment' urlpatterns = [ path('subscription', SubscriptionCreate.as_view(), name="create_subscription"), path('stripe_add_payment_method', StripePaymentMethodCreate.as_view()), path('customer', CustomerView.as_view(), name="customerview"), path('secret', SecretView.as_view(), name="secretview"), path('webhook', stripe_webhook, name="stripe_webhook") ] For every created user in the Django, a Free subscription is automatically associated with the user triggered by a post save callback, post_save_customer_create. class Customer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40, default="") product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) stripe_subscription_id = models.CharField(max_length=40, default="") clientsecret = models.CharField(max_length=80, default="") active = models.BooleanField(default=True) @property def get_created_date(self): subscription = stripe.Subscription.retrieve(self.stripe_subscription_id) return datetime.fromtimestamp(subscription.created) @property def get_next_billing_date(self): subscription = stripe.Subscription.retrieve(self.stripe_subscription_id) return datetime.fromtimestamp(subscription.current_period_end) def __str__(self): return self.user.username The following callback created a stripe customer in the Stripe backend and keeps tract of the customer id in Django backend. def post_save_customer_create(sender, instance, created, *args, **kwargs): customer, created = Customer.objects.get_or_create(user=instance) if customer.stripe_customer_id == "": # protection for multiple accounts for same user in Stripe Database stripe_customer_list = stripe.Customer.list(email=customer.user.username) if len(stripe_customer_list.data) > 1: for i in range(0,len(stripe_customer_list.data)): if customer.stripe_customer_id != stripe_customer_list.data[i].id: logging.info(f"Something is very wrong -> Stripe has multiple customers - Deleting : {stripe_customer_list.data[i].id} - {stripe_customer_list.data[i].email}") # stripe.Customer.delete(stripe_customer_list.data[i].id) else: logging.info(f"Something is very wrong -> Stripe had multiple customers - Keeping this user : … -
I have a django project with vue I added ckeditor in django administration but the text in the page appears as normal html
I have a django project with vue I added ckeditor in django administration but the text in the page appears as normal html and when I add {{ | safe }} I'm getting an error in vue js I added {{ | safe }} and I got an error in vue js -
Can't get docker to run a development container for a Django app: python: can't open file '/app/manage.py': [Errno 2] No such file or directory
I managed to get my production version of the app running using an entrypoint and a deploy version of the docker-compose file, however I still need to fix some bugs in the app and for that I wanted to run my application with a mounted volume and a "python manage.py runserver" command so that I can see the changes that I make in the code in real-time, but when I try to do that i get the following error: backend-dev | python: can't open file '/app/manage.py': [Errno 2] No such file or directory backend-dev exited with code 2 I couldn't see the filesystem of the container using the "docker exec" command because it only works on running containers, but I managed to overcome that issue by running those commands: > docker commit 3c3a8e5970e9 backend-dev-debug > docker run -it --rm --entrypoint sh backend-dev-debug and from there I could see that the manage.py file is actually present there. I also searched the internet and I saw that other people have also been coming across this problem, for example here: When run docker-compose up I get python: can't open file 'manage.py': [Errno 2] No such file or directory One user in this thread … -
DataTables - Export data with Ajax without downloading file
I am using the DataTables JS library with Excel/CSV buttons, and it's working great. My next challenge is uploading that Excel/CSV file to another destination/server, without downloading the file locally to the machine. In other words, on button click, I need to send the file to the backend with Ajax so it can then be uploaded as a file to another server. Any ideas? -
cannot import name 'SkipError' from 'rest_framework.exceptions'
I try to use DRF, but it raises this error: raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'SkipError' from 'rest_framework.exceptions' (C:\Users\C.M\.virtualenvs\src-Hn7NFGL7\lib\site-packages\rest_framework\exceptions.py) settings.py INSTALLED_APPS = [ # apps 'accounts', 'home', 'job', 'contact', # django modules "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # third-party 'bootstrap4', 'cities_light', 'django_filters', 'rest_framework', ] urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('accounts.urls', namespace='accounts')), path("admin/", admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('jobs/', include('job.urls', namespace='jobs')), path('contact/', include('contact.urls', namespace='contact')) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) How can I solve the error? I use Django 4.1 and DRF 3.14.0 -
What is the correct way to implement authentication via email accounts (using given email addresses)?
I am currently developing a website for my school and am trying to implement authentication using email accounts. I have a database of emails that can log into the website. So, there will be no sign-ups (only sign-ins). The question arises, because I do not want to use a separate password for the website (a multitude of reasons, listed below). Thus, the intended flow would include users signing-in with email accounts. Although I am seeking a general answer, here are some specifics: The email service provider (ESP) is Google, but the domain (@something.com) is different. I am using Django+postgres There are roughly 100 emails, so the project isn't big As a further note, since the ESP is Google, I will be using Google Identity Services (GIS) APIs. Of course, the most straightforward way of implementing this would be just to let the users sign-in using the GIS, and then retrieve the email address used to check whether it is in the database. This very well might be the best way of doing this, but it seems a tiny bit clunky - since I already know the email addresses that the users will use. The preferred flow would be to check … -
Getting "S3 Transfer Acceleration is not configured on this bucket" error when using django-storages
In a Django project that uses django-storages and is configured with AWS credentials, I am getting the following error when uploading a file (i.e. saving a model that has a models.FileField field) An error occurred (InvalidRequest) when calling the PutObject operation: S3 Transfer Acceleration is not configured on this bucket I triple-checked the AWS credentials -- they even work on another computer with the same codebase, but not on my machine. (I provide the solution below) -
How to save image to binary format in python?
guys! I am trying to convert image to binary using python, but something is not working properly. Here is my code: def binarize_image(filename): filename = MEDIA_ROOT + "\\" + filename img = cv2.imread(filename) greyscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) binary_img = cv2.threshold(greyscale_img, 127, 64, cv2.THRESH_BINARY,) resized_name = f"binary_{filename[:len(filename) - 4]}.png" cv2.imwrite(resized_name, binary_img) return resized_name It crashes on the moment of writing an image. Here is the traceback: Traceback (most recent call last): File "D:\Python\proj\venv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "D:\Python\proj\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\proj\src\core\views.py", line 48, in create_binary_image binarize_image(url) File "D:\Python\proj\src\core\utils\image_binarize.py", line 17, in binarize_image cv2.imwrite(resized_name, binary_img) cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'imwrite' > Overload resolution failed: > - img is not a numerical tuple > - Expected Ptr<cv::UMat> for argument 'img' Any ideas on what am I doing wrong? I will be very grateful for anny suggestions! -
Object of type User is not JSON serialiable
I'm trying to create a sign up method for users. This is what the user model looks like: class User(AbstractBaseUser): name = models.CharField(max_length=128, blank=False) created_at = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(blank=True,default=False, verbose_name="Is admin") designation = models.CharField(max_length=90, blank=True) email = models.EmailField(max_length=160, blank=False, unique=True) password = models.TextField(blank=False) USERNAME_FIELD = "email" def __str__(self): return self.name + " " + self.email This is what the serializer looks like: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "name", "designation", "is_admin", "email", "password"] extra_kwargs = { 'password': {'write_only': True} } #creates user after hashing #and salting password def create(self, validated_data): user = User.objects.create( name=validated_data.get('name'), email=validated_data.get('email'), password=make_password(password=validated_data.get('password'), salt=get_random_string(length=32)) ) return user The view class AuthViewset(viewsets.ViewSet): def signUp(self, request, **kwargs): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) is_new = True user = User.objects.filter(email=request.data['email']).first() if user is not None: #user exists is_new = False else: #create user user = serializer.create(serializer.validated_data) if is_new: return Response({ "user": user, "message": "Created new user" }, status=status.HTTP_201_CREATED) else: return Response({ "message": "User already exists" }, status=status.HTTP_409_CONFLICT) I've overridden the create method to allow for salting of a hashed password. I want my view method to get the created user, so I return the user object from the create method. But it throws an error saying Object … -
Django DRF Admin Panel Test Images Uploader Api project Problem with Post method
Im try to test my admin panel with additional options in my api app Im just started to test simply stuff like login and creating Images model and then checking its in the Django panel admin in this way i dont have any issues but when i want to make a post with url and data and then get created data my query set or response.get is empty Could you help me where is my bad? test_admin.py from django.test import Client from django.urls import reverse from django.contrib.auth import get_user_model from django.core.files.uploadedfile import SimpleUploadedFile from PIL import Image from io import BytesIO from api.models import Images, UserProfile from django.urls import reverse from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model import time from api.celery import app from time import timezone from api.admin import ImagesAdmin from django.contrib.auth.hashers import make_password class ImagesAdminTests(APITestCase): def setUp(self): app.conf.update(CELERY_ALWAYS_EAGER=True) self.client = APIClient() self.superuser = get_user_model().objects.create_superuser( username="testuser", email="testuser@example.com", password=make_password("Haslo1234"), ) self.user_profile = UserProfile.objects.create( user=self.superuser, account_type=UserProfile.ENTERPRISE ) self.image_data = BytesIO() self.image = Image.new("RGB", (900, 900)) self.image.save(self.image_data, format="JPEG") self.image_data.seek(0) self.image_to_upload = SimpleUploadedFile( "test_image.jpg", self.image_data.getvalue(), content_type="image/jpeg" ) self.data = { "title": "Test Image", "slug": "test-image", "image": self.image_to_upload, "author": self.superuser, } self.client.force_login(user=self.superuser) def test_login(self): response = self.client.get(reverse("admin:index")) self.assertEqual(response.status_code, 200) self.assertTrue(self.superuser.is_authenticated) self.assertTrue(self.superuser.is_staff) def … -
Django: I get this error: " AttributeError: 'bool' object has no attribute 'startswith' " when I try migrate in django
I get this error: " AttributeError: 'bool' object has no attribute 'startswith' " when I try migrate in django This is my code: from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import User # Create your models here. class Category(models.Model): slug = models.SlugField() title = models.CharField(max_length=255, db_index=True) class MenuItem(models.Model): title = models.CharField(max_length=255, db_index=True) price = models.DecimalField(max_digits=6, decimal_places=2, db_index=True) featured = models.BooleanField(db_index=True, default=False) category = models.ForeignKey(Category, on_delete=models.PROTECT) class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) menuitem = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.SmallIntegerField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) price = models.DecimalField(max_digits=6, decimal_places=2) class Meta: unique_together = ('menuitem', 'user') class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) delivery_crew = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='delivery_crew', null=True) status = models.BooleanField(db_index=True, default=False) total = models.DecimalField(max_digits=6, decimal_places=2) date = models.DateField(db_column=True) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) menuitem = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.SmallIntegerField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) price = models.DecimalField(max_digits=6, decimal_places=2) class Meta: unique_together = ('order', 'menuitem') I have tried deleting the old migrations and running it again but it didn't work -
Logic inside Django serializer
I have a Django serializer implementation that has a field which contains a list as part of a JWT authentication process. For example: class MySerializer(serializers.ModelSerializer): class Meta: field = ['a', 'b', 'c'] I then have some logic in my user model class MyUser(PermissionMixin, AbstractBaseUser): permissions = ['OK', 'NOT_OK'] I can access my users from the following logic inside my serializer self.context['request'].user.permissions I would now like to only share parts a and b of field if the user is not permitted to access c. In other words I want to do something roughly equivalent to class MySerializer(serializers.ModelSerializer): class Meta: if 'OK' in self.context['request'].user.permissions: field = ['a', 'b', 'c'] else: field = ['a', 'b'] However, the Meta class does not have self attached. What is the best design pattern to achieve what I want? Is the serializer the best place to house this logic? -
Django REST Framework Interface JWT Auth
I am trying to integrate the django-rest-framework-simplejwt package for jwt auth. Everything works as expected, the only issues is that I don't know how to make it work with the Django Rest Framework Interface. When I try to access a "protected" view I get the expected Not Authorized response, but there is no way for me to add the token when making the request. And when I try to Login I get redirected to the django login, which doesn't help. How can I add the Bearer token to the Django Rest Framework Interface? To circumvent this, I've installed the drf_spectacular package that does its job very well, I am just curios if I can make the Django Rest Framework Interface work with the jwt token so that I don't need the drf_spectacular package. Some of my configs: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "corsheaders", "rest_framework", "rest_framework_simplejwt", "drf_spectacular", "todo_api", ] REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), } MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] #TODOListApiView.py from .serializers import TodoSerializer from drf_spectacular.utils import extend_schema from rest_framework_simplejwt.authentication import JWTAuthentication class TodoListApiView(APIView): # add permission to check if user is authenticated … -
how to customize django model message for email
I created User model in django email = models.EmailField( verbose_name="Email Address", unique=True, null=True, blank=True) When i try to register user with same email it show message user with this Email Address already exist, how i customize this message to User with this email exist -
TemplateSyntaxError at /
firstpic secondpicWhen I develop my Django app example, I meet an error with TemplateSyntaxError at / error message like below. This error is so strange but so simple to fix, but it cost me a lot of time. So I want to write down the solution here for the reader to fix it quickly to save time. -
Redirect to an external URL in Django does not work
I have been trying to redirect to an external URL in Django view but somehow it does not seem to work. The image below is what I get. Apparently it is able to print out the 2 "print" statements, showing that there is no error with the line of code: link=redirect("https://google.com"). However, it just does not return me the redirect page. Is there something that I am supposed to write at urls.py? In the urls.py file: When the 3rd line of code representing the redirect url path is written, I get the error "Forbidden (CSRF token missing.): /deliveryJob". Without this line of code, no redirects or errors happen. Not sure if I am doing it right. <view_doctor.py> @api_view(['GET',"POST"]) def deliveryJob(request): order_id = request.POST.get('order_id') box_number = request.POST.get('box_number') ward_number = patients_data.objects.filter(order_id=order_id).first().ward_number status = "Pending" recorded_date = datetime.now().date().strftime('%Y-%m-%d') recorded_time = time.strftime("%H:%M:%S", time.localtime()) c = connection.cursor() c.execute("INSERT INTO user_patient (order_id, box_number, ward_number, status, recorded_date, recorded_time) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}');".format(order_id, box_number, ward_number, status, recorded_date, recorded_time)) order_id_str = str(order_id) c.execute("DELETE FROM patients_data WHERE order_id = '%s'" % (order_id_str)) ####################### ROBOT PROMPT TRIGGER ############################# c.execute("SELECT COUNT(*) FROM user_patient WHERE status = '%s'" % ("Pending")) for record in c.fetchall(): if record[0] == 1: print("There is … -
How can I integrate the reCAPTCHA V3 to my HTML form in Django?
I am following all the possible tutorials such as Google, I make the backend and after that, I move to the front (which is in the same project). In the backend, of course, I am setting my key private and public keys in settings. settings.py: RECAPTCHA_PUBLIC_KEY = "secret" RECAPTCHA_PRIVATE_KEY = "secreter" This is my users.view.py and the Class where I set the form fields: class createNewAccountForm(forms.Form): name = forms.CharField(required=True, validators=[validate_alphanumericplus]) email = forms.CharField(required=True) password = SetPasswordField(label='Password', required=True) captcha = ReCaptchaField( public_key=settings.RECAPTCHA_PUBLIC_KEY, private_key=settings.RECAPTCHA_PRIVATE_KEY, widget=ReCaptchaV3( attrs={ 'required_score': 0.85, } ) ) This is the class where I set the HTML and make the sign up happening: class createNewAccountView(FormView): form_class = createNewAccountForm template_name = 'account/create.html' def form_valid(self, form): captcha_score = form.cleaned_data['captcha'].verify(self.request) if captcha_score < 0.5: form.add_error(None, 'reCAPTCHA verification failed.') return self.form_invalid print("form is valid, creating user") print(form.cleaned_data) name = form.cleaned_data['name'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] next = form.data.get('next', None) And this is the create.html form part: <form method="post" action="{% url 'users:create_account' %}" id="create-form"> {% csrf_token %} {% if request.GET.next %} <input id="next" name="next" type="hidden" value="{{ request.GET.next }}"> {% endif %} <div> <label for="support_full_name"> Name </label> <div> <input id="support_full_name" name="name" type="text" required aria-required="true" placeholder="Your name" class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md … -
Django Nested Serializers won't work independently- Key Error /dashboard/api/institution/editor/ 'id'
I'm trying to create an app using JQuery Datatables Editor and a Django REST framework API. Whenever I try to create an entry, I am returned the above key error. I believe the problem is traced back to the to_internal_value function within the InstitutionDatatableSerializer. However, I cannot delete this function as it is necessary for me to create a new entry for the InvestigatorDatatableSerializer. How can I fix the serializer? serializers.py class InstitutionDatatableSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) def to_internal_value(self, data): return get_object_or_404(Institution, pk=data['id']) class Meta: model = Institution fields = ('__all__') datatables_always_serialize = ('id',) class InvestigatorDatatableSerializer(serializers.ModelSerializer): institution_name = serializers.ReadOnlyField(source='institution.name') institution = InstitutionSerializer() class Meta: model = Investigator fields = ('id', 'last_name', 'first_name', 'email', 'institution_name', 'institution', ) datatables_always_serialize = ('id',) models.py class Institution(models.Model): id = models.AutoField(unique=True, primary_key=True) name = models.CharField(max_length=50) dept = models.CharField(max_length=50) class Meta: managed = True db_table = 'institution' def __str__(self): return str(self.name) class Investigator(models.Model): id = models.AutoField(unique=True, primary_key=True) last_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) email = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) institution = models.ForeignKey(Institution, models.DO_NOTHING, related_name='institution_id', ) class Meta: managed = True db_table = 'investigator' def __str__(self): return str(self.last_name) -
How to open and edit the pdf file uploaded by form
I have ModelViewSet class which accepts the uploaded file. using pymupdf( pdf handling library) import fitz class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer def list(self, request): serializer = s.DrawingSerializer(queryset, many=True) return Response(serializer.data) def create(self, request, *args, **kwargs): #file is uploaded as 'drawing' doc = fitz.open(request.data['drawing']) class Drawing(models.Model): drawing = models.FileField(upload_to='uploads/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When I uploaded the file, there comes the error like this. fitz.fitz.FileNotFoundError: no such file: 'mypdf.pdf' -
AttributeError at /users/register/ Manager isn't available; 'auth.User' has been swapped for 'userty.MyUser'
I get this error whenver I try to register a new user from my website. I have two types of users (Athlete and Host). Ive created their models as follows from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from COMBAT_CON_F import settings class MyUserManager(BaseUserManager): def normalize_email(self, email): email_parts = email.split('@') domain = email_parts[-1].lower() username = '@'.join(email_parts[:-1]) return f'{username}@{domain}' def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class MyUser(AbstractUser): #objects = MyUserManager() is_athlete = models.BooleanField(default=True) is_host = models.BooleanField(default=False) class Athlete(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) WEIGHT_CATEGORY_CHOICES = ( ('Straw Weight', 'Straw Weight'), ('Fly Weight', 'Fly Weight'), ('Bantam Weight', 'Bantam Weight'), ) user = models.OneToOneField('userty.MyUser', on_delete=models.CASCADE) email = models.EmailField(null=True, default='example@example.com') name = models.CharField(max_length=100, null=True) profile_picture = models.ImageField(upload_to='athlete_pics/', null=True, blank=True) contact_number = models.CharField(max_length=20) date_of_birth = models.DateField() age = models.IntegerField() gender = models.CharField(max_length=1, choices=GENDER_CHOICES) height = models.DecimalField(max_digits=4, decimal_places=2) weight = models.DecimalField(max_digits=4, decimal_places=2) weight_category = models.CharField(max_length=20, choices=WEIGHT_CATEGORY_CHOICES) fighting_style = models.CharField(max_length=100) club_name = models.CharField(max_length=100) coach_name = models.CharField(max_length=100) record = models.CharField(max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = () def __str__(self): return self.user.username class … -
Telegram, Python-telegram-bot==13.13, webhook
help me figure out what the error is. I redesigned the bot to work from a webhook I will receive a reply from a telegram POST /webhook/ 200 OK but the bot stopped responding to commands when I press /start the bot is silent. Tell me where I went wrong? thanks in advance I start everything on django for port 8050 from telegram import * from telegram.ext import * from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from decouple import config import json TOKEN = config('TELEGRAM_TOKEN') bot = Bot(token=TOKEN) updater = Updater(token=TOKEN) dp = updater.dispatcher @csrf_exempt def webhook(request): print('this is webhook') if request.method == 'POST': update = Update.de_json(json.loads(request.body), bot) dp.process_update(update) return HttpResponse('ok') def start(update: Update, context: CallbackContext) -> None: print('this is start') update.message.reply_text('Hello World!') def echo(update: Update, context: CallbackContext) -> None: print('this is echo') update.message.reply_text(update.message.text) if __name__ == '__main__': print('this is main') dp.add_handler(CommandHandler('start', start)) dp.add_handler(MessageHandler(Filters.text, echo)) updater.start_webhook( listen="0.0.0.0", port=8050, ) updater.idle() -
How to configure nginx to serve Django at a different endpoint?
I separated my frontend (NextJS) and my backend (Django). I want to serve my Django app at /api using Nginx. events {} http { server { listen 80; gzip on; server_name $HOST; location /api/ { proxy_pass http://backend: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; } location / { proxy_pass http://frontend:3000/; } } } where backend and frontend are corresponding docker-compose services. Django is not recognizing my configuration and is having a lot of issues. For example when I access /api/admin it redirects to /admin and causes troubles. I searched around but can't find any answers. How can I solve this? -
Making a file available at url using uWSGI, Django and nginx
I'm attempting to have Django/nginx serve a specific file under a specific URL, unrelated to the Django app itself. I have a .php file I'd like to serve and be displayed as a normal PHP. The PHP file I'm using: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP - Hello, World!</title> </head> <body> <h1><?php echo 'Hello, World!'; ?></h1> </body> </html> I tried adding this to my nginx configuration to achieve it: location /deploy { alias /var/www/deploy.php } When I then attempted to run my uWSGI app, going to that URL (example.com/deploy) does indeed redirect to deploy.php, but I get a pop-up to save the file on my PC (download) instead of it being displayed as a webpage. I'm not sure how to configure it to behave correctly, I'm working with nginx for the first time. -
Django GeometryDistance usage with postgis database
I am having some issues using GeometryDistance where I have a node point object and am trying to find the closest node in another table in the database. GeometryDistance(start_node.geom, vertex.objects.all()) This is the truncated output. GeometryDistance(Value(<Point object at 0x7f3afe8e4d90>) <-> <QuerySet [<WaysVerticesPgr: WaysVerticesPgr object (1)>, <WaysVerticesPgr: WaysVerticesPgr object (2)>, <WaysVerticesPgr: WaysVerticesPgr object (3)>, and the only reference info I can find is this from Django. I know the issue is with the WaysVerticesPgr queryset in the second position but don't know how to only get the geometry from the table. I would like to return the closest nodes in the vertex table to the start_node. the vertex table has the geometry in column 'the_geom'. vertex.objects.order_by(GeometryDistance(start_node.geom, vertex.objects.all().the_geom)) Here, the queryset doesn't have the_geom attribute. I remember reading that django doesn't evaluate querysets until it has to either through iteration or other methods but I don't know exactly how I should go about this query. Any help is appreciated.