Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Responsive Navbar Link is not working on mobile device
I developed my first website using django. It works perfect on desktop, but on mobile device the category submenu links are not working. When clicked they act like I clicked on white space and close the navbar. Note: the Intital links work on mobile too. The children of the categories are not working. I though about z-index but the parent links are working. Here are the codes: <div id="responsive-nav"> <!-- category nav --> {% if page %} <div class="category-nav"> {% else %} <div class="category-nav show-on-click"> {% endif %} <span class="category-header">{% trans "Categories" %} <i class="fa fa-list"></i></span> {% load myapptags %} {% categorylist as category %} {% load mptt_tags %} <ul class="category-list"> {% recursetree category %} <li class="dropdown side-dropdown"> <a href="{% url 'category_products' node.id node.slug %}" class="dropdown-toggle" {% if not node.is_leaf_node %} data-toggle="dropdown" aria-expanded="true" {% endif %}>{{ node.title }} <i class="fa fa-angle-right"></i></a> <div class="custom-menu"> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </div> </li> {% endrecursetree %} </ul> </div> my apptag @register.simple_tag def categorylist(): return Category.objects.all() css of mobile @media only screen and (max-width: 991px) { #responsive-nav { position: fixed; left: 0; top: 0; bottom: 0; max-width: 270px; width: 0%; overflow: hidden; background-color: #FFF; -webkit-transform: … -
path('', views.IndexView.as_view(), name='index'), AttributeError: module 'polls.views' has no attribute 'IndexView'
how to solve this : i am using generic views method in django and facing this error while creating my first poll app ... path('', views.IndexView.as_view(), name='index'), AttributeError: module 'polls.views' has no attribute 'IndexView' my urls.py : urlpatterns = [ path('', views.IndexView.as_view(), name='index'), # ex: /polls/5/ path('<int:pk>/', views.DetailView.as_view(), name='detail'), # ex: /polls/5/results/ path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] -
venv dependencies are being added without being downloading
I use virtual environments in my django projects. I create my projects like this python3 -m venv <name of venv> After I pip install django in the venv, I use the pip list command. At this point the list only contains the default django packages. Then I start my django project like this. django-admin startproject <name of project> After that when I add the venv folder to my project folder, and run pip list again, all dependencies from previous projects are being added to the list. I can't figure out why this is happening. -
How can I enter numbers in the bar on the django form?
What you want to achieve I want to input numbers in the django form like this. Current code class Comment_movie_CreateForm (ModelForm): class Meta: model = Comment_movie fields = ('comment','stars') comment = forms.CharField (required = False, label ='comment', max_length = 1000) stars = forms.FloatField (required = False, label ='stars', widget = forms.TextInput ( attrs = {'type':'number','id':'form_homework', "class": "no_resize",'min': '0','max': '10','step': '0.1' }))) def clean (self): cleaned_data = super (). clean () return cleaned_data def clean_stars (self): stars = self.cleaned_data ['stars'] if stars! = None: if stars <0 or stars> 10: raise forms.ValidationError ("The rating input is incorrect.") return stars else: else: raise forms.ValidationError ("The rating input is incorrect.") def clean_comment (self): comment = self.cleaned_data ['comment'] if len (comment)> 1000: raise forms.ValidationError ("There are too many characters.") elif len (comment) == 0: raise forms.ValidationError ("Please enter the characters.") return comment def __init__ (self, * args, ** kwargs): super () .__ init__ (* args, ** kwargs) self.label_suffix = "" <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} {% if comment_tv %} <button type="submit">Edit Comment</button> <button type="submit" name="action" value="delete">Delete Comment</button> {% else %} <button type="submit">Post Comment</button> {% endif %} </form> What you want to ask How would you change it to look like … -
Django admin panel: How to show Form instead of the data list?
I have a simple project built with Django, and I need to add some settings to my project. I have created the settings model, but what I want is to hide the data, and when a user opens the settings page it shows the form to add or update the settings data, without showing the date list, because settings are always one object that will be created once and updated as needed. This is my simple settings model. class ConfigSettings(models.Model): """ This model is used to store the configuration settings for the application. """ use_invoice_terms = models.BooleanField( default=False, help_text=_('Add your terms & conditions at the bottom of invoices/orders/quotations') ) and this is how I registered the model class in the admin file. @admin.register(ConfigSettings) class ConfigSettingsAdmin(admin.ModelAdmin): pass -
how to set non-database field on a model in django
i want to set / update calculated field on a model, with a different value on each object. for example, i have a User model, and i want to set a name property on each user, where name is not a column on the DB and it can't be edited by the user. the names can come from get_all_users_names() or from get_name_by_user_id(id). where should i set it and how should i set it? im new with python so please share some code :) thanks -
How to save media files to Heroku local storage with Django?
Im having a Django REST app with React for client. Im recording a file with React and sending in to Django. When i save it i modify it with ffmpeg and save it again in the same folder with a new name, the ffmpeg command looks like this: os.system(f"ffmpeg -i {audio_path} -ac 1 -ar 16000 {target_path}") Because i need a path for my audio both for opening and saving, i can't use cloud stores like "Bucket S3, Cloudinary etc.". And the fact that im using it only for a few seconds and then deleting it makes Heroku (the app is deployed there) the perfect place to save it non-persistent. The problem is that the file isn't getting saved in my library with media files. It saves in the postgre db but doesn't in my filesystem and when i try to access it my program returns that there isn't a file with that name. My question is How can i save media files in Heroku file system and how to access them? settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'EmotionTalk/AI_emotion_recognizer/recordings') MEDIA_URL = '/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('EmotionTalk.emotion_talk_app.urls')), path('auth/', include('EmotionTalk.auth_app.urls')), path('api-token-auth/', views.obtain_auth_token), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def … -
AttributeError: module 'django.db.models' has no attribute 'Aqtau'
I work with django first time. And fced with this error. Can You help me to solve. Erro like this, I have many models and data in there, and I put this data to html like table, after I want to change values in data, but in views I cant search my models My models py like this: (in city_name I put name of Model there it is Aqtau ) from django.db import models class Aqtau(models.Model): city_name = models.CharField(max_length=255) KT_by_projects_10g = models.CharField(max_length=255) KT_by_projects_100g = models.CharField(max_length=255) KT_on_facts_10g = models.CharField(max_length=255) KT_on_facts_100g = models.CharField(max_length=255) My views to put data to html: def index(request): Aqtau_city = Aqtau.objects.all().values() template = loader.get_template('index.html') context = { 'Aqtau_city': Aqtau_city, } return HttpResponse(template.render(context, request)) HTML looks like: <tr> {% for x in Aqtau_city %} <td>Aqtau</td> <td>{{ x.KT_by_projects_10g }} </td> <td>{{ x.KT_by_projects_100g }} </td> <td>{{ x.KT_on_facts_10g }} </td> <td>{{ x.KT_on_facts_100g }} </td> <td><a href="update/{{ x.city_name }}/{{ x.id }}">update</a></td> {% endfor %} </tr> urls.py looks like: urlpatterns = [ path('', views.index, name='index'), path('update/<str:city_name>/<int:id>', views.update, name='update'), And views update like: There i want to get model by getattr, but django db.models don't search Aqtau class. def update(request, city_name, id): model = getattr(models, city_name) mymember = model.objects.get(id=id) template = loader.get_template('update.html') context = { … -
django "makemigrations" problem not working
08:41 ~/myapk $ python manage.py makemigrations Traceback (most recent call last): File "/home/chaxim/myapk/manage.py", line 22, in <module> main() File "/home/chaxim/myapk/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute _from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 228, in create if not issubclass(app_config_class, AppConfig): TypeError: issubclass() arg 1 must be a class everytime i tried to make migrations it shows same thing, i even tried export DJANGO_SETTINGS_MODULE=yoursite.settings command but no result. -
Using Telegram Bot with Django
I am trying to use my telegram bot with Django. I want the code to keep running in the background. I am Using the apps.py to do this but there's one problem when the bot starts as it's an infinite loop, the Django server is never started. Apps.py: from django.apps import AppConfig import os class BotConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'bot' def ready(self): from . import jobs if os.environ.get('RUN_MAIN', None) != 'true': jobs.StartBot() Jobs.py: def StartBot(): updater = Updater("API KEY") dp = updater.dispatcher dp.add_handler(ChatMemberHandler(GetStatus, ChatMemberHandler.CHAT_MEMBER)) updater.start_polling(allowed_updates=Update.ALL_TYPES) updater.idle() What's the best way to run my bot in the background? while making sure that the Django server runs normally. I tried Django background tasks but it's not compatible with Django 4.0. -
Setup Django Push notification for web only?
I want to setup push notification for website. I just follwed as described in documenation but Unfurtunately it is now working. Here is my settings. PUSH_NOTIFICATIONS_SETTINGS = { "WP_PRIVATE_KEY": BASE_DIR / 'private_key.perm', "WP_CLAIMS": {'sub': "mailto: development@example.com"} } and here is my client side code, I just copy this code from documentation ..... <h1>Push Notification Example</h1> <script> ............... ........... var applicationServerKey = "...."; // In your ready listener if ('serviceWorker' in navigator) { // The service worker has to store in the root of the app // http://stackoverflow.com/questions/29874068/navigator-serviceworker-is-never-ready var browser = loadVersionBrowser('chrome'); navigator.serviceWorker.register('navigatorPush.service.js?version=1.0.0').then(function (reg) { reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(applicationServerKey) }).then(function (sub) { var endpointParts = sub.endpoint.split('/'); var registration_id = endpointParts[endpointParts.length - 1]; var data = { 'browser': browser.name.toUpperCase(), 'p256dh': btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('p256dh')))), 'auth': btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('auth')))), 'name': 'XXXXX', 'registration_id': registration_id }; console.log(data); }) }).catch(function (err) { console.log(':^(', err); }); } and here is error snippets. I don't know what I'm missing??. -
django-pgroonga installation error: "UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 112: character maps to <undefined>"
I need to use Japanese characters with vector searches in Django / Postres. I am trying to install django-pgroonga and keep getting the same encoding error with cp1252.py: PS C:\JGRAM\JLPT> pip install django-pgroonga Collecting django-pgroonga Using cached django-pgroonga-0.0.1.tar.gz (3.7 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [10 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\61458\AppData\Local\Temp\pip-install-21w4o7u8\django-pgroonga_87013717bf0e4bcca83db91a993082b4\setup.py", line 17, in <module> long_description=read('README.rst'), File "C:\Users\61458\AppData\Local\Temp\pip-install-21w4o7u8\django-pgroonga_87013717bf0e4bcca83db91a993082b4\setup.py", line 6, in read return open(os.path.join(os.path.dirname(__file__), fname)).read() File "C:\Users\61458\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] **UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 112: character maps to <undefined>** [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. PS C:\JGRAM\JLPT> Can you help? I cannot find a solution online that outlines how to resolve this error when it occurs 'during installation'. I have tried updating the cp1252.py file, copying and … -
Django admin change view not change in linux
I have a change for the model in the templates folder, I added a button to object tools. In Windows, the change works without a problem; on Linux, the change cannot be seen. I restarted nginx, gunicorn. I tried collections static and it didn't help. I put the same version of django on linux also didn't help. -
How to create default filter on django queryset
I have below model in my django app. class Segment(BaseSegmentModel): payload_json = JSONField(null=True, default=None, blank=True) owner = models.ForeignKey(CustomUser, null=True, blank=True, on_delete=models.SET_NULL, related_name='segments') name = models.CharField(max_length=100, null=True, blank=False) status = models.CharField(max_length=100, null=True, blank=True, choices=SegmentStatuses.choices, default=SegmentStatuses.STOPPED) created_date = models.DateTimeField(null=True, auto_now_add=True)as There is a field status which has three values, Active Running Archive I need to add a default filter on this model where it should not show any results with status = Archive So whenever someone query this model it should not show any Archive results. -
Django-notifications-hq How to live update notifications to read
I've spent all day scouring a few versions of docs for this plugin, I've read through all of the tutorials I can find, and I went through every file in the repo to make note of all of it's parts. This ajax aspect is what I'm struggling with. my example is essentially this getting started tutorial, I just customized the html output by overwriting the fill_notification_list javascript function: https://pypi.org/project/django-notifications-hq/ I have the notifications outputting into my template and have written a function for overwriting the default notifications javascript function. It's just a list of the notifications as text items. I want to mark all of the notifications "unread=False" when the alerts dropdown is clicked. I know I'm supposed to ping a url on my app to set the notifications to read and then update the list using ajax. I started with: $('.sh-alert-btn').on('click touch', function(){ $.get('{% url "notifications:mark_all_as_read" %}', function(response) { }); }); but I realized I don't know what to do at this point. This is my custom fill_notification_list function: function streamshiv_notify(data) { var menus = document.getElementsByClassName('live_notify_list'); if (menus) { var messages = data.unread_list.map(function (item) { if(typeof item.verb !== 'undefined'){ message = message + '<h6>' + item.verb + "</h6>"; } … -
Why does my django allow downloading files outside of static folder?
My django project allows downloding images from static folder: http://0.0.0.0:8001/static/img/login.png This makes sense. But what concerns me is that it also allows me downloading files even outside of the static folder such as: http://0.0.0.0:8000/logs/result.log or even worse: http://0.0.0.0:8000/users/models.py All my local files can be downloaded via clients. This is a high security vulnerability. No matter what is the permission of my folders on my Linux server. I do not have such items in my path and I do not expect these paths being served. How can I fix this? BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True INSTALLED_APPS = [ 'comments', 'home', 'users', 'articles', 'notifications', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'static_precompiler', 'django_markup', 'django_minify_html', 'django_rename_app', ] MIDDLEWARE = MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_minify_html.middleware.MinifyHtmlMiddleware', ] ROOT_URLCONF = 'profplus.urls' TEMPLATES = TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'profplus.wsgi.application' STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_FINDERS = STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'static_precompiler.finders.StaticPrecompilerFinder', ] -
Celery doesn't start with Django 4.0
I have upgraded from Django 2.2 to 4.0, and even though the application works fine, celery doesn't start, it only displays the Celery logo, no text, no errors. My application has some tasks.py files in different modules. According to Celery's website, everything is set up fine. I even tried the debug_task example to test it, but I am getting the same result. My celery.py file inside proj/ is the following: import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings.production') app = Celery( 'proj', backend='amqp', broker='amqp://guest@localhost:5672//' ) app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Then, as mentioned in the official documentation, my proj/init.py is the following: from .celery import app as celery_app __all__ = ('celery_app',) -
Best way to create a unique URL to 'check-in' [Django]
I am needing to have a simple way for employees to 'check-in' to work by scanning a QR code that would be regenerated daily that would be available at the office. The qr code would take them to a page where they click 'check-in' in order to get credit for attendance. Where I'm getting stuck is that I would like is that there wouldn't be an easily sharable URL that employees could just send to one another. I've thought of having some kind of URl redirect but it seems like there would be a better solution. -
Django Query with 3 related tables
I'm hoping I can get a little guidance. I'm trying to return data from 3 related tables in my template. In SQL, this is a simple approach, but the Django requirements have me stumbling. I'd like to display information similar to this: WaiverAdult.first_name CheckIn.checkintime WaiverMinor.first_name CheckIn.checkintime WaiverAdult.first_name CheckIn.checkintime WaiverMinor.first_name CheckIn.checkintime WaiverMinor.first_name CheckIn.checkintime Here are a simplified representation of the models with the relationships defined. class WaiverAdult(models.Model): first_name = models.CharField(max_length=50, blank=True) class WaiverMinor(models.Model): first_name = models.CharField(max_length=50, blank=True) parent = models.ForeignKey(WaiverAdult, on_delete=models.CASCADE) class CheckIns(models.Model): adult = models.ForeignKey(WaiverParent, on_delete=models.CASCADE, blank=True, null=True) minor = models.ForeignKey(WaiverChild, on_delete=models.CASCADE, blank=True, null=True) checkintime = models.DateTimeField(auto_now_add=True) Here is my simplified view: class WaiverListView(ListView): waiver_adults = WaiverAdult.objects.all().prefetch_related( 'waiverminor_set').order_by('created') queryset = waiver_adults context_object_name = "waiver_list" template_name = 'waiver/waiver_list.html' And, this is my template. {% for adult in waiver_list %} <tr> <td>{{adult.first_name}}</td> <td>insert the adult checkin time here</td> </tr> {% for child in adult.waiverminor_set.all %} <tr> <td>{{child.first_name}}</td> <td>insert the child checkin time here</td> </tr> {% endfor %} {% endfor %} I would be very appreciative of details in the explanations as I really want to understand how this all works. Thank you in advance. -
Django: view not working, when i redirect to the view it failed to load the page?
I am trying to redirect to a callback view in django but it seems not to be working, the urls.py looks okay, but it keeps failing. i have a view investmentDetail that is getting the purchased_package_id , now the purchased package id is what i use to keep track of the particular payment that is being processed and i have passed in the purchased_package_id as parameter to my function, so i can do something with it in the urls, views body e.t.c but it seems that the purchased_package_id isn't working as expected and i cannot really tell what is broken? views.py def investmentDetail(request, slug): investment = InvestmentPackage.objects.get(active=True, slug=slug) if request.method == "POST": purchased_package = PurchasedPackage.objects.create(user=request.user, investment_package=investment ) purchased_package_id = purchased_package.id name = request.POST.get("name") email = request.POST.get("email") amount = request.POST.get("amount") return redirect(str(process_payment(name,email,amount, investment, purchased_package_id))) else: pass context = { "investment":investment, } return render(request, "core/investment-detail.html", context) def process_payment(name,email,amount, investment, purchased_package_id): auth_token= settings.FLUTTER_SECRET_KEY hed = {'Authorization': 'Bearer ' + auth_token} data = { "tx_ref":''+str(math.floor(1000000 + random.random()*9000000)), "amount":amount, "currency":"NGN", "redirect_url":f"http://localhost:8000/callback/{purchased_package_id}/", "payment_options":"card", "meta":{ "consumer_id":23, "consumer_mac":"92a3-912ba-1192a" }, "customer":{ "email":email, "name":name }, "customizations":{ "title":"Investment Platform", "description":" Limitless Learning For Everyone", "logo":"https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" } } url = ' https://api.flutterwave.com/v3/payments' response = requests.post(url, json=data, headers=hed) response=response.json() link=response['data']['link'] return link @login_required … -
import 'django' couldn't be resolved from source (VSCode)
I want to configure properly VSCode for working with Django but I get an error when I try to import any module from Django. I've researched many other similar questions but it doesn't solve it. One of the most popular answers is that the Python Interpreter should be the one inside my Virtual Environment in where I have Django installed. Inside the bin folder of my virtual environment I have three Python shortcuts (Python, Python3 and Python3.6). Any of them will solve the import error. Also, inside my project I have a file called pyvenv.cfg that looks like this. If I try to select the interpreter from that same path (the one in home) the import error still appears. How should I configure my Python interpreter in order that it recognizes all the Django imports? -
django model.objects.values() return related id instead of title
I want to get Chapter model data as json , i used values() method and it works but it return book id not the book title and i want the book title models.py class Books(models.Model): title = models.CharField(max_length=200 , unique=True) slug = models.SlugField(max_length=255,unique=True) data_id = models.IntegerField(unique=True) def __str__(self): return str(self.title) class Chapter(models.Model): book_id = models.ForeignKey(Books,on_delete=models.CASCADE) source = models.CharField(max_length=100,blank=True) chapter = models.CharField(max_length=10) date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.chapter)+" "+str(self.book_id) views.py class BookChapters(LoginRequiredMixin,View): def get(self,request): chapters = Chapter.objects.values() return JsonResponse(list(chapters),safe=False) json ouput [ { id: 1, book_id: 237, source: "nobel", chapter: "18", date: "2022-06-26T17:50:26Z" }, { id: 2, book_id: 237, source: "noble", chapter: "19", date: "2022-06-26T17:50:28Z" }] -
Django with Javascript fetch API: POST works but all other unsafe methods are forbidden
I am working on this CS50W project. When using the fetch API to send POST requests to the server, everything worked fine. After I changed the method to PUT, or any other unsafe methods, things stopped working. Javascript let like_form = document.querySelector('#like-form'); let data = new FormData(like_form); fetch(`post/${post_id}/like`, { method: 'POST', body: data, credentials: "same-origin" }) views.py @login_required def like_post(request, post_id): if request.method == 'POST': post = get_post(post_id) if post: if request.user in post.liked_by.all(): post.liked_by.remove(request.user) status = False else: post.liked_by.add(request.user) status = True return JsonResponse({ 'message': 'Success.', 'status': status }, status=200) index.html <form id='like-form'> {% csrf_token %} </form> Output using POST {message: 'Success.', status: false} Output using PUT PUT http://127.0.0.1:8000/post/17/like 403 (Forbidden) Forbidden (CSRF token missing.): /post/17/like The only thing I changed was the method in fetch and views.py Any help will be appreciated. -
How can I send emails with Django to my gmail account
I've tried sending emails with my Gmail account in Django, but I always get errors. I tried using a sandbox (Mailtrap) and it worked but using the actual Gmail account doesn't. I've also tried using App Password in my google account but it still doesn't work. EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "example@gmail.com" EMAIL_HOST_PASSWORD = "password" Error I always get; SMTPConnectError at /send/ (421, b'Service not available') This is what shows up Please how can this be fixed. -
Is there a way to implement the following requirements in django
Please, I need your suggestions, contributions, advise on how to implement the following in django: on user signup, validate email formatting and only allow signups with valid emails once signed up, enrich the User with geolocation data of the IP that the signup originated from based on geolocation of the IP, check if the signup date coincides with a holiday in the User’s country, and save that info data enrichment must be performed asynchronously, i.e. independently of the signup route API request implement retries for requests towards 3rd party API