Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get file URL from raw django SQL query
I have two models class Post(models.Model): ... class PostImage(models.Model): post = models.ForeignKey(Post) ... In a ListView I need to query post and one image for it, so I end up writing raw query. What I hit now is that the url fields are simple path strings which django tries to load from my app, instead of the MEDIA_URL which otherwise works if object is loaded via the ORM. Is there a way to convert that path to url in the template using the django sytax ? {{ post.image.url }} -
Formset and Form Wizard, Django
I have created a working first page using Form Wizard, on second page I am trying to use the value from first page which is stored to create formset forms. Is there a tutorial/guidance or documentation which helps? I went through documentation but am unable to figure it out. -
Django Model Form DateTimeField form validation error
I am a django noobie, I am having problem with models Datetimefield. When I am using model form to fill the date time it's showing pleae enter valid date. Here is My files Views.py def Report_incident(request): if request.method=='POST': form=IncidentReportForm(request.POST) if form.is_valid(): report=form.save(commit=False) report.user=request.user report.save() return HttpResponse('Success') else: form=IncidentReportForm() context={'form':form} return render(request, 'Assginment/report.html',context) Here is Model Form forms.py class DateTimeInput(forms.DateTimeInput): input_type = 'datetime-local' class IncidentReportForm(forms.ModelForm): incident_cat=( ('Environmental incident','Environmental incident'), ('Injury/Illness','Injury/Illness'), ('Property Damage','Propert Damage'), ('Vehicle','Vehicle'), ) time=forms.DateTimeField(widget=DateTimeInput(), input_formats=['%d/%m/%Y %H:%M:%S']) incident_type=forms.MultipleChoiceField(choices=incident_cat, widget=forms.CheckboxSelectMultiple) class Meta: model=Incident fields=('location','description','incident_location', 'severity','cause','action_taken') Here is my Models.py part class Incident(models.Model): location_choices=( ('Corporate Headoffice','Corporate Headoffice'), ('Operations Department','Operations Department'), ('Work Station','Work Station'), ('Marketing Division','Marketing Division'), ) severity_choices=( ('Mild','Mild'), ('Moderate','Moderate'), ('Severe','Severe'), ('Fatal','Fatal'), ) location=models.CharField(choices=location_choices,max_length=300, default='Corporate Headoffice') description=models.TextField() time=models.DateTimeField() incident_location=models.CharField(max_length=200) severity=models.CharField(max_length=200,choices=severity_choices, default='Mild') cause=models.TextField() action_taken=models.TextField() incident_type=models.CharField(max_length=200,null=True,blank=True) reporter=models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='reporter') My template {% extends "base.html" %} {% block title %}Report An Incident {% endblock %} {% block content %} <form method="POST"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Report Incident"> </form> <p>{{ cd }}</p> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape … -
How do I not let a user be able to modify data of another user, using django-rest-framework
I am using django-rest-framework and generic views to build an API for a simple blog app. I am using the RetrieveUpdateAPIView for updating data. By default, if I have a post made by user 1, user 2 can send a POST request and be able to modify the data of the post. I do not want this to happen. This is what I have tried: class PostUpdateAPIView(RetrieveUpdateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer def perform_update(self, serializer): if self.request.user == self.request.POST.get('user'): serializer.save(user=self.request.user) But this does not work. It does not let another user update the post, but it does not let the same user update the post either. I am a complete beginner so I don't really know how to query properly yet. What can I do to make this work? -
I want to pass the instance of one form to another form. How can I do that?
For eg: I have booking form and I have passenger form. I have one to one relationship with Booking model and Passenger model. Now I am on booking form, and when I click "book this flight" I am routed to passenger form. Now at that time, I want to pass the instance of booking form to passenger form. IN the following code, I am putting instance of booking form in passenger form which doesnt work. Can someone help?? def bookpassenger(request,pk): obj = Booking.objects.get(id=pk) content = { 'form': PassengerForm(instance= obj) # 'items': Booking.objects.get(id=pk) } return render(request, 'booking/passenger.html', content) This is the view after i submit the passenger form. def bookpassengersubmit(request): # if request.method == 'POST': form = PassengerForm(request.POST or None) if form.is_valid(): form.save() print('we are good') messages.success(request, 'Successfully added') return redirect('booking') # else: # messages.error(request, 'Submit again') # return redirect('bookpassengersubmit') -
django - how to get all the projects for a team?
I am new to Django and have a question I couldn't solve it by myself. It is a big question for me. I want to show the list of Projects related to a specific Team and show it in a ListView. I would assume it should check the current user belong to which team and then based on the team, it should list the projects. I have a two apps in my project: 1) users and 2)projects users.models: from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse class CustomUser(AbstractUser): bio= models.CharField(max_length=300, null= True, blank=True) class Team (models.Model): title = models.CharField(max_length=200) user= models.ManyToManyField(get_user_model()) date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated= models.DateTimeField(auto_now=True,blank=True, null=True ) def __str__(self): return self.title def get_absolute_url(self): return reverse('team_detail', args=[str(self.pk)]) and the project model is class Project (models.Model): team= models.ForeignKey(Team,on_delete=models.CASCADE ) title = models.CharField(max_length=150, null=False, blank=False) notes = models.TextField( null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project_detail', args=[str(self.pk)]) in projects.views: I made the following codes but cant work out the queryset between two models. class ProjectPageView(ListView): model = Project def get_queryset(self): queryset = super(ProjectPageView, self).get_queryset() queryset = queryset.filter( XXXXXXXXXXXXXXX ) return queryset … -
sweetalert not working on django template
I started with the following code to send the ID to a method to delete an object of model.But the first ID is always sent. this is my HTML and JavaScript code: {% for yad in yads %} <form action="{% url 'del-yadd' %}" method="post" id="myform"> {% csrf_token %} <button type="button" name="yidd" value="{{yad.id}}" id="btndelme" class=" btn btn-danger" onclick=" swal({ title: 'warning!', text: 'do you want to delete?', type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', cancelButtonText:'no', confirmButtonText: 'yes' }, function(isConfirm) { if (isConfirm) { document.querySelector('#myform').submit(); }}); ">delete</button> </form> {% endfor %} and this is my Django view code: def delete_yadd(request): id=request.POST['yidd'] yad=Yadd.objects.filter(id=id).delete() return redirect('home') -
Django login auth form with custom user model
I try to use the default django auth form for login. Django version 3.1 settings.py: AUTH_USER_MODEL = 'app.User' user.py: class User(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] According to the documentation: AuthenticationForm: Uses the username field specified by USERNAME_FIELD. However when i use the default authentication form it provides me a field for username and not email. When i handle the username field as an email it returns validation error (Please enter a correct email and password. Note that both fields may be case-sensitive). Any ideas what can be wrong? -
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