Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Secure raw SQL query in Django with psycopg2
I am creating a web application using django framework. In one of the SQL queries I had to join multiple tables and use the user input as part of the "where" clause to fetch the results. Since the query was rather complex, I chose to use raw SQL instead of django framework. A simplified form of the query is : select * from table where {where_clause} where_clause would be something of the form col1>100 and col2>50 and col3 <40 and so on This part is created on the front end based on the user input (sort of like a stock screener). To make the query secure against SQL injection, I decided to use psycopg2 which builds the query as : query = sql.SQL("select {field} from {table} where {pkey} = %s").format( field=sql.Identifier('my_name'), table=sql.Identifier('some_table'), pkey=sql.Identifier('id')) Even if I separate all the parts of where_clause into identifiers and literals, I do not know what all columns are there beforehand to write in this way. There could potentially be many columns which are chosen by the user to filter on. How can I go about making the query secure ? -
Custom authentication is not working in custom User modal in Django
I have created custom user model consist of username and password and I use logged in through the username and password but when i try to login the login is not working, I have also created custom authentication backend.py for custom user model HandleLogin in models.py register_app/model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class Register(models.Model): class Meta: db_table = "register" id = models.AutoField(primary_key = True) first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) email=models.EmailField() class HandleloginManager(BaseUserManager): def create_user(self, username, password=None): if not username: raise ValueError("username is required") user = self.model( username = username, ) user.set_password(password) user.save(using=self._db) return user class Handlelogin(AbstractBaseUser): class Meta: db_table = "login" username = models.CharField(max_length=150, unique = True) password = models.CharField(max_length = 50) register = models.OneToOneField(Register, on_delete=models.CASCADE) USERNAME_FIELD="username" REQUIRES_FIELD=['password'] objects = HandleloginManager() register_app/views.py from django.shortcuts import redirect, render, HttpResponse from .models import Register, Handlelogin from django.contrib.auth import authenticate, login # Create your views here. def home(request): return render(request, 'home.html') def register(request): if request.method == 'POST': add = Register() add.first_name= request.POST['firstname'] add.last_name= request.POST['lastname'] add.email= request.POST['email'] add.save() d = Handlelogin.objects.create_user( username=request.POST['username'], password=request.POST['password'] ) d.register = add d.save() return redirect('/') else: return render(request,'register.html') def users(request): reg = Register.objects.all() return render(request, 'users.html', {'reg':reg}) def login_handle(request): if request.POST: username = … -
Why does " 'list' object has no attribute 'likes' "?
I am a beginner in django. Can someone help me out in this? Getting error like this. ERROR IN THE PAGE IS HERE. In models.py class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) category = models.CharField(max_length=150, default="") author = models.ForeignKey(User, on_delete=models.CASCADE) sub_title = models.CharField(max_length=50) body = models.TextField(max_length=5000) pub_date = models.DateField(default=now()) likes = models.ManyToManyField(User, related_name='blogpost') In views.py def LikeView(request, pk): post = get_list_or_404(Post, post_id=request.POST.get('like_id')) post.likes.add(request.user) return HttpResponseRedirect(reverse('blogPost', args=[str(pk)])) In urls.py urlpatterns = [ path("", views.home, name="Home"), path("index/", HomeView.as_view(), name="blogHome"), path("blogpost/<int:pk>", BlogDetailView.as_view(), name="blogPost"), path("edit/<int:pk>", UpdateBlog.as_view(), name="editPost"), path("<int:pk>/delete", DeleteBlog.as_view(), name="deletePost"), path("addblog/", AddBlog.as_view(), name="blogAdd"), path("search/", views.search, name="Search"), path("contact/", views.contact, name="Contact"), path("catmenu/", views.catmenu, name="Catmenu"), path("category/<str:cats>/", CategoryView, name="categoryView"), path("like/<int:pk>/", LikeView, name="likepost"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In html file <form action="{% url 'likepost' post.pk %}" method="POST"> {% csrf_token %} <button type="submit" name="like_id", value="{{post.post_id}}" class="btn btn-primary btn-sm">Like</button> </form> -
I want order by date because i am creating upcoming event list
I want to order my upcoming event like I created 3 events 1 is on 23rd, 2nd in on 21 and 3rd is on 24th then it should arrange the event as 21, 23 and 24 This is the serializers.py class UpcomingEventsSerializer(serializers.ModelSerializer): class Meta: model = Events fields = ('id', 'event_title', 'small_description', 'event_location', 'event_date') This is the views.py class UpcomingEventsAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin): permission_classes = [permissions.AllowAny] serializer_class = UpcomingEventsSerializer queryset = Events.objects.all() lookup_field = 'id' filter_backends = [DjangoFilterBackend, filters.SearchFilter] def get(self, request, id=None): if id: return self.retrieve(request) else: return self.list(request) -
Certificate error SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED]
I've been trying to make a name sniping bot for minecraft in Python (not important) and I'm for some reason getting this error: Traceback (most recent call last): File "/Users/mikolajszczerbetka/Library/Python/3.8/lib/python/site-packages/aiohttp/connector.py", line 936, in _wrap_create_connection return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 1046, in create_connection transport, protocol = await self._create_connection_transport( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 1076, in _create_connection_transport await waiter File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/sslproto.py", line 529, in data_received ssldata, appdata = self._sslpipe.feed_ssldata(data) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/sslproto.py", line 189, in feed_ssldata self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 944, in do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/mikolajszczerbetka/Downloads/MCsniperPY-master/snipe.py", line 397, in <module> session = session(target_username, accounts, block_snipe, snipe_delay) File "/Users/mikolajszczerbetka/Downloads/MCsniperPY-master/snipe.py", line 300, in __init__ self.drop_time = loop.run_until_complete(time_snipe(self.target_username, self.block_snipe)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 612, in run_until_complete return future.result() File "/Users/mikolajszczerbetka/Downloads/MCsniperPY-master/snipe.py", line 93, in time_snipe async with session.get(f"https://namemc.com/search?q={target}") as page: File "/Users/mikolajszczerbetka/Library/Python/3.8/lib/python/site-packages/aiohttp/client.py", line 1012, in __aenter__ self._resp = await self._coro File "/Users/mikolajszczerbetka/Library/Python/3.8/lib/python/site-packages/aiohttp/client.py", line 480, in _request conn = await self._connector.connect( File "/Users/mikolajszczerbetka/Library/Python/3.8/lib/python/site-packages/aiohttp/connector.py", line 523, in connect proto = await self._create_connection(req, traces, timeout) File "/Users/mikolajszczerbetka/Library/Python/3.8/lib/python/site-packages/aiohttp/connector.py", line 858, in _create_connection _, proto = await self._create_direct_connection( File … -
Ajax not getting sucess reponse from django back-end
I hope everyone is fine and safe !! I am trying this below requirement where there is a voice synthesizer and it converts my voice which is a question in to a text and it sends that text to the back-end django through AJAX. At the back-end django takes that data and use that data(question) to access the database and get the result and send that result to the front which should get caught by the success part of the ajax. But, Its not working. I am not able to figure out where is the problem. I am posting the Ajax and django code below for your reference. views.py def GetAnswer(request): if request.method=='GET' and request.is_ajax(): question_asked=str(request.GET.get("message_now")) try: answer=QuestionAnswer.objects.filter(question=question_asked).value_list('answer', flat=True)[0] print(answer) data={"data":answer} return JsonResponse({"success": True}, data, status=200) except: return JsonResponse({"success": False}, status=400) else: print("Not Suceess") main.js function chatbotvoice(message){ const speech = new SpeechSynthesisUtterance(); if(message!==null && message!==''){ $.ajax({ url: "http://127.0.0.1:8000/getanswer", type: 'GET', data: { message_now:message }, success: function (data) { speech.text=JSON.parse(data); window.speechSynthesis.speak(speech); chatareamain.appendChild(showchatbotmsg(speech.text)); }, error: function(error){ speech.text = "Oh No!! I don't Know !! I am still learning!! Your question got recorded and answer for your question will be available with me in 24 hours"; window.speechSynthesis.speak(speech); chatareamain.appendChild(showchatbotmsg(speech.text)); }, }); } } I … -
Hey, why is bootstrap not displaying in django website at all?
I am generally getting pretty weird errors in this new module I am learning. For example I type <h1>Dashboard</h1> and it doesnt work and then I type <h1>fdcs</h1> and it displays **just my code from the navbar file in sublime text. ** <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> </div> </nav> -
Is it a good idea to replace redux with apollo and graphql when using django with react
I am starting a new project from scratch and I decided to use Django with react. But when I say react there are many developers who use redux as an essential library for state management but i think redux adds lot of complexity in code. So I searched an alternative for this and i found some developers are not using redux at all instead they are using GraphQL + Apollo as an alternative. And I found this beautiful repository as well on github that uses the django with react but this is not using redux at all. Link to a package.json file of that github repository - https://github.com/mirumee/saleor-dashboard/blob/0d9f8662299a98de4c89bbdf5b8142a0e1790bc7/package.json So, Is this a good idea of using Apollo + GraphQL instead of redux? -
Accessing environment variables in production in Django deployed to Heroku
I am developing a web-app in Django that needs to send automated emails. The username and password are saved locally in my Windows 10 environment variables. The app is able to send emails locally, but in proudction once deployed to Heroku, the following error is raised: 530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError y7sm6660123qtn.11 - gsmtp', 'webmaster@localhost' My guess is that the environment variables are not being accessed which is why this error is thrown. Here is my code in settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('NAHE-USER') EMAIL_HOST_PASSWORD = os.environ.get('NAHE-PASS') -
Login_Required decorator not working properly in django
I am building a website in django. I used login_required decorator to prevent user to move to UserView without a successful login. But I came to problem where its not moving from login page even after a successful login authentication and stays on the login page. What am I doing wrong? Here is my code: view.py def LoginView(request): if request.method=='POST': username=request.POST.get('username') password=request.POST.get('password') try: user_info=User_Registration.objects.get(username=username) if user_info.password==password: return redirect("userview") else: messages.info(request,"Invalid Password") except User_Registration.DoesNotExist: messages.info(request,"User Doesn't exist") else: return render(request,'login.html') @login_required(login_url="login_view") def UserView(request): return render(request,'user.html') -
How to import live pgphpmyadmin database to local sqllite in django
How to import live database of django project to local sqllite db to run django project on local machine. -
Django NodeNotFoundError at every project
I 'broke' the migrations at one project so I deletetd it and now everytime I run python3 manage.py <action> (no matter at which project), I get: raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0005_auto_20200919_1755 dependencies reference nonexistent parent node ('app3', '0004_auto_20200919_1754') although neither 'app3' nor the project where app3 was in exists anymore. -
Django error{ Page not found, error 404},
Getting this error when trying to connect Using the URLconf defined in project.urls, Django tried these URL patterns, in this order: admin/ The current path, hello, didn't match any of these. C:\Users\Kwaku Biney\Desktop\dj\mysite\polls\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'),] C:\Users\Kwaku Biney\Desktop\dj\mysite\mysite\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'),] mysite\polls\views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") settings.py # Application definition # Application definition INSTALLED APPS= [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls',] -
Group users by country of phone numbers in django
I am using django-phonenumber-field like below: from phonenumber_field.modelfields import PhoneNumberField class MyModel(models.Model): name = models.CharField(max_length=255) phone_number = PhoneNumberField() Now, I want to find out number of users per country of their phone number. Like: { 'US': 10, 'IR': 18, 'GE': 9, } Could django-phonenumber-field help me? If no, What is the best way to get this? -
Dynamic URL routing for a class-based view
I want to turn a function view into a class-based view. Here is the View & URL path that I have right now. View: def customer(request, pk): customer = Customer.objects.get(id=pk) return render(request, 'accounts/customer.html) URL Path: path('customer/<str:pk>/, views.customer, name='customer') What would the proper syntax be to turn this view into a class-based view. Thanks! -
Changing div of similar class after a set time with Django loop
I've different images on my database. I did a forloop, making each div class the same. Now, assuming I've 20 images displayed, I want this images and it's image_title to interchange themselves, let's say the first image replaces the third(something like that). Note, this should be in a random basics. Here's my code, for easy understanding {% for men in clothes %} <img src = "{{men.images}} "{{men.image_name}} {% endfor %} </div> I tried using forloop counter to different the different class so as to implement it on my jQuery, but I'm stucked because I don't know how to implement it on jQuery.. any rough sketch on how to go about this will be appreciated.. thanks -
why is python not recognized in cmd as a internal, external or batch file
so, i was trying to use django in python, at first it was running manage.py it worked normally, but as soon as i edited some code, CMD started saying this C:\Users\pert\PycharmProjects\chatapp\web> python manage.py runserver 'python' is not recognized as an internal or external command, operable program or batch file. so, why is cmd saying 'python is not recognized, i am sure my code was correct, i watched it at youtube, but what is going on, also i have had python for 3 years now, and it never gave me this error, also i was using pycharm and at youtube, he used sublime, is it just a problem with IDE's -
How to log api calls into databse using django?
I don't know how to log all the API calls like API name, API call time, API call success/fail status into my sqlite3 database. Please help me I have no idea about this. -
Django UserAdmin, save_model override function doesn't return updated user groups
I need to do some actions after saving a user in the django admin user form. Specifically, inside the save_user method of UserAdmin, I need to check if the user belongs to a certain group after creation. When I print the user groups after saving a new user model with a "Doctor" group, the group doesn't seem to be updated inside the save_model function. Here's the sample code for clarification: def is_doctor(self, user): z = user.groups.filter(name='Doctors').exists() if not z: z = user.groups.filter(name='Doctor').exists() return z def save_model(self, request, obj, form, change): super(UserAdmin, self).save_model(request, obj, form, change) user = User.objects.get(pk=obj.pk) print(f'is doctor: {User.objects.is_doctor(obj)}') print(f'is doctor new user: {User.objects.is_doctor(user)}') print('Printing groups of newly created user...') groups = user.groups.all() groups_count = groups.count() for group in groups: print(group['name']) print(f'This user has {groups_count} groups') After saving a user with a "Doctor" group like the image below: It prints the following: is doctor: False is doctor new user: False Printing groups of newly created user... This user has 0 groups The doctor group that was added isn't updated in creation of a new user object. Is this normal or have I missed something? -
Django valid URL in url file not being found . Instead a circular error is being shown
This my views file where I am trying to use a usercreationform from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserRegisterView(generic.CreateView): form_class = UserCreationForm template_name = 'registration/register.html' success_url = reverse_lazy('home') And this is my url file where I point to this view from .views import UserRegisterView from django.urls import path url_patterns = [ path('register/', UserRegisterView.as_view(), name="register"), ] Now when I try to run the server , I am getting this error for some reason django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'members.urls' from does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. This does not make any sense . There is already a url pattern in it pointing to my view . -
How to reset password in django2 without django Authentication
Please help me for reset password without django authentication in django2. My views is: #password reset def resetpass(request): mail_forms = PassResetForm() if request.method == 'POST': mail_forms = PassResetForm(request.POST) if mail_forms.is_valid(): mail = mail_forms.cleaned_data['mail'] user_info = UserInfo.objects.get(email=mail) user_mail = user_info.email context = { 'mail_forms':mail_forms, } return render(request, 'login/pass_reset_mail.html', context) -
Django Live data view to web page
I want to display the csv data to web page. The data from the csv is live which means the continuously added to the csv. Meanwhile the webpage needs to display the updated data as well. How can i do that? The csv file located in the local machine. -
Django Bootstrap Modal form CSRF verification failed
I was trying a bootstrap model form in django detailview using form mixin, but while submitting the form I am receiving Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. error please find my code below. Thank you for any help you can provide. views.py class PostDetail(FormMixin, generic.DetailView): model = Post form_class = SubscriberForm template_name = 'post_detail.html' #for related post start #post_rel = Post.objects.filter(status=1) #post_related = Post.tags.similar_objects().filter(status=1).order_by('-created_on')[:3] #post_related = post_rel.tags.similar_objects()[ : 3] #post_related = Post.tags.similar_objects().filter( #).order_by('-created_on')[:3] #Post = get_object_or_404(Post) #post_related = [Post.tags.similar_objects()][:3] context = { 'tag':Post.tags, } def post(self, request, *args, **kwargs): form = SubscriberForm(request.POST) if form.is_valid(): try: sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() return render(request, "post_detail.html", {'form': SubscriberForm(), 'model': Post, 'email': sub.email, 'action': 'added'}) except: return render(request, "post_detail.html", {'existing_email': sub.email, 'action': 'already added', 'duplicate': 'duplicate', 'form': SubscriberForm(), 'model': Post}) template.html <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">New message</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% if form %} <form method="post" style="padding-left: 14px;"> <div class="row" style="padding-top: 30px; padding-bottom: 30px;"> <div class="col-lg-12"> <div class="input-group" style="border-radius: 4em;"> {% csrf_token %} {{form}} <button class="btn btn-lg btn-default" style="background-color: white; color:#0412DE; font-weight: … -
When to use Django Workers, Queues, and Tasks rather than Python Threading or Concurrent?
Assume on a Django projects, we want to update a user profile along with sending him/her an email notifying changes, in this case two different solutions would come in mind: using python concurrent library to run both tasks use something like Django Q the project also needs "Scheduled Tasks" to be run daily or weekly, so a job Que library is a must, but I thought I could use python concurrent library for making functions run concurrently and something like Advanced Python Scheduling, this also came in mind when I realized Dramatiq does not support scheduling tasks. now my question is : What are benefits of using Django Task Queuing apps over using python core libraries like concurrent? -
Annotate on two prefetched_related tables deep in Django
My issue is similar to the following question, but that doesn't quite cover the scenario I'm looking for. Combine prefetch_related and annotate in Django I have the following models: class Item(models.Model): name = models.CharField(max_length=100) class Recipe(models.Model): name = models.CharField(max_length=20) output_item = models.ForeignKey(Item, null=True, blank=True, on_delete=models.SET_NULL) class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) item = models.ForeignKey(Item on_delete=models.CASCADE) quantity = models.IntegerField() class StorePrice(models.Model): store_name = models.CharField(max_length=20) item = models.ForeignKey(Item, null=True, blank=True, on_delete=models.SET_NULL) price = models.IntegerField() I'm trying to display the following details about a single recipe: The recipe name The name and quantity of each ingredient linked to the recipe The lowest price available for that ingredient, and the name of the store So far I have the following query... Recipe.objects.filter(id=5)\ .select_related('output_item')\ .prefetch_related( 'output_item__storeprice_set', 'ingredient_set', 'ingredient_set__item', 'ingredient_set__item__storeprice_set', ).first() This accomplishes goals 1 and 2, but now I need to add the annotation to achieve #3. The lowest price should be calculated per ingredient, but so far I've only been able to have it apply at the recipe level, by adding the following. .annotate(lowest_store_price=Min('ingredient__item__store_price__price'))