Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ManyToMany not saving
I have a ModelMultipleChoiceField that I try to save save as ManyToMany relationships and tried almost every solution on the internet but for some reason I can't get mine to save. I don't get any errors and the rest of the form submits just not the ManyToMany. Models.py class Game(models.Model): players = models.ManyToManyField(Student, blank=True) other fields... class Student(models.Model): user_name = models.CharField(max_length=150, null=False, blank=False) Forms.py class Game(forms.ModelForm): players = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Student.objects.all(), label="Players", required=False) Views.py def creategame(request): if request.method == "POST": form = Game(request.POST) if form.is_valid(): form.save() return redirect(reverse('management')) else: ... I tried multiple solutions like this, but none of them worked. Views.py def creategame(request): if request.method == "POST": form = Game(request.POST) if form.is_valid(): new_game = form.save(commit=False) new_game.save() form.save_m2m() return redirect(reverse('management')) else: ... -
NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
I am sorry to post this problem once again. I am getting the error even though the configuration files looks correct with the 'login' entry. In settings.py added "LOGIN_URL = '/login/'" In the APP/templates/base.html: {% if user.is_authenticated %} <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} The APP/views.py looks as follows: from django.http import HttpResponse from django.template import loader from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required @login_required(login_url='login') # Redirect to the login page if not authenticated def protected_intro(request): return render(request, 'intro.html') The APP/urls.py looks like: from django.urls import path from django.contrib.auth.views import LoginView from . import views app_name = 'APP' urlpatterns = [ ... path('login/', LoginView.as_view(), name='login'), ] All the entries regarding the 'login' seems correct, but ending up with the error "Reverse for 'login' not found. 'login' is not a valid view function or pattern name." Please help. Thanks! I tried looking for the solution, but could not solve it. -
when I am running python manage.py make migrate there is an overflow error so which is causing an error
When I am running python manage.py makemigrations it worked but when I am running python manage.py migrate it is raising an overflow error # from email.policy import default # from pyexpat import model from django.db import models # from unicodedata import decimal from shortuuid.django_fields import ShortUUIDField from django.utils.html import mark_safe from userauths.models import CustomUser STATUS_CHOICE=( ("process","Processing"), ("shipped","Shipped"), ("delevered","Delevered"), ) STATUS=( ("draft","Draft"), ("disable","Disable"), ("rejected","Rejected"), ("In_review","In Review"), ("published","Published"), ) RATING=( (1,"⭐☆☆☆☆"), (2,"⭐⭐☆☆☆"), (3,"⭐⭐⭐☆☆"), (4,"⭐⭐⭐⭐☆"), (5,"⭐⭐⭐⭐⭐"), ) # Create your models here. def user_directory_path(instance,filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Category(models.Model): cid=ShortUUIDField(length=10,max_length=100,prefix="cat",alphabet="abcdef") title=models.CharField(max_length=100,default="Food") image=models.ImageField(upload_to="category",default="category.jpg") class Meta: verbose_name_plural="Categories" def catagory_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Tags(models.Model): pass class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=models.TextField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) tags=models.ForeignKey(Tags, on_delete=models.SET_NULL ,null=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=(self.price/self.old_price) * … -
i am facing this error (1054, "Unknown column 'id' in 'erp_app_invoice'")
hello i am newbie in this field, at the beginning everything's worked fine however i faced this error (1054, "Unknown column 'id' in 'erp_app_invoice'") after making some changes in my models.py. notice that i dont have id in my models.py as it should be generated automatically as far as i know i tried adding id = models.AutoField(primary_key=True) but it didn't work due to the fact that i cant have 2 AutoFields, also tried to make it as CharField but that didn't work also -
Django project with Gunicorn, Nginx, Docker
I have a django app that runs fine locally (no DB). However, I need to deploy this into a VM using a docker image and am really new to everything for deployment and dont know how to start. Could anyone provide a step by step on how I can add gunicorn and nginx to the project and build everything into a docker image (i do not want to use docker-compose). Also looking on what the Dockerfile should have. Thanks -
DRF mixin uses the model manager's create method but not the update method
# models.py class HelloManager(models.Manager): ''' On create, set date_created and last_modified to the same values On update, set last_modified to current time ''' def create(self, *args, **kwargs): current_time = datetime.now() kwargs.setdefault('date_created', current_time) kwargs.setdefault('last_modified', current_time) return super().create(*args, **kwargs) def update(self, *args, **kwargs): kwargs['last_modified'] = datetime.now() return super().update(*args, **kwargs) The CreateModelMixin works just fine, but the UpdateModelMixin does not call my manager's update method. I went through DRF's implementation and found that the UpdateModelMixin calls serializer.save() wich calls either update or create but this is where I got lost. I tried just directly overriding perform_create like so: # views.py class HelloDetailView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, generics.GenericAPIView): queryset = HelloModel.objects.all() lookup_field = 'id' def get_serializer_class(self): if self.request.method == 'POST': return HelloWriteSerializer return HelloReadSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def perform_update(self, serializer): HelloModel.objects.update(**serializer.validated_data) But the problem now is the UpdateModelMixin now returns old data. What's the best approach for this? -
Related fields aren't filtering in the formset (using library 'django-formset' )
I'm trying to use the library 'django-formset' to filter drop-down list (ForeignKey objects) when selecting an item in a linked drop-down list (related ForeignKey objects). I think, I did everything according to the instructions, but still the data in the second drop-down list is not filtered. Maybe someone has experience using this library with formset? What I did: Model class TypeCar(models.Model): title = models.CharField(max_length=20) class Car(models.Model): reg_mark = models.CharField(max_length=10) type_car = models.ForeignKey( 'TypeCar', ... ) class Order(models.Model): car = models.ForeignKey( Car, ... ) type_car = models.ForeignKey( TypeCar, ... ) Form (FormSet): from formset.widgets import Selectize class OrderCloseForm(forms.ModelForm): type_car = forms.ModelChoiceField( label="Type_car", queryset=TypeCar.objects.all(), widget=Selectize( search_lookup='name__icontains', placeholder="First, select Type car" ), required=False, ) car = forms.ModelChoiceField( label="Car", queryset=Car.objects.all(), widget=Selectize( search_lookup=['title__icontains'], filter_by={'type_car': 'type_car__id'}, placeholder="Then, select a Car" ), required=False, ) class Meta: model = Order fields = ( 'type_car', 'car', ) Formset displays already existing objects in which need to make a selection of the above fields OrderCloseFormSet = modelformset_factory( Order, form=OrderCloseForm, extra=0, can_delete=False, ) Template <head> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link href="{% static 'formset/css/bootstrap5-extra.css' %}" rel="stylesheet"> <link href="{% static 'formset/css/collections.css' %}" rel="stylesheet"> <script type="module" src="{% static 'formset/js/django-formset.js' %}"></script> </head> <django-formset endpoint="{{ request.path }}" csrf-token="{{ csrf_token }}"> {{ formset.management_form }} {{ … -
Python Django does not see the CSS file
I just started using Django, which I initially had a lot of problems with, but that's not the point. I launched a new project about 4 times, it turned out that through the console it did not create a complete list of folders and files and I had to create them manually. I created and added an init file everywhere so that Python sees this folder, however, when I need to insert a Banner photo for my profile, when I start the server through the console and the python manage.py runserver command, although it launches my entire HTML structure, it does not display the photo , which I inserted there initially. I tried to change the location of the folders, I tried to change the location of the photos and it didn’t bring much results. Also, I changed settings.py and urls several times, but this also did not change anything, perhaps I made a mistake in the code or missed something? {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="{% static 'css' %}" /> <title>Your Profile</title> </head> <body> <div class="container"> <div class="sidebar"> <div class="logo"><span class="tf-logo">{{ title … -
Using an object attribute when accessing element in array in Django Template Python
So basically in my Django template I'm passing in two things from my view. a Django model object Plan which is defined like: class Plan(models.Model): class Sport(models.IntegerChoices): RUN = 1, "RUNNING" CYC = 2, "CYCLING" SWM = 3, "SWIMMING" sport = models.PositiveSmallIntegerField( choices=Sport.choices, default=Sport.RUN ) start_date = models.DateField("Starting Date") end_date = models.DateField("End Date") weeks = models.PositiveSmallIntegerField(default=0) title = models.CharField(max_length=20) description = models.TextField(max_length=100, blank=True, null=True) completed = models.BooleanField(default=False) def __str__(self): return self.title and 2. an array of arrays of strava activities pulled from an API, activity_list which is formatted so activity_list[i][j] would return week i's activity on day j. In my template, I need to access activity_list dynamically whilst looping through the week numbers in the plan. My first attempt was to do something like ativity_list.week.number.0 to access the Monday of the week we're on, but as expected Django treats week.number as a literal instead of replacing it with the number "0" or "3" or whatever. I'm really stuck on this so any help would be much appreciated, either with an ad-hoc fix or a way to refactor my models to make this feasible. Thanks -
CPU to 90% for gunicorn process on debian 11 - Django Nginx Gunicorn Supervisor
Since 3 days, I have some issues with the CPU usage which is up to 90%. When I run "top" on command line, I see that CPU usage for gunicorn is very high ! I do not have a lot of trafic on the website. I have checked the access log et error log, but I do not find anything... What Could I check to solve this performance issue ? Thanks I have checked the logs but I did not find anything. I work with Django, Nginx, Gunicorn and Supervisor. -
How to pass data to injected django template?
In django admin interface I have a custom tab for displaying a table. How to display the table as django admin model list table instead of field, but get the context for table from admin.py by calling the method from the model. I used django-baton's baton_form_includes to insert a template below the field, but then I could not pass data to that template. models.py class MyModel(TimeStampedModel): . . . def get_custom_tab_data(self): return OtherModel.objects.filter( active=False ) admin.py @admin.register(models.MyModel) class MyModelAdmin(): . . . readonly_fields = ( "get_custom_tab_data", ) fieldsets = ( _("Custom Tab"), { "fields": ("get_custom_tab_data"), "classes": ("tab-fs-custom") } ) . . # django-baton baton_form_includes = [("admin/custom_tab_template.html", "get_custom_tab_data", "below")] # This was the better solution but template table should display as model admin list with custom data, so had to use baton_form_includes to inject template above field. # def custom_tab_data(self, myModel: models.MyModel): # if myModel.active: # return "N/A" # if custom_data := myModel.get_custom_tab_data()[:15]: # get 15 latest # html_content = render_to_string( # "admin/custom_tab_template.html", # {"custom_data": custom_data} # ) # return mark_safe(html_content) @admin.display(description="Custom Tab") def get_custom_tab_data(self, myModel: models.MyModel): return self.custom_tab_data(account) custom_tab_template.html {% load i18n l10n %} <table class="table table-stripped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>State</th> <th>Created</th> </tr> </thead> <tbody> {% comment %} {% … -
How to get parent model id in child serializer?
How to get parent id in child serializer? class Parent(models.Model): name = models.CharField('') date = models.DateField('') class Material(models.Model): name = models.CharField('') description = models.TextField('') parent = models.ForeignKey(Parent, on_delete=models.CASCADE) serializer = ParentSerializer(data=item) if serializer.is_valid(raise_exception=True): serializer.save() class MaterialSerializer(serializers.ModelSerializer): parent = ? class Meta: model = Material fields = ['id', 'name', 'description', 'parent'] class ParentSerializer(serializers.ModelSerializer): material = MaterialSerializer(many=True) class Meta: model = Parent fields = ['name', 'date', 'material'] I dont understand how get parent id in child serializer -
django-filter ModelMultipleChoiceFilter for product color with Preview
I'm honing my django skills by writing my own e-commerce web application from scratch and I want to let users see a preview for the product colors in the color filters. Here is what I currently have, which works perfectly: What I'm trying to achieve is this: My filters.py file: import django_filters from .models import Product,ProductColor class ProductFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_expr='iexact') price_sale = django_filters.NumberFilter() price_regular= django_filters.NumberFilter() release_year = django_filters.NumberFilter(field_name='date_added', lookup_expr='year') release_year__gt = django_filters.NumberFilter(field_name='date_added', lookup_expr='year__gt') release_year__lt = django_filters.NumberFilter(field_name='date_added', lookup_expr='year__lt') chogoyo = ProductColor.objects.all() def colors(request): return ProductColor.objects.all() product_color = django_filters.filters.ModelMultipleChoiceFilter(queryset=colors) class Meta: model = Product fields = ['price_sale','price_regular', 'date_added','product_color'] What would be the best approach to accomplish this? Thank you in advance. -
"kombu.exceptions.OperationalError" occurs When running a server consisting of django, rabbitMQ, celery worker, and celery beat with docker-compose
Im currently trying to deploy a server consisting of django, rabbitMQ, celery worker, and beat. While celery beat executes the created periodic task well, the celery worker that executes the SMS sending task generates the above error message and does not work. version: "3.9" services: was_container: build: context: ./was dockerfile: Dockerfile.was container_name: was_container ports: - "8000:8000" env_file: - ./was/.env restart: always entrypoint: /entrypoint.sh networks: - miti_network rabbitmq: image: rabbitmq:3-management container_name: rabbitmq environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=admin - RABBITMQ_DEFAULT_VHOST=/ ports: - "5672:5672" - "15672:15672" expose: - "15672" networks: - miti_network celery_worker: container_name: celery_worker build: context: ./was dockerfile: Dockerfile.celery-worker environment: - CELERY_BROKER_URL=amqp://admin:admin@rabbitmq:5672// depends_on: - was_container - rabbitmq networks: - miti_network command: celery -A config worker --loglevel=info --concurrency=1 celery_beat: container_name: celery_beat build: context: ./was dockerfile: Dockerfile.celery-worker environment: - CELERY_BROKER_URL=amqp://admin:admin@rabbitmq:5672// depends_on: - was_container - rabbitmq - celery_worker networks: - miti_network command: celery -A config beat --loglevel=info networks: miti_network: driver: bridge import os import dotenv from datetime import timedelta from celery import Celery dotenv.load_dotenv() os.environ.setdefault('DJANGO_SETTINGS_MODULE', f'config.settings.{os.getenv("ENVIRONMENT")}') app = Celery('MITI') app.config_from_object('django.conf:settings', namespace='CELERY') CELERYBEAT_SCHEDULE = { 'game_status_auto_update': { 'task': 'config.tasks.update_game_status', 'schedule': timedelta(minutes=1), }, } app.conf.update( CELERYBEAT_SCHEDULE = CELERYBEAT_SCHEDULE ) app.autodiscover_tasks() from .celery import app as celery_app __all__ = ['celery_app'] Please tell me the cause and how can … -
How to make a field unique across two models in Django without inheritance?
I have following 2 models, Admin and Employee: class Admin(models.Model): name = models.CharField(max_length=30) email = models.EmailField() city = models.CharField(max_length=30) def __str__(self): return str(self.name) class Employee(models.Model): name = models.CharField(max_length=30) email = models.EmailField() city = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return str(self.name) What I want is to ensure that the field email is unique across both the models i.e. no two admins can have the same email AND no two employees can have the same email AND no admin and employee have the same email. I created a base class CustomUser and inherited it to both Employee and Admin class: class CustomUser(AbstractUser): email = models.EmailField(unique=True) class Employee(models.Model): name = models.CharField(max_lengt=30) email = models.OneToOneField(CustomUser, on_delete=models.CASCADE) city = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return str(self.name) class Admin(models.Model): name = models.CharField(max_lengt=30) email = models.OneToOneField(CustomUser, on_delete=models.CASCADE) city = models.CharField(max_length=30) def __str__(self): return str(self.name) What I want to know is, is there any other way of ensuring this kind of cross-model uniqueness that wouldn't require me to create a separate Abstract class? -
Unable to display the webpage using reactjs and having problems to integrate it with Django
I have created project where in I am using reactjs as the frontend and Django as the beackend. I have set up both Django and react but I am having trouble to get the app.js in my react project to load on the server, and not sure how to connect it to the Django api endpoint I have created models on the Django server, and when testing on the Django server, I am able to use get and post requests and it is working as expected Below is the my GitHub repo link as I am not sure where I am going wrong and it wouldn't be easy to read if I post all my files on here https://github.com/revanthperla/platform_test.git Appreciate any help I can get -
Django Elastic Search configuration for modeltranslation fields
I'm using ElasticSearch with Django. I've a model "Product", that has title field. I'm also using django-modeltranslation for my Product model to translate title field in several languages. How can I return title field matches with language that coming from request in Elastic Search. I've ElasticSearch currently working, but it's returning default title field -
Django channels and asynchoronise system
How does Django Channels facilitate real-time communication in chat systems, and what are the key components involved in its operation? Additionally, could you elaborate on how Django Channels enables asynchronous communication between two devices in a chat system, highlighting its mechanisms for handling WebSocket connections, message routing, and consumer processing? -
Python: Auto-update a field in database
I want the database to automatically update the status field when the date already passed. For example the date for the event was yesterday, and I don't want to update the status myself. Is it possible for database to automatically change the status? models.py class Events(models.Model): id = models.AutoField(db_column='id', primary_key=True) title = models.CharField(max_length=45, blank=True, null=True) venue = models.CharField(max_length=45, blank=True, null=True) date = models.DateTimeField(max_length=45, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to=eventpath, blank=True, null=True) date_posted = models.CharField(max_length=45, blank=True, null=True) status = models.CharField(max_length=45, blank=True, null=True) -
How I can run django cronjob function on windows?
I'm developing a Django application which fetches an external API and stores information from that API to a local Django model so I have set a cronjob to automatically fetch and store data within some period of time. but the problem is this that cronjobs don't work on windows. So is there any way I can test my function that it will work on production on linux server. (I'm not using windows task scheduler because I'll have to host it on linux based server.) Any help will be appreciated! -
Django : ValueError at / The 'avatar' attribute has no file associated with it
Django sends me the following error: ValueError at / The 'avatar' attribute has no file associated with it. enter image description here The message appears just after I log in, even though I uploaded an avatar when I registered a dummy profile. I can't even find the avatar in the configured path: media/avatars. Could you help find where I got this wrong please? Bellow is my code. **models.py: ** from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): (some code) avatar = models.ImageField(upload_to='avatars/',blank=True, null=True) **forms.py: ** class RegisterForm(UserCreationForm): (some code) avatar = forms.ImageField( required=False, widget=forms.ClearableFileInput( attrs={ "class": "form-control" } ) ) class Meta: model = User fields = ['username','first_name','last_name','email','avatar','password1','password2','user_type'] **settings.py: ** STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_DIR = BASE_DIR / 'media' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' I added this in urls.py of the main project directory: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And finally, the path of where I want the avatars to be uploaded: mainProject ├── media │ ├── avatars Thank you very much for any help I tried to make all the uploaded avatars go to media/avatars. I even made conditions where there is a placeholder image in case the user … -
Could not find module 'C:\OSGeo4W\bin\gdal308.dll' (or one of its dependencies)
I'm trying to use GeoDjango + gdal + PostGis in order to create a map application. OSGeo4W is completelly installed, and all the dll files are there When I run this command: python3 manage.py check I get the following result: ^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: Could not find module 'C:\OSGeo4W\bin\gdal308.dll' (or one of its dependencies). Try using the full path with constructor syntax. However the files are correctly existing in the location. Here is how my settings file looks like, for the gdal part: if os.name == 'nt': OSGEO4W = r"C:\\OSGeo4W" # if '64' in platform.architecture()[0]: # OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\\share\\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\\share\\proj" os.environ['PATH'] = OSGEO4W + r"\\bin;" + os.environ['PATH'] GDAL_LIBRARY_PATH = OSGEO4W + r"\\bin\\gdal308.dll" Could someone who has gone through this please help me shed some light over it? -
View in django not running
I have a Django project where I'm trying to activate a user's account when they reset their password. I've created a custom view ActivateUserPasswordResetConfirmView that inherits from PasswordResetConfirmView and overrides the form_valid method to set user.is_active = True. However, the form_valid method in my custom view does not seem to be called when a user resets their password. I've checked my URL configurations and they seem to be correct. Here are the relevant parts of my code: views.py: from django.contrib.auth.views import PasswordResetConfirmView class ActivateUserPasswordResetConfirmView(PasswordResetConfirmView): def form_valid(self, form): user = form.save() user.is_active = True user.save() return super().form_valid(form) myapp/urls.py: from django.urls import path from .views import ActivateUserPasswordResetConfirmView urlpatterns = [ path('reset/<uidb64>/<token>/', ActivateUserPasswordResetConfirmView.as_view(), name='password_reset_confirm'), # other urls... ] project/urls.py: from django.urls import include, path urlpatterns = [ path('', include('myapp.urls')), path('accounts/', include('django.contrib.auth.urls')), # other urls... ] I have also added logging in the form_valid method, but I don't see any log messages when testing the password reset flow, which suggests that the method is not being executed. Any ideas on why the form_valid method is not being called or how I can debug this issue further? -
Technical question: Building API using python in real time connection + authentication
I need to build an API that will be called from Android, iOS and desktop clients using framework like flutter The problem i am facing is that i need to build an APIs that relies on HTTPS request/response that uses JSON format using python and offer some features like authentication, authorization, database storing, static files storing like.png and .pdf and some parts should work in real time connection for chat system but i don't know what should i use. Because i am stacked in multiple options like Django, RESTful and channels frameworks So my questions are Is there a way to combine all those technologies or should i choose one of them and work with them? Is there a better way to do the listed features up? -
SMTPSenderRefused Error Django: (501, b'<settings.EMAIL_HOST_USER>: sender address must contain a domain', 'settings.EMAIL_HOST_USER')
I am working on a Django project. I have a contact form. What I want when someone fills up the form my info@mydomain.com should send my gmail a notification like "Someone filled up your form". When i go to contact form and submit it, there is an error page that says: SMTPSenderRefused at /contact/ (501, b'<settings.EMAIL_HOST_USER>: sender address must contain a domain', 'settings.EMAIL_HOST_USER') Django Version: 5.0.2 Exception Type: SMTPSenderRefused Exception Value: (501, b'<settings.EMAIL_HOST_USER>: sender address must contain a domain', 'settings.EMAIL_HOST_USER') Exception Location: C:\Users\Bedirhandd\AppData\Local\Programs\Python\Python311\Lib\smtplib.py, line 887, in sendmail And here is my codes: Settings.py # EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = 'backend.email.EmailBackend' EMAIL_HOST = 'mail.info@mydomain.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'info@mydomain.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'Mydomain <info@mydomain.com>' backend.email file: (I created the email_backend.py file to avoid "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain" error. I found the code here import ssl from django.core.mail.backends.smtp import EmailBackend as SMTPBackend from django.utils.functional import cached_property class EmailBackend(SMTPBackend): @cached_property def ssl_context(self): if self.ssl_certfile or self.ssl_keyfile: ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile) return ssl_context else: ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE return ssl_context And lastly here is my views.py: from django.shortcuts import render from portfolio.models import Portfolio from …