Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, deployment on Heroku. SMTPSenderRefused at /password_reset/ when i try to send an email
I'm deploying the Django app on Heroku. App works fine, but when I try to reset a forgotten password via sending an email - I encounter this error: SMTPSenderRefused at /password_reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError h13sm1336757qti.32 - gsmtp', 'None') The only way to fix this error is to replace this: EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') with this: EMAIL_HOST_USER = 'fake_email' EMAIL_HOST_PASSWORD = 'myfakepassword123' and switch on permission to use less secure apps in Gmail settings. BUT THIS IS NOT HOW I WOULD LIKE TO SOLVE THIS 1) i show my host_user and host_password with this approach, which i don't want. 2) each user needs to go here "Gmail -> Settings -> Allow less secure apps", and i don't want that either, because it's not wery user friendly. Moreover, why should the user allow access to unsecure applications? Maybe you have encountered this problem and know how to solve it in a different way? Thanks! -
Django response code 200 React accept error code
I have a web app with React frontend and Django rest API backend. when I enter the correct username and password to log in I get the message that should appear when the username or password is wrong. The React code: fetch('/token-auth/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({username: this.state.username, password: this.state.password}) }) .then(res => res.json()) .then(json => { if (json.ok) { localStorage.setItem('token', json.token); this.props.notify_login(this.state.username) } else { this.setState({been_failed: true}) } }); So as you can understand the code enters the else block. But the Django server prints the following message saying that the response code is 200. "POST /token-auth/ HTTP/1.1" 200 286 Does anyone know what can cause such a thing? -
How do I return valid MultiSelectField data in the html file
The results I'm getting is none after it renders the context in the HTML file, but it works fine in the admin panel, any clue why this is happening and how I can solve it models.py GENRE_CHOICES = ( ("1", "Action"), ("2", "Adventure"), ("3", "Animation"), ("4", "Comedy"), ) class movies(models.Model): Genre = MultiSelectField(choices=GENRE_CHOICES) views.py def home(request): return render(request, template_name='main/home.html', context={"movies": movies.objects.all}) home.html {% for m in movies %} <li>{{m.Genre}}</li> {% endfor %} what the result looks like: [1]: https://i.stack.imgur.com/lUVfe.png It should return two valid choices instead of none, none -
Python framework Django syntax Error: invalid syntax
enter image description here Python framework Django is not working in my system and whenever I check the version on cmd then display this type of error( https://i.stack.imgur.com/ULGUZ.jpg). Two weeks before it was working but I have installed the bootstrap after that this problem has come in. -
Not able to run local django server with MULTIPLE SETTINGS files DJANGO/PYTHON. Please solve this problem
I am trying to run a Django project on my windows machine. I am getting nomodulefounderror. The project consists of multiple settings files for prod, Development, and Test. I try to run the command I need help to run this project on my local machine. Python manage.py runserver --settings=Sitename.settings.settings_dev_sai It throws me an error. Here is my error log python manage.py runserver --settings=bridge.settings.settings_dev_sai Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", … -
How do I render objects in a queryset to different tags in template in Django?
So I'm trying to make a simple scheduler with Django, but then got stuck. I have this following code. ... <td class="myClass" data-date="2020-05-15"> <div class="myContent">today's schedule comes here</div> </td> <td class="myClass" data-date="2020-05-16"> <div class="myContent">today's schedule comes here</div> </td> ... I have a separate model where each object has two fields-date(datefield) and schedule(CharField). Let's assume the user can only put one schedule per day. So for example if the data is [{"date":"2020-05-15", "schedule":"Read books"}, {"date":"2020-05-16", "schedule":"Do laundry"}], how do I assign each schedule to each date? I think I was able to get the objects using query in views.py below, but got stuck on rendering each data(schedule) to each corresponding date in template. from .models import NewEvent def SchedulePage(request): eachDay = NewEvent.objects.all() return render(request, 'schedule.html', {'eachDay':eachDay}) I believe I'll have to use JQuery here but have no idea on how to do it. I very much appreciate your help. :) -
Django Admin. Filter foreign key dropdown objects based on another field
These are my models: class Place(models.Model): district = models.ForeignKey(District, on_delete=models.CASCADE) street = models.ForeignKey(Street, on_delete=models.CASCADEdefault) class District(models.Model): name = models.CharField(max_length=255) class Street(models.Model): name = models.CharField(max_length=255) district = models.ForeignKey(District, on_delete=models.CASCADE) Every District has some Streets. In the Admin Create Form (for Place), I need to filter Streets based on the selected District. -
How to cach api call on the client
How to implement caching api call from react. And make the call again only when the data change on the server (Django rest framework). I want to make api call ND store the data on local storage on the client side. And only make api call when the data on the server side changed. Thank a lot. -
Can't connect to cloud sql MySQL server through socket '/cloudsql/project:zone:mysql-instance-id', Google Vm Instance
I am trying to deploy django3 app on google vm instance on Ubuntu 20. Everything installed perfectly but when trying run sudo python3 manage.py makemigrations getting "Can't connect to local MySQL server through socket '/cloudsql/project:zone:mysqliinstance-id' ". Please help. Thank you. -
Django child html page reloading due to extend template tag
I have a base home HTML page which has a sidebar and required jquery code to change active class but it is not working because of all the child HTML pages which are linked to the sidebar has {extends} tag because of which it is reloading and due to that the jquery is also reloaded. -
Set parameter of an object to it's default value in Django views
In my Django Models I have set default field to a field For e.g. Class Foo(models.Model): xyz = models.IntegerField(default=122) Now when I am using it in some views, How can I set it to its default value after usage ? I know I can do this: a = Foo.objects.get(...) a.xyz = 122 But is there a better method so that I don't have to re-write the default value in Views? -
How to properly design my models for the categories?
I have a category (e.g. PoliticalParty) and I might create another sub category(e.g.ABC Party) from this PoticialParty and also I might want to create another sub category(e.g.XYZ group) from the ABC party and so on. For such scenario how can I design a Category model? Any suggestions? class Category(models.Model): title = models.CharField(max_length=255) There can be use case that the Category might have another subcategory and the subcategory might also have another subcategory and so on. -
Using Mamind in Django
I am trying to get logged in user city using MaxMind. To do this i first got the user ip using: x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: print ("returning FORWARDED_FOR") ip = x_forwarded_for.split(',')[-1].strip() elif request.META.get('HTTP_X_REAL_IP'): print ("returning REAL_IP") ip = request.META.get('HTTP_X_REAL_IP') else: print ("returning REMOTE_ADDR") ip = request.META.get('REMOTE_ADDR') then i passed the ip variable to MaxMind using : reader = geoip2.database.Reader(maxmindpath_city) response = reader.city(ip) user_city = response.city.name The ip variable when passed to response = reader.city(ip) does not work, however it works only when i pass it like :response = reader.city('197. . .38'). I have tried to convert ip variable to a string but it still does not work. How can i pass the ip variable to response = reader.city() -
how to pass an object in django?
Hello guys i need a bit a help i just started learning Django for 1 month and i am a bit confused how to passing and object through Django? i try the urls thing but it only returned a string base on the type of variable it passing. can anyone give me a tips? how to do this? thanks here is my code i try to passing the api object to the other function in my view view.py from django.shortcuts import render,redirect from django.contrib import messages import routeros_api # Create your views here. def mikrotikapi(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] iprouter = request.POST['iprouter'] try: con = routeros_api.RouterOsApiPool(host=iprouter,username=username,password=password,plaintext_login=True) api = con.get_api() return redirect("dashboard/{}".format(api)) except: messages.info(request,"gak bisa login mas") return redirect("mikrotiklogin") else: return render(request,"loginmikro.html") def dashboard(request,api): resource_log = api.get_resource("log") content_log = api.get() resource_user = api.get_resource("/ip/hotspot/user") content_user = resource_user.get() all_user = len(content_user) total_user = 0 if all_user <= 0: total_user = 0 else: total_user = all_user return render(request,"dashboard.html") here is my urls urlpatterns = [ path("dashboard/<api>",views.dashboard,name="dashboard"), ] -
Getting an error while trying to integrate slack in my django app?
Actually my requirement is integrating slack in my existing django app for that I had done these following steps I had created slack app in api.slack.com I had followed this django package tutorial https://pypi.org/project/django-slack-oauth/ so I had included the getting slack button like this in my template like this <a href='{% url 'slack_auth' %}'>Get slacked</a> and when I click this the error in my webpage is Something went wrong when authorizing this app. Try going back and authorizing again. If problems persist, contact support for help. Error details Invalid client_id parameter and the url of the page it is redirecting when I click getting slack is this https://slack.com/oauth/authorize?client_id=None&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fslack%2Flogin%2F&scope=admin%2Cbot&state=791cc2&tracked=1 Can anyone help me out from this? -
.How user account locked for 30 minutes after 5 attempts in django?
Lock user account (prevent login) to user account after a defined number of failed logins/time. Number of logins and time should be set in admin panel. Example: Lock account after 5 failed login attempts in 60 minutes. -
Block tag and Django errors
I am Using Django version = 3.0.6 and Python version 3.8.2. I am having issues with getting my index.html page does not show my buttons with my current template tags. I have my URLs matched to my views not sure what the problem is. When I run my app I do not see my navbar that I have under my unordered list. Can someone please help me? <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Circle</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css" integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script> <!-- Fonts to be used --> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet"> <link rel="stylesheet" href="{% static 'circle/css/master.css'}"> </head> <body> <nav class="navbar mynav" role='navigation' id='navbar'> <div class="container"> <a class="navbar-brand mynav" href="{% url 'home' %}">Circle</a> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li> <a href="#">Post</a></li> <li> <a href="#">Circles</a></li> <li> <a href="#">Create Circle</a></li> <li> <a href="{% url 'accounts:logout' %}">Log Out</a></li> {$ else %} <li><a href="#">Circle</a></li> <li><<a href="{% url 'accounts:login' %}">Log In</a></li> <li><a href="{% url 'accounts:signup' %}">Sign Up</a></li> {% endif %} </ul> </div> </nav> <div class="container mycontent"> {% block content %} {% endblock %} … -
What is the url.py file that opens home using wagtail?
I'm starting using Wagtail + Django. Generally, in Django you set the urls path in a urls.py file. However, I cannot find the url.py that says to my app, when users visits main domain (local http://127.0.0.1:8000/) show home_page.html view. I'm following the get_started tutorial. And used this command to generate the basic apps: wagtail start elim This generated: a) elim, b) home, c) search apps. Only elim app contains a urls.py, but it doesn't set a path for home: from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from search import views as search_views urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), ] This is my project structure: -
How should I build a bug tracker app with Django?
I was thinking of building a bug tracker/ issue tracker application with Django. Now I have two questions: What exactly is a bug tracker. I've tried watching youtube vids but some concepts like tickets, reports just seems very confusing to me. Is Django a good choice to build something like this? If not, what do you think would be the best to build a bug tracker. Thanks in advance! -
How to set HTTPS protocol in uWSGI docker app
I would like to deploy my Django app with Docker on https with a certificate. For all others Django Docker apps I have it like this: FROM python:3.6 RUN apt-get update && apt-get install -y python-dev && apt-get install -y libldap2-dev && apt-get install -y libsasl2-dev && apt-get install -y libssl-dev && apt-get install -y sasl2-bin RUN apt-get update RUN apt-get install -y locales locales-all ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install --no-cache-dir --upgrade pip RUN pip install --no-cache-dir --upgrade setuptools RUN pip install --no-cache-dir -r requirements.txt COPY . . RUN chmod u+rwx manage.py RUN chmod 777 logs RUN if [ ! -d ./static ]; then mkdir static; fi RUN python manage.py collectstatic --no-input RUN chown -R 10000:10000 ./ EXPOSE 8080 CMD ["sh", "./run-django.sh"] and then in run-django uwsgi --chdir=/usr/src/app --module=app.wsgi:application --master --pidfile=/tmp/project-master.pid --http=0.0.0.0:8080 --processes=5 --max-requests=5000 --vacuum --uid=10000 --gid=10000 --static-map /static=/usr/src/app/static in yml file I have docker_container: name: "{{ app_container_name }}" ... ports: - "{{ deploy_port }}:8080" and this works! Now I would like to deploy it on https: I try it like uwsgi --chdir=/usr/src/app --module=app.wsgi:application --master --pidfile=/tmp/project-master.pid --https=0.0.0.0:443,certificate.crt,privateKey.key,HIGH --processes=5 --max-requests=5000 --vacuum --uid=10000 --gid=10000 --static-map /static=/usr/src/app/static and docker_container: name: "{{ app_container_name }}" ... ports: - "{{ … -
Paypal create payment django
Total noob question, I was reading through paypal SDK here https://github.com/paypal/Checkout-Python-SDK and on paypal website on how to add payment. They listed four steps the first two I'm a little confused about. Handle payment client side, handle payment server side. I'm wondering how to get the response from the client side and pass it to django view since I'm using paypal button. Need help -
Generic way to perform CURD operation
I am new to the Django framework. I want to create generic controller which can accept body as follows { "operation":"select", "fields":["user_id","user_name","user_email"], "table":"user", "where":[ { "field":"user_id", "value":"1234", "operator":"=", "endwith":null } ] } produce a proper SQL query and generate proper JSON output. there is any way to do this using Django rest framework? -
How to load content dynamically from database into Bootstrap modal using Django
I am working on a testing app that lists out users from the database in a HTML table, what I want to achieve is this, when you click on any icon for a particular record or row the full detail of that record is displayed in a Bootstrap Modal. My problem is how do I implement my views, urls, and also my Templates? Do I need Javascript help here? Cause in PHP this is done easily without JavaScript. Plesae I will prefer code samples as a correction to my issue thanks. Here is my view def users(request): get_users = User.objects.all() return render(request, 'classwork_app/users.html', {'users':get_users}) My urls from classwork_app import views app_name = 'classwork_app' urlpatterns = [ path('', views.users, name='users'), ] Templates <table class="table table-bordered"> <tr> <th>S/N</th> <th>Username</th> <th>Firstname</th> <th>Lastname</th> <th colspan="2">Action</th> </tr> {% if users %} {% for u in users %} <tr> <td>{{ forloop.counter }}</td> <td>{{ u.username }}</td> <td>{{ u.first_name }}</td> <td>{{ u.last_name }}</td> <td style="font-size: 12px"><a data-toggle="modal" href="#MyModal{{ u.id }}"><i class="fa fa-eye"></i></a></td> </tr> {% endfor %} {% endif %} </table> <div id="#MyModal{{ u.id }}" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">{{ u.first_name }} {{ u.last_name }}</h4> </div> … -
can't return write context in Detail View
**post_detail.html** {{post.total_likes}} <form class="" action="{%url 'like_post' %}" method="post"> {%csrf_token%} {% if is_liked %} <button type="submit" value="{{post.id}}" name="post_id" class="btn btn-danger">DisLike</button> {% else %} <button type="submit" value="{{post.id}}" name="post_id" class="btn btn-primary">Like</button> {% endif %} </form> **views.py** def like_post(request): post = get_object_or_404(Post,id=request.POST.get('post_id')) is_liked=False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked=False else: post.likes.add(request.user) is_liked=True return HttpResponseRedirect(post.get_absolute_url()) class PostDetailView(DetailView): model = Post fields = ['likes'] def get_context_data(self,**kwargs): post = self.get_object() request = self.request post.is_liked = False if post.likes.filter(id=request.user.id).exists(): post.is_liked = True context = super().get_context_data(**kwargs) context['total_likes','is_liked'] = [post.total_likes(),post.is_liked] return context **urls.py** from django.urls import path from django.conf.urls import url from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, SearchResultView ) from . import views urlpatterns = [ path('', PostListView.as_view(), name='Blog-home'), path('search/', SearchResultView.as_view(), name='search-result'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='Blog-about'), path('like/',views.like_post,name="like_post"), ] **models.py** from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) ikes = models.ManyToManyField(User,related_name='likes',blank=True) def __str__(self): return self.title def total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) This is my code. It do not have any error the only problem is that the like … -
Removing b' in python django
I have a string showing as b'value' i want to remove the b' part. AFTER Searching thru stackoverflow, i tried below but didnt work {% for item in row %} 35 <td>{{ item.decode('UTF-8') }}</td> 36 {% endfor %} I get error Could not parse the remainder: '('UTF-8')' from 'item.decode('UTF-8')'