Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement dynamic pagination in Django?
I want to create a dynamic pagination system for my ListViews. views.py: class BankPaymentListView(PermissionRequireMixin, ListView): queryset = BankPayment.objects.all() template_name = GENERIC_MODEL_LIST_TEMPLATE permissions = [Permissions.STAFF, ] raise_exception = True paginate_by = PAGINATION_NUMBER def get_paginate_by(self, queryset): return self.request.GET.get('paginate_by', self.paginate_by) def get_queryset(self): query = self.request.GET.get('search') bank_list = [] bank_payment_queryset = self.queryset if query: bank_payment_queryset = bank_payment_queryset.filter( Q(row_index__icontains=query) | Q(branch_code__icontains=query) | Q(datetime__icontains=query) | Q(document_number__icontains=query) | Q(document_description__icontains=query) | Q(paper_number__icontains=query) | Q(debt_amount__icontains=query) | Q(credit_amount__icontains=query) | Q(balance__icontains=query) ) for bp in bank_payment_queryset: obj = {} obj['row_index'] = bp.row_index obj['branch_code'] = bp.branch_code obj['datetime'] = datetime2jalali(bp.datetime).strftime('%Y/%m/%d %H:%M') obj['document_number'] = bp.document_number obj['document_description'] = bp.document_description obj['paper_number'] = bp.paper_number obj['debt_amount'] = f"{bp.debt_amount:,}" obj['credit_amount'] = f"{bp.credit_amount:,} ریال" obj['balance'] = f"{bp.balance:,} ریال" bank_list.append(obj) return bank_list and my template file has two part for pagination: one of them included select tag for get number of item for pagination and another one for get pagination pages: <select name="paginate_by" onchange="location = this.value;"> <option value=""> ----- تعداد آیتم ها -----</option> <option value="?paginate_by=10&{{page_obj.number}}">10</option> <option value="?paginate_by=20&{{page_obj.number}}">20</option> <option value="?paginate_by=50&{{page_obj.number}}">50</option> <option value="?paginate_by=100&{{page_obj.number}}">100</option> <option value="?paginate_by=500&{{page_obj.number}}">500</option> </select> {% if is_paginated %} <div style='display:flex; justify-content:center'> {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?paginate_by={{ paginate_by }}&page={{ page_obj.previous_page_number }}">قبلی</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/register.html
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/register.html Using the URLconf defined in LMS.urls, Django tried these URL patterns, in this order: admin/ base [name='base'] [name='home'] single_course [name='single_course'] contact [name='contact_us'] about [name='about_us'] msg [name='msg'] accounts/login/register [name='register'] accounts/login/login [name='login'] accounts/ login/ [name='login'] accounts/ logout/ [name='logout'] accounts/ password_change/ [name='password_change'] accounts/ password_change/done/ [name='password_change_done'] accounts/ password_reset/ [name='password_reset'] accounts/ password_reset/done/ [name='password_reset_done'] accounts/ reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/ reset/done/ [name='password_reset_complete'] The current path, accounts/login/register.html, didn’t match any of these. It should display output -
How to deploy Docker container to Google Cloud Run with Google Application Credentials?
I have a Django project that uses the Google API and Nginx for reverse proxy. I created a docker-compose.yml which has my Django container and Nginx container. It builds successfully but when I run docker-compose up, I get following error: google.auth.exceptions.DefaultCredentialsError: File /file/path/.config/gcloud/application_default_credentials.json was not found. I have installed the Google SDK and ran 'gcloud auth application-default login' which creates the json file in my root directory. I then created an environment variable for it and configured my Django app. settings.py: GOOGLE_APPLICATION_CREDENTIALS = os.environ["GOOGLE_APPLICATION_CREDENTIALS"] I can open the credentials json file in my finder so I know it's there. The Google API is being used for secret manager to retrive secret keys: from google.cloud import secretmanager import environ env = environ.Env() environ.Env.read_env() def get_secret(secret_id, version_id="latest"): project_id = env("GOOGLE_PROJECT_ID") client = secretmanager.SecretManagerServiceClient() name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" response = client.access_secret_version(name=name) return response.payload.data.decode("UTF-8") Without running docker-compose up it works fine and I can retrieve keys but I want to test it out running my docker containers. My docker-compose.yml: version: '3' services: backend: build: context: ./ dockerfile: ./Dockerfile env_file: - ./backend/.env container_name: backend ports: - 8000:8000 nginx: build: context: ./nginx dockerfile: ./Dockerfile container_name: nginx ports: - 80:80 depends_on: - backend Why is this error showing? … -
value of enum field in dataclass converts to string after instantiation in python
I have an enum class. and a dataclass containing a field with that enum class type. When i try to create an instance with an unpacked dictionary value of that enum field converts to string. Imagine this is my enum class class Statuses(Enum): SEND = 1 ACK = 2 NACK = 3 and this is my dataclass containing that enum @dataclass class Message: status: Statuses when i try to make an instance by unpacking a dictionary like this: some_dict = {"status":"1"} instance = Message(**some_dict) by printing instance i get this: Message(status='1') while i expected like this : Message(status=Statuses.SEND) -
How to customize DRF reset password link?
What I want to achieve Backend is DRF. The front end is React.js. I'm making an app and implementing Reset password. When user resets password, email will be sent to the user's email. Premise I am currently using the following libraries https://github.com/anexia-it/django-rest-passwordreset/blob/master/README.md When user resets password, he got the link below. http://localhost:8000/api/password_reset/confirm/?token=604c13ce7bff445 However I would like to customize this link. I use React.js so I want to make like. http://localhost:3002/api/password_reset/confirm/?token=604c13ce7bff445 Is that possible? If so, how? Models.py @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): """ Handles password reset tokens When a token is created, an e-mail needs to be sent to the user :param sender: View Class that sent the signal :param instance: View Instance that sent the signal :param reset_password_token: Token Model Object :param args: :param kwargs: :return: """ # send an e-mail to the user context = { 'current_user': reset_password_token.user, 'username': reset_password_token.user.username, 'email': reset_password_token.user.email, 'reset_password_url': "{}?token={}".format( instance.request.build_absolute_uri(reverse('password_reset:reset-password-confirm')), reset_password_token.key) } # render email text email_html_message = render_to_string('email/user_reset_password.html', context) email_plaintext_message = render_to_string('email/user_reset_password.txt', context) msg = EmailMultiAlternatives( # title: "Password Reset for {title}".format(title="Some website title"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: [reset_password_token.user.email] ) msg.attach_alternative(email_html_message, "text/html") msg.send() /Desktop/my_app/my_project/accounts/templates/email/user_reset_password.html {% block subject %} 【MY App】Password Reset {% endblock subject %} {% … -
How do I create a serialiser for one to many (Foreign key) relationship?
I have to upload multiple images and save their URLs. A number of images can be uploaded but the post will be one, similarly for other posts also. I have created the models but I don't know how to create the serializer for it. My models are: class Posts(models.Model): user = models.ForeignKey(User, related_name='user_posts', on_delete=models.CASCADE, null=True, blank=True) ###other fields And class PostsMedia(models.Model): post = models.ForeignKey(Posts, related_name='post_media', on_delete=models.CASCADE, null=True, blank=True) media = models.URLField(max_length = 500, null=True, blank=True) -
keep old value input in django model form
In Laravel, we used old('field_name') to display previous input values. How can I do this in Django form model? I mean If the validation is unsuccessful the input value will be deleted. I want its previous value to be preserved and not need to be typed. mean when submitting invalid form, field fields should keep the same invalid value in input value. class AddMenuForm(forms.ModelForm): def __init__(self,*args,**kwargs): x=super(AddMenuForm, self).__init__(*args, **kwargs) return x class Meta: model=Menu fields="__all__" widgets = { 'title': forms.TextInput(attrs={ 'class': 'form-control', 'id':'inputname', 'placeholder': "نام آیتم" }), 'url': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'inputurl', 'placeholder': " mr-keshi.ir /" }), view : class addMenu(FormView): template_name = 'Menu/addMenu.html' success_url = reverse_lazy('Menu') form_class = AddMenuForm def get_context_data(self, **kwargs): if (self.kwargs['menu'] not in Menu.placeMenu): # Todo: send error message pass data = super(addMenu, self).get_context_data(**kwargs) data['places'] = Menu.placeMenu data['place'] = self.kwargs['menu'] return data def form_valid(self, form): print("form valid") menu = self.kwargs.get('menu') if (menu in Menu.placeMenu): form.save() else: pass # Todo: send error message # Todo:send success message return True def form_invalid(self, form): print("form is not valid") return super(addMenu, self).form_invalid(form) -
Exception for creation of user in social django
I have disabled creation of user in social Django. It is redirecting to login page, but there is no message displayed. Settings.py Debug = False INSTALLED_APPS = [ ... 'social_django', ]``` LOGIN_URL = 'login' LOGIN_ERROR_URL = '/' MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', ], }, }, ] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) I have removed 'social_core.pipeline.user.create_user', from the pipeline. login.html <h1 class="login-title">Log in</h1> {% if form.errors %} <div class="alert alert-danger alert-dismissable fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p>Invalid Credentials. Retry again.</p> </div> {% endif %} {% if messages %} {% for message in messages %} <div class="alert {% if message.tags %} {{ message.tags }} {% endif %} alert-dismissable fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p>{{message}}</p> </div> {% endfor %} {% endif %} <form action="{% url 'login' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="username">Username:</label> <input type="username" name="username" id="username" class="form-control" placeholder="Enter your Username"> </div> <div class="form-group mb-4"> <label for="password">Password:</label> <input type="password" name="password" id="password" class="form-control" placeholder="Enter your passsword"> </div> <button class="btn btn-outline-primary btn-block btn-lg" type="submit" name="Login" id="Login">Login</button> <a href="{% url 'social:begin' 'google-oauth2' %}">Login … -
paypal rest api and flask/django/python integration 2023, update user credits immediately after payment
In my flask web application, I am trying to update user's credits immediately after user has made payment through paypal. To make it secure, I want to make sure that user doesn't modify the amount of payment. I also want to ensure that I credits to the correct user who made the payment. This requires me to send a 'custom' variable assocaite to the user who is going to make the payment. And on the payment is captured/successed, the custom variable can be read back from the payment confirmation, so that I can identify which user made the payment. After that, I can update database and update user credit. My biggest question is that I can't find an appropriate place to create the custom variable and send to paypal in the creataion of the payment. I searched for a tons of tutorials for flask, but they are deprecated: such as the github one paypal-python-sdk at this link: github paypal-python-sdk or they are written in another language: such as in nodejs from the official paypal developer doc paypal official doc with html&nodejs example I can't get my head arround when reading the official nodejs example. But I know that I have … -
How can I customize the data for a serializer in Django Rest Framework with the POST request data and function generated data?
I have created an APIView that handles a POST request in DRF. I need the POST request to save data in my database based on one of my models: Model class Card(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) image_numbers = jsonfield.JSONField() The game parameter is an integer that will be received from the client application, and the image_numbers field is a list that I want to serialize to be stored as a json object. Here is my serializer: class CardSerializer(serializers.ModelSerializer): class Meta: model = Card fields = ( 'game', 'image_numbers' ) Here is my view class CardsView (APIView): permission_classes = (IsAuthenticated, ) def generate_combinations(request): L = [i for i in range(1, 64)] List = random.choices(L, k = 16) return List def get(self, request, *args, **kwargs): qs = Card.objects.all() serializer = CardSerializer(qs, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): #I asume this is the line I should modify serializer = CardSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error) Whenever the POST request is received with the game parameter, I want to execute the generate_combinations function and store both the game(received with the request) and the generated_combinations result, which is a list. I'm lost on how to structure the data for … -
ModelSerializer foreign key relation issue in multi database DRF project
In my DRF project, I use multiple databases to handle the data I don't specify a default database in settings. whenever I use the model serializer with ForeignKey relation Django emits the following error settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I know why this error is prone because by default ModelSerilizer sets the field of an FK relation like this serializers.PrimaryKeyRelatedField( queryset=ItemCategory.objects.all(), required=True, allow_null=False) because I don't have a default DB it will show that error it's fine to overcome I did something like this class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'name', 'category') def __init__(self, instance=None, data=..., **kwargs): user = kwargs.get('context').get('user') database = user.db self.fields['category'] = serializers.PrimaryKeyRelatedField( allow_null=True, queryset=ItemCategory.objects.using(database).all(), required=False) super().__init__(instance, data, **kwargs) but when I print the field category it returns something like this PrimaryKeyRelatedField(allow_null=True, queryset=<QuerySet [<ItemCategory: ItemCategory object (1)>]>, required=False) instead of the query param, it assigns the querySet is there any solution for this (I am not sure assigning the fields manually from init method works fine) -
What is the syntax for setting a particular object's eternal cache when declaring cache.set()?
On a project, I use a package to generate cronjobs - for this I declared a class in utils.py, inherited from the broker class that serves the crontab file in Ubuntu - writes and updates cronjobs data. An instance of this object is not created alone for the entire project. I've extended this broker class to keep a hash table of all the cronjobs internally - this is how I access the cronjobs in the Ubuntu crontab to update them. Broker - crontab is not connected to the database in any way, so it resets every time I log into the IDE and I get a KeyError when accessing cronjobs. To solve the problem, I want to set an eternal cache only for this object. What parameter should be specified in cache.set() to do this? I tried storing this object in a json serializer I wrote, but the deserializer failed. If you know how this can be done, I will be grateful if you write about it. Thanks for any answer! -
TypeError: fromisoformat: argument must be str in datetimefield
I hav e a model in my models.py as ` class PassForm(models.Model): name= models.CharField(max_length=100, default=None) time_periode = models.ForeignKey(SubTime, on_delete = models.CASCADE, default=True) school_name = models.ForeignKey(admindb.SchoolDetail, on_delete = models.CASCADE, default=True) start_place = models.ForeignKey(Place, null=True, blank=True, on_delete =models.CASCADE, related_name="pass_start") end_place = models.ForeignKey(Place, null=True, blank = True, on_delete = models.CASCADE, related_name = 'pass_end') age = models.IntegerField(blank=True, null=True, default=True) dob = models.DateTimeField(default=timezone.now ) address = models.TextField(max_length=100, blank=True, null=True) adhaar_no = models.CharField(max_length=200, null=True, blank=True) mobile = models.CharField(max_length=200, blank=True, default=None) idimage = models.ImageField(upload_to='users/static/ksrtcimage/idimage', null=True, default=None) adhaar_image = models.ImageField(upload_to='users/static/ksrtcimage/adhaar', null=True, default=None) profileimage = models.ImageField(upload_to='users/static/ksrtcimage/profileimage', null=True, default=None) while I'm trying to migrate it I'm getting the following error related to the datetimefield parsed = parse_datetime(value) File "/home/noelsj/anaconda3/lib/python3.9/site-packages/django/utils/dateparse.py", line 114, in parse_datetime return datetime.datetime.fromisoformat(value) TypeError: fromisoformat: argument must be str I've tried providing default value to the field but it didn't get fixed please give me your possible answers thank you so much -
Django, Ajax, csrftoken. Please tell me what is the problem
UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. warnings.warn( On HTML templates everything worked. After switching to AJAX, this error appeared Tried these tips, did not help: How can I send a CSRF token in a form?. https://django.readthedocs.io/en/latest/howto/csrf.html. addnew.html {% load widget_tweaks %} <form method="post" action="{% url 'table:addnew' %}" class="js-product-add-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title modalLabel">Добавить запись</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button> <input type="submit" class="btn btn-primary" value="Добавить" /> </div> </div> </form> views.py def index(request): snj = ScheduleNotJob.objects.all() form = SNJ() return render(request,"index.html",{'snj': snj, 'form':form}) def save_product_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True SNJ = ScheduleNotJob.objects.all() data['html_product_list'] = render_to_string('table.html', { 'snj': SNJ }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def addnew(request): … -
Convert list to JSON Lines file and write to Django FileField on S3
Let's say I have the following list of dicts: data = [ {"a": 1}, {"a": 1, "b": 2}, {"a": 1, "b": {"c": 3, "d": 4}}, ] And a simple model with a file field backed by S3: from storages.backends.s3boto3 import S3Boto3Storage class S3Storage(S3Boto3Storage): bucket_name = "my-bucket" class Output(models.Model): file = models.FileField(upload_to="uploads/") I want to generate a JSON Lines file and upload that to Output.file. This is what I have so far: from tempfile import TemporaryFile with TemporaryFile(mode="w+") as tmp_file: for record in data: json.dump(record, tmp_file) tmp_file.write("\n") tmp_file.seek(0) bytes_file = tmp_file.read().encode() content = ContentFile(bytes_file) output = Output() output.file.save("data.jsonl", content) This works fine but seems inefficient, specifically reading the entire temp file and encoding it. Is there a more performant way to do this, perhaps by writing bytes to the file originally so I can avoid the following lines: tmp_file.seek(0) bytes_file = tmp_file.read().encode() Or are there other areas for speed / memory optimization? -
Stripe Subscription using stripe.Subscription.create function does not provide client_secret with Django
As suggested here , I am using stripe.Subscription.create function to create a subscription for the users in my Django DRM and expect to have a client secret that is associated with the subscription and the related payment_intent. However following is the error that I get : customer.clientsecret=stripe_subscription.latest_invoice.payment_intent.client_secret AttributeError: 'NoneType' object has no attribute 'client_secret' Below is the code that I am executing in the backend : stripe_customer = stripe.Customer.create(email=instance.email) customer.product = Product.objects.get(plan=0) # Free plan price id customer.stripe_customer_id = stripe_customer['id'] stripe_subscription = stripe.Subscription.create( customer=customer.stripe_customer_id, items=[{"price": customer.product.stripe_plan_id},], payment_behavior='default_incomplete', payment_settings={'save_default_payment_method': 'on_subscription'}, expand=['latest_invoice.payment_intent'], ) customer.clientsecret=stripe_subscription.latest_invoice.payment_intent.client_secret How can I get a valid client_secret for the subscription that I create ? -
Prometheus - Django app metrics are notcollected
I have installed Prometheus on the same server where my Django app is running. I am attempting to retrieve metrics using an API and the curl response appears to be in the correct format. API (url & view): `ROUTER.register('organization_metrics', simulation.views.OrganizationViewSet, basename='organization_metrics') class OrganizationViewSet(viewsets.ViewSet): renderer_classes = [StaticHTMLRenderer] def list(self, request): organizations = ["org1", "org2", "org3"] # Replace with your own data # Create a new CollectorRegistry object registry = CollectorRegistry() # Create a new Counter metric to track the number of organizations #org_counter = Counter('organizations_total', 'Total number of organizations', registry=registry) org_counter = Counter('organizations_total', 'Total_number_of_organizations', ['org_name'], registry=registry) # Increment the counter for each organization for org in organizations: org_counter.labels(org_name=org).inc() # org_counter.inc() # Generate the Prometheus format response #response_data = generate_latest(registry) # Return the response with the content type 'text/plain' logging.info('here I am') #return Response(response_data, content_type='text/plain') return ( Response( generate_latest(registry), status=status.HTTP_200_OK, content_type='text/plain', ) )` Curl response looks good and in right format: `curl --request GET http://localhost:8070/api/v1/organization_metrics/ -H 'Accept: text/html' # HELP organizations_total Total_number_of_organizations # TYPE organizations_total counter organizations_total{org_name="org1"} 1.0 organizations_total{org_name="org2"} 1.0 organizations_total{org_name="org3"} 1.0 # TYPE organizations_created gauge organizations_created{org_name="org1"} 1.6776296973446844e+09 organizations_created{org_name="org2"} 1.6776296973447082e+09 organizations_created{org_name="org3"} 1.6776296973447242e+09` In my prometheus.yml file, I have included relevant scrape_configs: ` - job_name: 'myapp-organization-metrics' scrape_interval: 6s metrics_path: '/api/v1/organization_metrics/' static_configs: - targets: … -
I'm rtying to import the Stripe API using pip but I'm getting a module not found error even though I've installed it
I'm trying to install stripe using pip, however, when I try to run my project with the import I get a module not found error. This makes no sense to me as when I look at the list of requirements I see stripe: 5.2.0. I'm using Django and I'm trying to install it in my virtual environment. The stack trace is shown below: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\bench\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\bench\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\core\checks\urls.py", line 61, in _load_all_namespaces url_patterns = getattr(resolver, "url_patterns", []) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\bench\Documents\z12-app\server\.venv\Lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\bench\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) … -
Google OAuth Login in DRF application raise Invalid token type
I had implemented Google OAuth in my DRF application using all-auth and dj-rest-auth, but for some reason stop working. Traceback shows the JWT, but for some reason, allauth raise this raise DecodeError(f"Invalid token type. Token must be a {bytes}") Traceback_1 Traceback_2 I tried to follow this tutorial but couldn't reproduce the scenario. The code is at this PR Does anyone have the same error? -
Responsive floating label on input form
I've created a form using Django, Crispy Forms and Bootstrap. At screen widths above 575px the form and labels look as expected with fields of the correct width and floating labels in the correct position, however at screen widths below 575px the form looks like this: I believe this is because, in order to force the responsive resizing of the input fields, I manually amended the CSS to reduce the the field width to 85% at screen widths lower than 575px by using a media query as follows: @media (max-width: 575px) { .form-floating > .form-control, .form-floating > .form-select { display: block; width: 85%; padding: 0.375rem 0.75rem; margin: 0 auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } } It seems the issue is that the label has remained in its original position and therefore is now outside of the perimeter of the input field. How can I amend the CSS again so that the floating label is repositioned to remain inside of the input field? -
running a django project in a virtualenv on both windows and WSL
How can I make a $ pipenv shell and then a $ python3 manage.py runserver work inside the WSL just like it runs on Windows terminal? I want to code in both windows and linux environment and run the application server on both environments. I'm writing a Django project mostly on Windows but I wanted to be able to eventually use my good and old vim+Linux through the Windows Subsystem for Linux (WSL2). I have WSL with ubuntu, python, and pipenv installed and I'm on my project's directory that is mounted C: drive. Inside my project folder, I already have .venv and everything working fine from a Windows terminal, but can't just go to Linux and run the application server. -
Django models.IntegerField choices
In my Django admin page, I have a dropdown field (Teachers Name) that fills from Database when the page loads. But when I want to Save something, the Teacher's dropdown field has an error. I need to TecherID. My model.py: class classes_info(models.Model): ClassName = models.CharField(max_length=255, verbose_name="Class name") On = "On" Off = "Off" Status_CHOICES = [ (On, 'On'), (Off, 'Off'), ] Status = models.CharField(max_length=10, choices=Status_CHOICES, default=On) Teacher_CHOICES = [ (0, '-------'), ] TeacherID = models.IntegerField(max_length=200, choices=Teacher_CHOICES) And My Admin.py: class classes_info_Admin(admin.ModelAdmin): list_display = ('ClassName') def formfield_for_choice_field(self, db_field, request, **kwargs): if db_field.name == "TeacherID": Teachers_Info = personal_info.objects.values('id', 'FirstName', 'MiddleName', 'LastName', 'images').filter(Type='Teacher', Status='On') Teachers_List = [(0, '-------')] if len(Teachers_Info) != 0: for x in list(Teachers_Info): y = (x['id']), x['FirstName'] + " " + x['MiddleName'] + " " + x['LastName']) Teachers_List.append(y) kwargs['choices'] = Teachers_List return super(classes_info_Admin, self).formfield_for_choice_field(db_field, request, **kwargs) Teacher information is loaded from the database: When I want to save information, my error in TeacherID field is: "Select a valid choice. 34 is not one of the available choices." I have a problem and I don't know what's my problem. Please Help me. Thanks. I changed models to CharField: TeacherID = models.CharField(max_length=200, choices=Teacher_CHOICES) And also, I changed Datatype in the Database. From … -
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