Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.template.exceptions.TemplateDoesNotExist: registration/login.html
here's my files: views.py from django.shortcuts import render from django.urls import reverse_lazy from . import forms from django.views.generic import CreateView from django.views.generic import TemplateView class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("login") template_name = "webportal/signup.html" class HelloPage(TemplateView): template_name = "hello.html" 2.apps urls.py: from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = "webportal" urlpatterns = [ path("logout/", auth_views.LogoutView.as_view(), name="logout"), path("", views.SignUp.as_view(), name="signup"), path( "login/", auth_views.LoginView.as_view(template_name="webportal/login.html"), name="login", ), ] 3.models.py: from django.db import models from django.contrib import auth class User(auth.models.User, auth.models.PermissionsMixin): """ this is account User model""" def __str__(self): return "@{}".format(self.username) 4.forms.py: from django.db import models from django.contrib import auth class User(auth.models.User, auth.models.PermissionsMixin): """ this is account User model""" def __str__(self): return "@{}".format(self.username) 5.templates->webportal(myapp's name)->1.login.html , {% extends "base.html" %} {% load bootstrap3 %} {% block content %} <div class="container"> <h1>Login In</h1> <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Login" class="btn btn-default" /> </form> </div> {% endblock content %} 2.signup.html {% extends "base.html" %} {% load bootstrap3 %} {% block content %} <div class="container"> <h1>Sign Up</h1> <form method="POST" action="{% url 'webportal:login' %}"> {% csrf_token %}{% bootstrap_form form %} <input type="submit" value="Sign Up" class="btn btn-default" /> </form> </div> {% endblock content %} … -
Django order by query in foreign key cases
I do have two tables such that, class A(BaseModel): name = models.CharField(...) class B(BaseModel): a = models.ForeignKey(A, on_delete=models.CASCADE) val = models.IntegerField(blank=True, null=True) a = A.objects.all().oreder_by("b__val") Whenever I use order by query, getting repeated instances with different val. But i wanna get only one row from the B model. Optimized query?? NOTE: Using MySQL. -
Django template tags loop in condition for comm seperation
This is my current condtion: {% for d in datalist %} <span class="bold">{{ d }}, </span> {% endfor %} For example, in datalist, the datalist is a queryset, i have these ['t;, 'b', 'c'] I need to show this data like thise t,b,c. in the last item, there should be a fullstop/dot, and after each item, there should comma Can anyone help me to fix this? -
saving template for specific user
Is that possible to save a certain template content to a certain user? I want to display diffrent content on the right side of the image dependent of user's choices.The whole view is coded in JS and HTML The code I want to be unique <div class="home-wrapper home-wrapper-second"> <div class="player-on-map toplaner"> <img class='img-on-map' src="{% static 'images/ago/img1.png' %}" alt="portrait-on-map"> <span name='n' class="nickname">Szygenda</span> </div> <div class="player-on-map jungler"> <img class='img-on-map' src="{% static 'images/ago/img2.png' %}" alt="portrait-on-map"> <span class="nickname">Zanzarah</span> </div> <div class="player-on-map midlaner"> <img class='img-on-map' src="{% static 'images/ago/img3.png' %}" alt="portrait-on-map"> <span class="nickname">Czekolad</span> </div> <div class="player-on-map botlaner"> <img class='img-on-map' src="{% static 'images/ago/img4.png' %}" alt="portrait-on-map"> <span class="nickname">Woolite</span> </div> <div class="player-on-map support"> <img class='img-on-map' src="{% static 'images/ago/img5.png' %}" alt="portrait-on-map"> <span class="nickname">Mystqiues</span> </div> </div> ```[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/8n9Wv.jpg -
GenericViewSet------TypeError: 'method' object is not iterable
Hello I'm new to Django RestFramework, I'm trying to implement Genericviewset but I keep getting this error " TypeError: 'method' object is not iterable " my code is as follows views.py---- class exampleviewset(viewsets.GenericViewSet, mixins.ListModelMixin): serializer_class=exampleSerializer queryset=example.objects.all What might be the reason for this error? -
How can IPAddressField error message be changed
first of all, Its not duplicated Im using djangorestframework==3.11.0 django==3.0.3 I have changed the CharField Error_message easily but when im trying to change the error message for the IPAddressField class InterfaceSerializer(serializers.Serializer): ip_address = serializers.IPAddressField(protocol="IPv4", required=False, allow_blank=True, error_messages={'invalid': 'test fail'}, ) but the result is always {"error_message": { "ip_address": [ "Enter a valid IPv4 address." ]}} and response is 2020-03-18 13:13:12,878 : ERROR : response : {'error_message': {'ip_address': [ErrorDetail(string='Enter a valid IPv4 address.', code='invalid')]}} -
Huey; Doesn't run tasks in one Django App
i have an app called "tickets", it's in the settings file, can be imported correctly. INSTALLED_APPS = [ ... "huey.contrib.djhuey", "core", "telefon", "termine", "tickets", ... ] I am running Huey for background tasks and it does run all tasks in two other apps, just not in the app "tickets". Here is the module "helpers" in the app tickets: from huey import crontab from huey.contrib.djhuey import db_periodic_task, periodic_task @periodic_task(crontab(minute="*/1")) def checkForRunningHuey(): logger.debug("Huey did run at {pendulum.now()}") @db_periodic_task(crontab(minute="*/5")) def getKissTickets(): site_settings = Setting.load() if not site_settings.last_update_tickets: soy, now = getThisYear site_settings.last_update_tickets = soy site_settings.save() site_settings = Setting.load() ... And here is my Huey Configuration: HUEY = { "huey_class": "huey.RedisHuey", # Huey implementation to use. "name": "Huey", # Use db name for huey. "results": False, # Store return values of tasks. "store_none": False, # If a task returns None, do not save to results. "immediate": False, # If DEBUG=True, run synchronously. "utc": True, # Use UTC for all times internally. "blocking": True, # Perform blocking pop rather than poll Redis. "connection": { "host": "192.168.x.xxx", "port": 6379, "db": 0, "connection_pool": None, # Definitely you should use pooling! "read_timeout": 1, # If not polling (blocking pop), use timeout. "url": None, # Allow Redis config via … -
Django OperationalError: table sampleapp_userprofile has no column named email
Git Repo I'm a beginner in the Django. I tried to implement JWT inside Python but when I add a new user I get an error, which is as follows. django.db.utils.OperationalError: table sampleapp_userprofile has no column named email I have created the email field and also put the default value in the email field, and I still get this error .. I have provided the git repository and given some code below, please help. models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser): email = models.EmailField(verbose_name="email",max_length=60, unique=True,default='') username = models.CharField(max_length=30,default='Null') password = models.CharField(verbose_name='password',max_length=16) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) objects = MyAccountManager() USERNAME_FIELD = 'username' EmailField = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from … -
Collectstatic copies my new css file, but doesn’t get served
I collectstatic and see my style.css file copied properly. The browser is serving a style.css file with a hash in the name. It is an old css file. How do I get collectstatic to work with my new css file. I’m using Django 2.2. -
I have to click the button twice to make the onclick work
Here is my html and JS code. When I first click on the button it submits the form but doesn't call the onclick function. I've tried adding onsubmit method to the form and make button type=button. However, that didn't change anything. The form submission is for Django btw. <form action='' method='GET' required id='form_id'> <input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br> <button class='submit-btn' type='submit' onclick="delayRedirect()">Listen</button> </form> JavaScript function delayRedirect(){ setTimeout(function(){ window.location = 'player'; }, 1500); } Thanks in advance! -
django cassandra not executing select query with where clause for datetime range
I have data in cassandra and I am trying to fetch data from the DB within a datetime range. Below is the code. fromdate = datetime.combine(dt, datetime.min.time()) todate = datetime.combine(datetime.now().date(), time(23, 59, 59)) print(fromdate) print(todate) batch = BatchStatement() batch.add(SimpleStatement("SELECT * FROM datadump WHERE 'pickup_time' >= '%s' AND 'pickup_time' <= '%s' ALLOW FILTERING;"), (fromdate, todate,)) data = session.execute(batch) The above code does not work when I try to fetch data within a datetime range but if I try to fetch all the data like "SELECT * from datadump" it works. Can someone please let me know what's wrong with the above approach? Thanks in advance! -
Python comma for loop conditional comma seperation
I want, when i for loop, there will be comma in the end of each item except the last item, last item should be dot x = ['df', 'second', 'something', 'another'] separator = '' for i in x: r = i print(r, separator) separator = ',' else: separator = '.' this is my current code. My expected result should be like this below: df second , something , another. can anyone help me in this case? -
Accessing Angular/Django Application deployed on EC2 through host computer
I have deployed 2 applications on a EC2 machines. 1. Angular 8 Application (frontend) running on 0.0.0.0:80 2. Django Application (backend) running on 127.0.0.1:8000 I am able to access my Angular (frontend) application through browser on http://localhost:80 and also getting successful response from my backend application. Whenever I am trying to access this application from any other system (present in the same network), I can still access my frontend application on http://public_ip:80, but not getting any response from the backend. -
How does .get() work on the back end of Django?
I'm trying to wrap my head around how django's .get() function works; it cant just be a simple LIMIT 1 because the exception it throws gives you the exact number of objects returned. So does django do a COUNT first and then a LIMIT 1? I'm not an SQL expert so I don't know if there's a better way to do it -
Resize images before uploading to google cloud storage django
I am trying to resize and compress images that are uploaded from my django app before it is uploaded to google cloud storage. I tried using firebase to resize any image that is uploaded automatically, but it gives giving resize error. I would like my django app to do this compression first before it is uploaded to google cloud. The standard pillow compression doesn't work on cloud storages. How can accomplish this? -
How to redirect python graph output to the same page using django?
Description of Image 1 - The HTML page shown in the image is divided into two parts. After the user selects the file & clicks the SUBMIT button the graph should be generated on the same HTML page in the second section. This graph is generated from the python code. I'm using Django, Python 3.7 & HTML. Description of Image 2 - The final output should appear as shown in the image. -
Error running 'Django' Can't run remote python interpreter: Process `docker-compose config` failed
I'm struggling with this error for hours now.. There is so little documentation on the internet about this error. All my docker "instances" are running (app, db, mongo,..) but running or testing application doesn't work due to this error. Anyone knows where I can start? It's really frustrating.. -
Dango: What is "the proper successor to" pinax.notifications?
pinax.notifications is a nice package but it uses the decorator @python_2_unicode_compatible and it apparently still tries to get it from django.utils.encoding rather than six. This is after running pip3 install --upgrade pinax.notifications just now. Is there a more up-to-date package that I should be using now? -
Run function on loading DetailView in Django
I would like to execute a function immediately upon loading a DetailView. Specifically, I have a Market model, and when users land on a DetailView using that model, I want the current_price on the relevant market to be saved in the most_recent_price feature of the relevant user. Here's what I have right now, which isn't doing anything - I don't get any error message or anything, it simply doesn't get executed: class MarketDetailView(LoginRequiredMixin, DetailView): model = Market template_name = 'question.html' login_url = 'login' def set_current_price_for_user(self, **kwargs): pk = self.kwargs['pk'] market = Market.objects.get(pk=pk) user = request.user user.most_recent_price = market.current_price I feel like I'm missing something basic here. What am I doing wrong? -
How to close all html popup window when I click logout button in django backend
I tried to close all the html popup window when I clicked on logout button. But when I tried with Httpresponse and javascript It's not working. So I have attached my code for better understanding. I can't understand what's happening. I tried to render with Httpresponse in views.py with the help of Javascript, But It's failed. Thanks in advance... Success.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <!-- Interaction Script Here --> <script type="text/javascript"> function win() { var secondWindow= window.open("{% url 'choice' %}","choice","height=700,width=700,scrollbars=no"); if(window.close()){ secondWindow.close(); } } function win1(){ var thirdWindow= window.open("authordetails.html","AUTHOR DETAILS","height=800,width=700,scrollbars=no"); if(window.close()){ thirdWindow.close(); } } function win2(){ var fourthWindow= window.open("maxsales.html","MAX. SALES","height=800,width=700,scrollbars=no"); if(window.close()){ fourthWindow.close(); } } function win3(){ var fifthWindow= window.open("updatePrice.html","CHANGE PRICE","height=800,width=700,scrollbars=no"); if(window.close()){ fifthWindow.close(); } } function win4(){ var sixthWindow= window.open("report.html","REPORT","height=800,width=700,scrollbars=no"); if(window.close()){ sixthWindow.close(); } } window.onload=function(){ window.resizeTo(700,700); window.open("{% url 'success' %}","success","width=700,height=700,scrollbars=no"); }; </script> </head> <body> <nav class="fixed-top"> <input type="checkbox" id="check" /> <label for="check" class="checkbtn"> <i class="fas fa-bars"></i> </label> <label class="logo">Book Managment</label> <ul> <li><p style="font-size:17px;color:white;">Welcome {{user.username}}</p></li> <li><a href="{% url 'logout' %}">Logout</a></li> </ul> </nav> <!-- Interaction Code Here--> <div class="suc"> <h1>Your Interaction</h1> <form action="{% url 'success' %}" method="POST"> <fieldset class = "insertion"> <div> <label for="insert">Insert Values</label> <button type="button" id="insert" onclick="win()">SELECT</button> </div> <div> <label for="details">View Author Details</label> <button type="button" id="details" … -
How to generate coverage reports programmatically using Coverage.py?
At present, I am generating coverage reports via coverage.py, by giving the coverage command which would thus generate an HTML report. Now I want to automate this whole process such that in my Django project I should have a URL and a corresponding view that should generate the coverage report for the whole project and render it as HTML file..! -
Django Serve Special files like favicon and manifest
How can I serve a directory as the default in Django? I build a django/react application. Got it all set up with uWSGI. Static files for both react and django working (using whitenoise for multiple static directories). But files like /favicon.ico and /manifest.json in the index.html built from react return a 404 error because they don't exist. How can I get django to attempt to serve files in the same directory as index.html if everything else fails? Currently I serve index.html by doing the following in Django: In myproject/urls.py: urlpatterns = [ path('', index, name='index'), path('favicon.ico', favicon, name='favicon'), ...other-stuff ] In myproject/views.py index = never_cache(TemplateView.as_view(template_name='myproject/index.html')) favicon = never_cache(TemplateView.as_view(template_name='myproject/favicon.ico')) The index works, but favicon doesn't. So what about the other files that need to be served? How can I define those files (anywhere from 4-20 files) to be served by uwsgi? -
Passing data from html to python
It is necessary to obtain information from the selected cell from the html file and then work with it in views.py. Is it possible and how to do it? Thank you in advance! <tbody> {% for element in qz %} <tr> <td class="counterCell"></td> <td style="display: none">{{ element.0 }}</td> <!-- information is needed for this cell when it is selected --> <td>{{ element.1 }}</td> <td>{{ element.2 }}</td> <td><span class="glyphicon glyphicon-trash"></span></td> </tr> {% endfor %} </tbody> -
'QuerySet' object has no attribute 'favourite'
Can any one please fix the problem. Here in this view I am getting the error . Actually I am adding the favourite list to the product and tried to write the view . listings/views.py from django.shortcuts import get_object_or_404, render from .choices import price_choices, bedroom_choices, state_choices from django.core.paginator import EmptyPage, PageNotAnInteger,Paginator fetch the data from .models import Listing, Comment from realtors.models import Realtor from sellers.models import Seller Create your views here. def index(request): #varname = modelname.objects.all() # listings = Listing.objects.all()//displaying in any order # now displaying the list in the latest date(descending) listings = Listing.objects.order_by('-list_date').filter(is_published = True) if listings.favourite.filter(pk = request.user.id): is_favourite = True #creating the pagination paginator = Paginator(listings, 3) page = request.GET.get('page') paged_listings = paginator.get_page(page) is_favourite = False context = { 'listings' : paged_listings, 'is_favourite':is_favourite } return render(request, 'listings/listings.html', context) def listing(request, listing_id): if request.method == "POST": name = request.POST['name'] message = request.POST['message'] proid = listing_id query = Comment(message = message, name = name ) # stars = stars query.proid_id = proid # query.stars = stars query.save() listing = get_object_or_404(Listing, pk = listing_id) seller = Seller.objects.all().filter(pk = listing_id) comment = Comment.objects.all().filter(proid = listing_id) context = { 'listing' : listing, 'comments':comment, 'seller':seller } return render(request,'listings/listing.html',context) def search(request): queryset_list = … -
Django: How to show second form on submit of first form without refreshing the page?
Hi all I am trying to display a second form without refreshing the page when I click on submit button of first form. Is there any solution for this? Thanks in advance.