Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add scroll wheel to Ckeditor 5 text editor django
I am quite new to using django. I want to add a rich text editor to my webapp and I saw a tutorial on how to do so using "django-ckeditor-5". I followed these steps: https://pypi.org/project/django-ckeditor-5/ and the editor works fine and everything however, it keeps expanding with the the text, so it just goes of the screen after a while. Is there a way to stop this behavior, and instead add a scroll wheel to the side of the editor so users can use that to see the entire text? I was also wandering how I can install plugins to the editor since I know it's possible but i'm not really sure how. Here is my ckeditor config in the settings.py file: customColorPalette = [ { 'color': 'hsl(4, 90%, 58%)', 'label': 'Red' }, { 'color': 'hsl(340, 82%, 52%)', 'label': 'Pink' }, { 'color': 'hsl(291, 64%, 42%)', 'label': 'Purple' }, { 'color': 'hsl(262, 52%, 47%)', 'label': 'Deep Purple' }, { 'color': 'hsl(231, 48%, 48%)', 'label': 'Indigo' }, { 'color': 'hsl(207, 90%, 54%)', 'label': 'Blue' }, ] CKEDITOR_5_CONFIGS = { 'default': { 'toolbar': ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote' ], }, 'extends': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', … -
Custom logger Formatter in Python
I need to use 2 different handlers, one for Elasticsearch and the other for Django. The Elasticsearch handler has already custom formatter (json-like), and is set to ERROR level. I need to pass extra args in order to create indexes in Kibana. The Django logs needs a different formatting: '[%(asctime)s] %(name)s %(levelname)-8s --> %(message)s'. But for the ERROR level I need to take care of the extra, because the message will be: f"[{pid}] {func}() - {msg} - {tb} - [{exc_name} - {exc_args}]" For the INFO i need only f"[{pid}] {func}() - {msg}" So I created a Custom Formatter Class, and it works but: I can not find a way to pass the fmt in order to add asctime and name (package.module). The LogRecord doesn't have by default them. LOG_BASE_PATH = BASE_DIR / 'logs/' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'precise': { '()': utils.DjangoCustomFormatter("[%(asctime)s] %(name)s %(levelname)s: %(message)s"), # 'format': '[%(asctime)s] %(name)s %(levelname)-8s --> %(message)s', }, 'ecs': { '()': 'ecs_logging.StdlibFormatter', }, }, 'handlers': { 'file_django': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_BASE_PATH / 'django.log', 'formatter': 'precise', 'level': 'INFO', }, 'file_ecs': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_BASE_PATH / 'test.log', 'formatter': 'ecs', 'level': 'ERROR' }, }, 'loggers': { 'multi_logger': { 'handlers': ['file_ecs', 'file_django'], 'level': … -
Field name `email` is not valid for model `customer`. in Multi User authentication Django Rest Framework
I am trying to create a multiple user authentication system in Django and am using onetoone field and booleans for creating profiles. But when creating serializers it throws the error "Field name email is not valid for model customer." Can someone please clarify what am I doing wrong here? models.py: from django.db import models from django.contrib.auth.models import User,AbstractBaseUser,BaseUserManager # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError("The email must be set") if not password: raise ValueError("The password must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user class user(AbstractBaseUser): is_customer = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) email = models.EmailField(max_length=100,unique=True) USERNAME_FIELD = 'email' objects = UserManager class customer(models.Model): user = models.OneToOneField(user,on_delete=models.CASCADE) firstname = models.CharField(max_length=80) lastname = models.CharField(max_length=80) class restaurant(models.Model): user = models.OneToOneField(user,on_delete=models.CASCADE) rest_name = models.CharField(max_length=80) serializers.py:- from rest_framework import serializers from .models import * class userserializer(serializers.ModelSerializer): class Meta: model = user fields = '__all__' class cust_serializer(serializers.ModelSerializer): class Meta: model = customer user = userserializer(read_only=False) email = serializers.StringRelatedField(read_only=False,source = 'user.email') password = serializers.StringRelatedField(source = 'user.password') fields = [ 'id', 'email', 'password', 'firstname', 'lastname', ] def create(self,validated_data): user1 = user.objects.create(self,email=validated_data['email'],password=validated_data['password']) user1.is_customer = True user1.save() instance = customer.objects.create(user=user1,firstname = validated_data['firstname'],lastname = ['lastname']) return … -
Django ORM: LEFT JOIN condition based on another LEFT JOIN
I'm using Django 4.0 and PostgreSQL (13.7) as the backend (upgrading would be possible if its required for a solution) I have two models: Cat and Attribute. The Attribute holds generic key-value pairs describing Cat instances. Cat table: PK name 1 Wanda 2 Aisha 3 Thala Attribute table: PK cat_id key value 1 1 size 10 2 1 age 5 3 2 size 7 4 2 intelligence 75 5 2 children 3 6 3 intelligence 60 7 3 age 9 I'd like to select different attribute values depending on conditions of other attributes for all instances, e.g.: Get size of a Cat if its age is greather than 4 or it has more than 2 children - or if there is no match, get age if intelligence is over 50. Well, the example here contains random attributes and numbers and does not make any sense, but in my application's world the conditions can be overly complex including several recursive AND, OR, EXISTS and NOT conditions. My query would be: SELECT DISTINCT(cat.id), cat.name, COALESCE( result1.key, result2.key ) as result_key COALESCE( result1.value, result2.value ) as result_value FROM cat -- first condition LEFT OUTER JOIN attribute cond1 ON ( cat.id = cond1.cat_id AND … -
create a new model instance automatically in django
I am creating a django + react.js project. I have integrated social auth for google using django social auth. I am able to get the django access token and in the admin panel I can see a new User instance is getting created. However I have a UserProfile model which has a one-to-one relation with the User model and there no new instance is getting created. Following is my model class for UserProfile. class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) userName = models.CharField(max_length=26,unique=True) email = models.EmailField(max_length=254,unique=True) profilePhoto = models.ImageField(default="/default.png") rank = models.CharField(max_length=26,default="Novice") def __str__(self): return self.userName My question is, Is there any way that I could automatically create a new instance for UserProfile just whenever a new User instance is getting created. -
Django Models: Different fields in a form depending on a selected option from a selected list
One table has a choices select list, specialization (rocket engines, navigation software, or airports) The other table(s) should create different Forms which have different classes, (I mean college study program classes) and therefore different fields in the Form, depending on what was selected on the other table. Should I create several models, one for each specialization? so that each has different study program classes? How can I make it so that upon having chosen a specialization, the corresponding model is activated and launches me the correct Form? This is my timid visualization, but I have no idea whether that is the right approach or even how to implement that code. So far 4 days and can't get my head around it. I have seen this: Django: Switch a form in template depending on choice field but still can't come full circle. -
Django Postgresql jsonfield queryset
p = Profile(name="Tanner", data={'daily__email': 'a@a.com', 'weekly__email': True}) p.save() Profile model has jsonfield. Profile.objects.filter(data__daily__email='a@a.com') Profile.objects.filter(data__daily__email__startswith='a') how can i find Tanner on queryset?.. how can i find Tanner on queryset? -
Django models.IntegerField
In my Django admin page, I have a dropdown field (Teachers Name) that fills from Teacher_CHOICES. But when I want to Save something, the Teacher's dropdown field has an error "Select a valid choice. 25 is not one of the available choices.". I need to TecherID. 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, '-------'), (34, 'Farhad Dorod'), (26, 'Mahsa Ghafarzadeh'), ] TeacherID = models.IntegerField(max_length=200, choices=Teacher_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 BIGINT to LONGTEXT Please help me. Thanks so much. -
function on entering admin list view
I have an admin list view, that for every row calls an external API and therefore becomes costly. So I am looking for a way to make the call once on entering the admin list view: @admin.display(description = "foo") def some_action(self, obj): return do_some_expensive_call(obj) I want to turn this into: def run_once(self): self.results = {} self.results[key] = some_expensive_list_call() @admin.display(description = "foo") def some_action(self, obj): return self.results[obj] Is there a method that should be used? -
Django: connection of LoginView with template fields
I created a combined registration and login form that is linked to the LoginView, but I ran into a problem relating the fields in the form to the LoginView mechanism (it does not use them). Can anyone suggest if it's possible to use custom template styling instead of using the standard approach with unstyled {{form.username}}, {{form.password} } and the like? Thanx! Here is my template login.html <div class="form-structor"> <div class="signup slide-up"> <h2 class="form-title" id="signup"><span>or</span>SignUp</h2> <form method="post"> {% csrf_token %} <div class="form-holder"> <label> <input id="uname" type="text" class="input" placeholder="Name" required autocomplete="off"/> </label> <label> <input id="pwd" type="password" class="input" placeholder="Password" required autocomplete="off"/> </label> <label> <input id="pwd2" type="password" class="input" placeholder="Retype password" required autocomplete="off"/> </label> </div> <button id="id_signup" class="submit-btn">SignUp</button> </form> </div> <div class="login"> <div class="center"> <h2 class="form-title" id="login"><span>or</span>Login</h2> <form method="post"> {% csrf_token %} <div class="form-holder"> <label> <input name="{{ form.name.name }}" id="id_name" type="text" class="input" placeholder="Name" required autocomplete="off"/> </label> <label> <input name="{{ form.name.name }}" id="id_password" type="password" class="input" placeholder="Password" required autocomplete="off"/> </label> </div> <button id="id_login" class="submit-btn">Login</button> </form> </div> </div> </div> And simple use: class SimpleLoginUser(LoginView): template_name = 'login/login.html' def get_success_url(self): return '/show-person-visits/'+str(self.request.user.person.id)+'/' Does anyone have experience with this? -
Uploaded image in ImageField is not shown by generic CreateView/DetailView/UpdateView
When uploading an image, the image file is stored in the desired folder. Good! But the generic views doesn't show the stored image but only: My code looks like this: model: def tenant_images_path(instance, filename): # generate filename like: return 'data/1/images/2023/03/01/' + filename class ArticleModel(models.Model): product_image = models.ImageField(_('Product image'), upload_to=tenant_images_path) article_create.html template: <h1>{% trans "Create new article" %}</h1> <div class="col-md-10"> <form action="{% url 'article-create' %}" method="post" class="form" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit">{% trans 'Create' %}</button> {% endbuttons %} </form> </div> article_update.html template: <h1>{% trans "Update article" %}</h1> <div class="col-md-10"> <form action="" method="post" class="form" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit">{% trans "Update" %}</button> {% endbuttons %} </form> </div> I expected the generic views to handle the display of the image. Am I wrong? -
Login using social auth
I am trying to integrate social login functionality in my react.js + Django app. I am following this video https://youtu.be/wlcCvzOLL8w and documentation provided by https://github.com/wagnerdelima/drf-social-oauth2 . I have created the custom signIn button and on clicking it I am getting getting the information about my gmail. However, I am not sure how to proceed further as I haven't found any tutorial or good documentation on how to connect the user's gmail with the backend, So the user's progress could be tracked. Can anyone please provide some link that might help me to proceed. -
How to insert business logic in django template?
I am working on review rating form, and I want to display the rating stars given by the user. I am getting an int value rating from the database out of 5 rating. However I want to implement a logic in django template that would looks like the follow code, a = "THIS IS A STRING" b = "THIS IS B STRING" max_val = 5 def review_rating(val): flag = 0 for i in range(max_val): if flag == 0: for j in range(val): print(a) flag = 1 new_val = max_val - val for k in range(new_val): print(b) break review_rating(1) Note: val is the rating value from database. Can anyone help ? -
Populating a Leaflet map with EasyButton instances in JavaScript using a loop results in onclick function reflecting only the last iteration
It's probably my poor knowledge in JS but I am stuck. My issue is that anything I place where !!!PROBLEM IS HERE!!! (see code below) is located, is set to the last iteration, here water as key and "{% static 'map/img/modes/water.png'%}" as value. template.html <script> for (mode in modes) { btn_mode = new L.easyButton('<img src="' + modes[mode] + '" style="width: 24px; height: 24px;"/>', function(btn, map){ window.location='/' + mode; <--------- !!!PROBLEM IS HERE!!! }, 'Mode "' + mode + '" information here' ); btn_mode.addTo(map).setPosition('topleft'); } </script> with modes looking like this (in reality I collect this data in Python, dump it as JSON and pass it onto my map template using the Django template language): template.html // Normally retrieved by calling "var modes = JSON.parse('{{ modes | safe }}');" var modes = { 'default': "{% static 'map/img/modes/default.png'%}", 'agriculture': "{% static 'map/img/modes/argriculture.png'%}", 'commerce': "{% static 'map/img/modes/commerce.png'%}", 'energy': "{% static 'map/img/modes/energy.png'%}", 'environment': "{% static 'map/img/modes/environment.png'%}", 'geology': "{% static 'map/img/modes/geology.png'%}", 'health': "{% static 'map/img/modes/health.png'%}", 'insurance': "{% static 'map/img/modes/insurance.png'%}", 'vegetation': "{% static 'map/img/modes/leaf.png'%}", 'military': "{% static 'map/img/modes/military.png'%}", 'social': "{% static 'map/img/modes/social.png'%}", 'weather': "{% static 'map/img/modes/weather.png'%}", 'thermal': "{% static 'map/img/modes/thermal.png'%}", 'water': "{% static 'map/img/modes/water.png'%}", } I don't get this problem if I e.g. place a simple … -
def-spectacular not generate schema urls for django-oauth-toolkit urls
I'm trying to generate Open API schema. settings.py: SPECTACULAR_SETTINGS = { 'TITLE': 'TMC Authentication API', 'DESCRIPTION': 'Description', 'VERSION': '1.0.0', 'SERVE_INCLUDE_SCHEMA': False, 'SWAGGER_UI_DIST': 'SIDECAR', 'SWAGGER_UI_FAVICON_HREF': 'SIDECAR', 'REDOC_DIST': 'SIDECAR' } urls.py: path('api/schema/', SpectacularAPIView.as_view(), name='schema'), path('api/swagger/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger'), path('api/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'), path('api/auth/token/', oauth2_provider.views.TokenApiView.as_view(), name="token"), ... When run python manage.py spectacular --file schema.yaml the oauth2_provider urls are not generated. Any idea ? -
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 …