Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove password field from Django
I want to register in Django with a phone number and only get a phone number from the user I don't even want to get a password from the user That's why I decided to remove the password field from the custom user model(password=None) But with this method, I cannot enter the admin panel in Django with created super user It asks me for a password to enter the admin panel in Django How can I enter the admin panel? Code: class CustomUserManager(UserManager): def _create_user(self, name, phone_number, **extra_fields): if not phone_number: raise ValueError("You have not provided a valid phone number") user = self.model(phone_number=phone_number, name=name, **extra_fields) user.set_unusable_password() user.save(using=self._db) return user def create_user(self, name=None, phone_number=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(name, phone_number, **extra_fields) def create_superuser(self, name=None, phone_number=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self._create_user(name, phone_number, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): password = None phone_number = models.CharField(max_length = 25,blank=True, null=True, unique=True) email = models.EmailField(blank=True, null=True, unique=True) name = models.CharField(max_length=255, blank=True, null=True) objects = CustomUserManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] -
My problem with getting the current month as default in django
I have 2 models. AyModel == MonthModel and OdemelerModel == PaymentModel first model is: class AyModel(models.Model): AYLAR = ( ("Ocak", "Ocak"), ("Şubat", "Şubat"), ("Mart", "Mart"), ("Nisan", "Nisan"), ("Mayıs","Mayıs"), ("Haziran","Haziran"), ("Temmuz","Temmuz"), ("Ağustos", "Ağustos"), ("Eylül", "Eylül"), ("Ekim", "Ekim"), ("Kasım", "Kasım"), ("Aralık","Aralık"), ) ay = models.CharField(max_length=10,choices=AYLAR) def __str__(self): return self.ay class Meta: verbose_name = 'Ay' verbose_name_plural = 'Aylar' and second model is: class OdemelerModel(models.Model): odeme_ay = models.ForeignKey(AyModel,default=datetime.now().strftime('%B'), on_delete=models.DO_NOTHING) Whatever record I enter into the database first for AyModel, that record appears by default in OdemelerModel. How Can I Solve This? Thanks.. I want this month to have odeme_ay by default. The same problem occurs in my other model called YearModel. -
Site shows data after logout when clicks back button (Django)
Whenever i logout from my Django site , when i press browser's back button browser shows previous cached data .I need to clear all site data when logging out. Is there a way using JavaScript or something? I've tried @cache_control(no_cache=True, must_revalidate=True, max_age=0) but i only need to clear when user logs out . is there any solution except i provided above one? -
Django not displayed data from db
db image result #models.py class Text(models.Model): id = models.CharField(max_length=255, primary_key=True, blank=False) text = models.TextField(blank=False)enter image description here public = models.BooleanField() #views.py def home(request): data = Text.objects.all() data = { 'data': data } return render(request, 'app1/index.html', data) #index.html <div class="container p-4 g-col-6 w-50 "> {% if data %} {% for i in data %} <div class="row bg-dark text-white mt-3 rounded"> <p class="p-1 text-info">{{ i.text }}</p> </div> {% endfor %} {% else %} <p>not data</p> {% endif %}enter image description hereenter image description here </div>' I tried to output the manually recorded data several times - it was displayed perfectly, but when it comes to data from the model, nothing is displayed -
extra action viewset doesn't see object permission. django rest framework
I have extra action in my viewset: @action( detail=True, methods=["patch"], permission_classes=[IsModeratorOfThePageOwner] ) def block(self, request, pk=None): self._block_page(pk) return Response( data={"detail": "Successfully blocked."}, status=status.HTTP_200_OK, ) Permissions_classes don't work. If I change the permission class to the has_permission class then everything is Okay. But If pass permissions classes with has_object_permission then It doesn't work. My permission class: class IsModeratorOfThePageOwner(BasePermission): def has_object_permission(self, request, view, obj): return bool( request.user_data and request.user_data.get("role") == "Moderator" and obj.owner_group_id == request.user_data.get("group_id") ) -
Django, The static files (CSS, fonts) uploaded to the media folder from external sources cannot be used from the media folder
I have an index.html file and a verdana.ttf font file uploaded within a zip file. I use this font embedded in index.html as they are in the same folder. I provide a relative path like this: @font-face { font-family: Verdana_Bold; src: url(verdana.ttf); } If I provide a font file from a remote server as the src, it works. However, it cannot access a locally available file (in the media folder). I've tried some possibilities like: /media/verdana.ttf /code/media/verdana.ttf (my root directory structure due to Docker usage) But it always gives the error: 'The joined path (/media/verdana.ttf) is located outside of the base path component (/usr/local/lib/python3.8/site-packages/django/contrib/admin/static).' I want to dynamically provide HTML template files, including font and CSS static files from an external source and use them. My goal is to generate PDFs from HTML templates. I've created a service for users to create their own templates. Maybe moving the file to the static folder after uploading and running the 'python manage.py collectstatic' command might work. I haven't tried that yet, but I would prefer not to use this solution -
How to bulk_create in django using MySQL
Does not return ID when using bulk_create method. PostgreSQL returns the ID, but MySQL does not. Is there a way to create a temporary ID and solve it? bar_list = [] foo_list = [] for i in range(3): foo = Foo(body="text") foo.temp_id = uuid.uuid4() foo_list.append(foo) bar = Bar(foo_temp_id=foo.temp_id, body="text") bar_list.append(bar) Foo.objects.bulk_create(foo_list) # The query sets are created, but the ID is None Bar.objects.bulk_create(bar_list) # Error occurred because the ID of the referring foo is None -
EC2 with Cloudflare
I have an EC2 Ubuntu instance with the Cloudflare's nameservers. It's a Django app. The instance is running nginx and supervisor gunicorn. The instance has a security group with the IPs range from Cloudflare. These inbound rules are for port 443 only because I have an SSL certificate: This is my django.conf: After a test my certificate is not working: And I cannot access my webpage: I need help, please. Probably is something obvious but I don't understand. -
I am writing a single login app using react and django but i cant send anything from the front end to the backend. it gives me 403 error
i want to know how to send the csrf token. i searched but i coudn't know how. here is my code I want to send the username and the password to the backend from here const LoginPage = () => { const [username , setUsername] = useState('') const [password , setPassword] = useState('') const handlelogin = async () => { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); await fetch('http://localhost:8000/auth/login' , { method : "POST" , headers : { "X-CSRFToken" : csrftoken }, body : { " username" : username , "password" : password } } ).then(res => res.json()).then(data => console.log(data)) } return ( \<div\> \<div className=" mx-auto"\> <h1 className=" font-bold sm:text-2xl md:text-3xl p-6 font-serif"> Tailwindcss Login Card</h1> <div className="card" > <label className=" font-bold">Username:</label> <input type="text" placeholder="Enter username" className="inputs" onChange={(e)=>{ setUsername(e.target.value)}} /> <label className=" font-bold">Password:</label> <input type="password" placeholder="Enter password" … -
React & cloudflare image upload Fail.. ㅠ ㅠ Please help me
I am doing web development with Django and React. I was working on implementing a feature to upload images using CloudFlare. My code is like the image picture. [this is the React and api File] I saw the error below: ERROR in src/routes/UploadPhotos.tsx:51:7 TS2322: Type '() => Promise' is not assignable to type 'MutationFunction<IUploadURLResponse, void>'. Type 'Promise' is not assignable to type 'Promise'. I cannot solve this problem alone due to my limited abilities. Please help me I cannot solve this problem alone due to my limited abilities. Please help me -
django-tables2: sorting does not function on a table of related data
I have two classes: Project which has a many-to-one relationship with Client. I would like my detailed template of Client to display a list of projects. The code below successfully gets the required Projects, and stores them in context, which is then passed to the template renderer which renders them successfully. So far, so good. But the rendered table will not "sort" the data successfully. I can click on the headers, which will add ?sort=name to the request, but nothing happens. Is this the correct approach for what I am intending, and if so, what step am I missing to get the full functionality? models.py class Client(models.Model): name = models.CharField("Name", max_length=300, unique=True) class Project(models.Model): client = models.ForeignKey("Client", on_delete=models.RESTRICT) name = models.CharField("Name", max_length=300, unique=True) tables.py import django_tables2 as tables from .models import * class ProjectTable(tables.Table): class Meta: model = Project template_name = "django_tables2/bootstrap.html" fields = ("name", ) views.py class ClientDetailView(DetailView): model = Client def get_context_data(self, **kwargs): # Get related Projects and put then in 'table' table = ProjectTable(self.object.project_set.all()) # Add 'table' to 'context' context = super(ClientDetailView, self).get_context_data(**kwargs) context['table'] = table return context html {% load render_table from django_tables2 %} {% render_table table %} -
How to create an import-export using Rest Framework in Django?
I don't know how to create the import-export an excel file using the Rest Framework in Django. I haven't seen any article and any tutorial that related on import-export rest framework. Here is my html code in import Asset List Import \ \ \ <div class="content-wrapper"> <section class="content"> <div class="row"> <div class="col-sm-6"> <h4 class="font-weight-bolder">Asset List Import</h4> </div> </div> </section> <section class="content pb-4"> <div class="row"> <div class="col-12 col-sm-12"> <div class="card"> <div class="card-header d-flex align-items-center px-3 py-2"> <div class="card-title"> Import file </div> </div> <div class="card-body"> <div class="col-md-6 offset-md-3 mt-5"> <div class="card"> <div class="card-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="file">Choose CSV file</label> <input class="form-control col" type="file" name="file" accept=".csv, .xlsx"> </div> <button type="submit" class="btn btn-cyan mt-3">Import</button> </form> </div> </div> </div> </div> </div> </div> </div> <!--Start Card Footer ---> <div class="card-footer float-end"> <a class="btn btn-outline-cyan" href="{% url 'asset_list' %}">Cancel</a> </div> <!--End Card Footer ---> <section> </div> I want this import will function and I can import-export an excel file. -
Django rest how to serializers all child comment under it's parent comment
Now my API response look like this "results": [ { "id": 12, "blog_slug": "rest-api-django", "comment": "Parent Comment", "main_comment_id": null }, { "id": 13, "blog_slug": "rest-api-django", "comment": "Child Comment of 12", "main_comment_id": 12 }, { "id": 14, "blog_slug": "rest-api-django", "name": "Mr Ahmed", "comment": "Child Comment OF 13", "comment_uuid": "c0b389bc-3d4a-4bda-b6c6-8d3ef494c93c", "main_comment_id": 13 } ] I want something like this { "results": [ { "id": 12, "blog_slug": "rest-api-django", "comment": "Parent Comment", "main_comment_id": null, "children": [ { "id": 13, "blog_slug": "rest-api-django", "comment": "Child Comment of 12", "main_comment_id": 12, "children": [ { "id": 14, "blog_slug": "rest-api-django", "name": "Mr Ahmed", "comment": "Child Comment OF 13", "comment_uuid": "c0b389bc-3d4a-4bda-b6c6-8d3ef494c93c", "main_comment_id": 13 } ] } ] } ] } so each child will be under its parent. here is my mode class BlogComment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) blog_slug = models.CharField(max_length=500) main_comment_id = models.ForeignKey("self",on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=250) email = models.CharField(max_length=250) comment = models.TextField() is_published = models.BooleanField(True) comment_uuid = models.CharField(max_length=250) my BlogCommentSerializers class BlogCommentSerializers(serializers.Serializer): id = serializers.IntegerField(read_only=True) comment_uuid = serializers.CharField(read_only=True) blog_slug = serializers.CharField(max_length=500) main_comment_id = serializers.CharField(required=False) name = serializers.CharField(max_length=250) email = serializers.CharField(max_length=250) comment = serializers.CharField(style={'base_template': 'textarea.html'},allow_blank=False,required=True) is_published = serializers.BooleanField(default=True) def to_representation(self, instance): data = { 'id': instance.id, 'blog_slug': instance.blog_slug, 'name': instance.name, 'email': instance.email, 'comment': instance.comment, "comment_uuid": instance.comment_uuid, "main_comment_id": instance.main_comment_id } if instance.main_comment_id: … -
Django logging output that doesn't seem to be part of root
I'm trying to understand Django's logging output so I've separated out all the core django loggers (django, django.request, django.db.backend, core, django.template) and set their levels to WARNING and gave it it's own formatter to make it more easily distinguishable from the rest. I've also overridden the root logger, set it to debug and made a similar easy to notice formatter for it. So now I get stuff like this: 127.0.0.1:99999 - - [08/Nov/2023:00:50:06] "GET /static/frontend/main.js" 304 - ROOT CRAP ! >>>>>>> [2023-11-07 16:50:10] - daphne.http_protocol - HTTP response complete for ['127.0.0.1', 99999] 127.0.0.1:99999 - - [08/Nov/2023:00:50:10] "GET /api/auth/user" 200 606 ROOT CRAP ! >>>>>>> [2023-11-07 16:50:12] - daphne.http_protocol - HTTP 200 response started for ['127.0.0.1', 99999] ROOT CRAP ! >>>>>>> [2023-11-07 16:50:12] - daphne.http_protocol - HTTP close for ['127.0.0.1', 99999] ROOT CRAP ! >>>>>>> [2023-11-07 16:50:12] - daphne.http_protocol - HTTP response complete for ['127.0.0.1', 99999] 127.0.0.1:99999 - - [08/Nov/2023:00:50:12] "POST /sg/query/user_tasks" 200 6001 But I still don't know where those REST logs are originating from (ie the ones that don't say ROOT CRAP!). I assumed they'd be a part of the root log stream but apparently they aren't? Is there another Django-level logger that I've not accounted for. These are … -
Can you help me ? my application display an error (500)
I have a problem: my django application display an error 500. I rolled back to a version that is working on heroku, pull the code, but when i push just by changing a in my html file into heroku, i got again an error 500, the logs telling me anything. Someone got an idea about what's going on ? Thank u by advance ! Rolled back, pull the code and i was expecting that works -
How to run some vps together with database in another server?
I need to run django site and some scripts together on vps server. But scripts has a large load on the server. Therefore, I assume creating 4 VPS, 1 for the site, the second for the database and the remaining 2 for scripts. And i need to somehow connect them to the database. What technology can be used to achieve this? As I understand it, large companies use several servers to distribute loads, I want to do the same. I only have experience installing Django with postgresql on Nginx with Gunicorn on one vps -
failed to authenticate multiple user in django
I have multiple user models in my Django app, one for OLAROOM and the other one for REALTOR. As you can see, everything is working successfully, but when I try to authenticate them and redirect them based on their role, it does not work. The authentication is working fine, but instead of redirecting the Olaroom user to the Rooms page, it is redirecting me to the Realtor_Dashboard, and the user role isn't a Realtor. Using the form below, the user is created based on what is defined in the save function. However, when I try to authenticate them and redirect the user to the page based on their role, it doesn't work, and I'm using the same method, something like this: user.Role.REALTOR and user.Role.OLAROOM. How can I solve this problem please? def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.Role.REALTOR: auth_login(request, user) return redirect('Realtor_Dashboard') elif user.Role.OLAROOM: auth_login(request, user) return redirect('Rooms') else: messages.error(request, 'Invalid Creadentials') else: form = AuthenticationForm() return render(request, 'Login/login.html', {'form':form}) User Models class User(AbstractUser): class Role(models.TextChoices): ADMIN = "ADMIN", 'Admin' REALTOR = "REALTOR", 'Realtor' OLAROOM = "OLAROOM", 'Olaroom' base_role … -
Django WSGI with Gunicorn does not find settings
I am following the tutorial to dockerize a django application with associated github code. My problem is when I try to start the application using gunicorn, the application = get_wsgi_application() line of wsgi.py fails with: [2023-11-07 20:05:13 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2023-11-07 20:05:13 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2023-11-07 20:05:13 +0000] [1] [INFO] Using worker: sync [2023-11-07 20:05:13 +0000] [37] [INFO] Booting worker with pid: 37 [2023-11-07 20:05:13 +0000] [37] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/local/lib/python3.10/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 "/mpp/mpp/mpp/wsgi.py", line 20, in <module> application … -
Custom token authentication with Django and Firebase
Sure, here's a sample Stack Overflow question for the problem of custom token authentication with Django and Firebase: Title: Custom token authentication with Django and Firebase Problem: I'm trying to implement custom token authentication with Django and Firebase. I've followed the steps in the documentation, but I'm still having trouble getting it to work. When I try to sign in with the custom token, I get an error that says "Invalid custom token." `# Django server code from django.contrib.auth import authenticate, login from rest_framework import permissions, views, status from firebase_admin import auth class CustomTokenLogin(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): username = request.data.get('username') password = request.data.get('password') if username is None or password is None: return Response({'error': 'Missing username or password'}, status=status.HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if user is not None: login(request, user) # Create a custom token using Firebase Admin SDK custom_token = auth.create_custom_token(user.uid) return Response({'token': custom_token}) else: return Response({'error': 'Invalid username or password'}, status=status.HTTP_401_UNAUTHORIZED) for verify token ' class ProfileView(APIView): def get(self, request): try: decoded_token = auth.verify_id_token(request.headers.get('Authorization', '')) user_id = decoded_token['uid'] user = User.objects.get(id=user_id) # Fetch the user from the database # Fetch user profile data profile_data = { 'username': user.username, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name # Include … -
Custom Django Model User
I can´t seriualize this class : class RidesSerializer(serializers.ModelSerializer): passageiros = CarregaDadosPassageirosSerializer(many=True, required=False,read_only=True) passageiros_id = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=User.objects.all(),source='passageiros') class Meta: model = Ride fields = ['motorista','passageiros','passageiros_id','data_publicaçao', 'data_saida','origem','destino','preço','veiculo','modalidade'] wich brigs this other class , 'CarregaDadosPassageirosSaerializer', and i need to extend a field to the model User : class CarregaDadosPassageirosSerializer(serializers.ModelSerializer): class Meta: diretorio = serializers.ImageField(source='user.profile.diretorio',read_only=True) nome_usuario = serializers.SerializerMethodField() model = User fields = ['id','username','email','diretorio'] def get_nome_usuario(self, obj): return obj.nome.username The error in the output i´ve been receiving everytime is the following : 'Field name diretorio is not valid for model User'. So, how can i fix this ? I've tried changing some aspects in models.accounts : user = mo.OneToOneField(User,related_name='userprofile',on_delete=mo.CASCADE) -
Failed building wheel for twisted-iocpsupport
I'm trying to dockerize my django project. When i run "docker build -t django_project" i get following error: 18.82 Building wheel for twisted-iocpsupport (pyproject.toml): started 19.23 Building wheel for twisted-iocpsupport (pyproject.toml): finished with status 'error' 19.24 error: subprocess-exited-with-error 19.24 19.24 × Building wheel for twisted-iocpsupport (pyproject.toml) did not run successfully. 19.24 │ exit code: 1 19.24 ╰─> [13 lines of output] 19.24 running bdist_wheel 19.24 running build 19.24 running build_ext 19.24 building 'twisted_iocpsupport.iocpsupport' extension 19.24 creating build 19.24 creating build/temp.linux-x86_64-cpython-39 19.24 creating build/temp.linux-x86_64-cpython-39/twisted_iocpsupport 19.24 gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -Itwisted_iocpsupport -I/usr/local/include/python3.9 -c twisted_iocpsupport/iocpsupport.c -o build/temp.linux-x86_64-cpython-39/twisted_iocpsupport/iocpsupport.o 19.24 twisted_iocpsupport/iocpsupport.c:1210:10: fatal error: io.h: No such file or directory 19.24 1210 | #include "io.h" 19.24 | ^~~~~~ 19.24 compilation terminated. 19.24 error: command '/usr/bin/gcc' failed with exit code 1 19.24 [end of output] 19.24 19.24 note: This error originates from a subprocess, and is likely not a problem with pip. 19.24 ERROR: Failed building wheel for twisted-iocpsupport 19.24 Successfully built autobahn 19.24 Failed to build twisted-iocpsupport 19.24 ERROR: Could not build wheels for twisted-iocpsupport, which is required to install pyproject.toml-based projects 19.70 19.70 [notice] A new release of pip is available: 23.0.1 -> 23.3.1 19.70 [notice] To update, run: pip … -
Dynamically add select fields Django form
I have a model whose values are linked by a many-many field class Structure(models.Model): structure_id = models.CharField(max_length=100,) drawings = models.ManyToManyField(Drawing, related_name="structures") I am trying to create a form that allows me to dynamically add structures and drawings, where each drawing must be from existing drawings. With formsets I am able to create multiple forms for 1 structure 1 drawing, but I want to be able to have multiple drawing per structure Goal is to display the inputs in the following layout How do I create a form that allows me to add multiple drawings using select -
I can't receive an email from Django Forms
I am developing a Django project. In my project, there is a form, and when I fill out the form, I can see it on the admin page. What I want to do is to receive an email notification when someone fills out the form, saying that a new form has been submitted. However, I am failing in this regard. Where is my mistake? Here is my Views.py def contact(request): if request.method == 'POST': form = ContactFormForm(request.POST) if form.is_valid(): form.save() subject = 'New Form Submitted' # message = form.cleaned_data['amessage'] message = 'There is a new form:\n\n' + \ f'Name: {form.cleaned_data["name"]}\n' + \ f'-mail adress: {form.cleaned_data["email"]}\n' + \ f'phone number: {form.cleaned_data["phone"]}\n' + \ f'call at: {form.cleaned_data["call_time"]}\n' try: email_from = EMAIL_HOST_USER recipient_list = ['xxx@mail.com'] html_message = render_to_string('contact.html', {'message': message}) msg = EmailMessage(subject, html_message, email_from, recipient_list) msg.content_subtype = "html" msg.send() except ValueError: return HttpResponse('Invalid header found.') else: form = ContactFormForm() return render(request, 'contact.html', {'form': form}) And Here is my settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.yandex.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'XXX' EMAIL_HOST_PASSWORD = 'XXX' DEFAULT_FROM_EMAIL = 'XXX' EMAIL_USE_TLS = True -
UseEffect in React Components in Django App
I am trying to use react components within a Django app. Single components should bei integrated within an HTML. In the first step it is working: the react components are beeing rendered and everything looks fine. The problem: I have a component let's say a table, where lets say Artikel/ price data are rendered. Now due to another non-React functionality new data are uploaded from the users desktop. Of course the table should be re-rendered. But how can this be managed? I tried to solve it with useEffect and a global variable. Apart from the fact that this seems to be a anti-pattern it simply doesn't work. So the question is, how can I solve this problem? I don't have an idea. I tried any kind of research and manipulation around the usage of global variables within this context. Unfortunately without any result. -
DJango captcha Error messages getting duplicated
my captcha error messages get duplicated my template error display code: {% if form.non_field_errors %} {% for error in form.non_field_errors %} <h3 style = "color:red;text-align:center">{{ error }}</h3> {% endfor %} {% elif messages %} {% for message in messages %} <h3 class = "{% if message.tags == 'success' %} message-green {% elif message.tags == 'error' %} message-red {% endif %}" style = "text-align:center">{{message}}</h3> {% endfor %} {% endif %} and my views: def Insertvalue(request): if request.method == "POST": form = EmpInsertForm(request.POST) if form.is_valid(): form.URL = request.POST.get('URL') form.email = request.POST.get('email') form.save() messages.success(request,'Info saved. Be on the lookout for a confirmation e-mail') else: messages.error(request,'Captcha not cleared. Please try again.') return render(request,'Index.html',{"form":form}) else: form = EmpInsertForm() return render(request,'Index.html',{"form":form}) the messages.error is the one that gets duplicated. to reproduce it, I first have to get the non field error which is bascally a unique_together error, and then get the captcha error and it will be printed as many times as I got the non field error + 1. Is there any way to delete all messages in the messages array if non field error is raised? Thank you in advanced.