Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change multiple elements innerHTML using setinterval?
I'm working on certain app and I need to create kind of count down for each element. Unfortunately when I', passing the element to my function it does not work. Neverthless if I change the function a bit and just replace the element's innerHTML out of the setInterval it starts working. I'm totally out of any idea now. Appreciate for help :) const timeout is the element. const json_content = json_reader(reserved) for(x=0;x<json_content["key"].length;x++){ var tds = document.querySelectorAll(".display_content table td") for(let td of tds){ new Vue({ delimiters: ['[[', ']]'], el:td, data: { display: "test", seats_number: "0", }, methods:{ test(){ console.log("elo") } }, created: ()=>{ const td_date = td.innerText if(td_date.includes(json_content["key"][x])){ const td_hour = td.nextElementSibling const json_hour = json_content["value"][x]["times"] if(Object.keys(json_hour).includes(td_hour.innerText)){ const seats = json_content["value"][x]["times"][td_hour.innerText] const td_seat = td_hour.nextElementSibling const timeout = td_seat.nextElementSibling const seats_array = [] seats.forEach(element => { const seat_json = json_reader(element) seats_array.push(seat_json["key"]+":"+seat_json["value"]) }); this.seats_number = seats.length td_seat.innerHTML = "<span onclick='display_seats(this.nextSibling)'>"+[[this.seats_number]]+"</span>"+"<span class='seats' value='"+seats_array+"'></span>" counter(timeout) } } } }) } } and counter function: function counter(element){ var t = 10 setInterval(()=>{ element.innerHTML = String(t) t -= 1 },1000) -
Invalid block tag on line 66: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
Why is it giving me this strange error: Did you forget to register or load this tag? it was working fine but when i did some changes in this code it started this error... i was going through question related to this issue but could not find the solution.... <div class="container"> <div class="row"> <div class="pagination"> {% for item in post.object_list %} <!-- {% for item in post %}--> <div class="card my-3 text-white bg-dark mb-3" style="width: 18rem;"> <img src="/media/{{item.thumbnail}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.title}}</h5> <p class="card-text">{{item.intro}}</p> <!-- href={% url 'bicep' %}--> <a href="blog_detail/{{item.post_id}}" class="btn btn-primary">read more...</a> <!-- <a href="{% url 'blog_detail/pk' pk=item.post_id %}" class="btn btn-primary">read more...</a>--> </div> </div> {% if forloop.counter|divisibleby:4 %} </div> {% endif %} {% endfor %} -
Reset password after first successful login
I am building an web application using existing Auth features in Django where admin create user profile with username and password. Admin created user name and password will be given to user to login. So for security reasons I need to ask user to reset password (given by admin) after user's first successful login. To reset password, I will be displaying template where user should be entering only new password and new password again for confirmation. This new password will be updated in sqlite database. So whenever admin changes the users password. I need to ask users to reset password after first successful login. Here are the implementation I have done. models.py: Here I set boolean flag profile.force_password_change to TRUE when new user created. But profile.force_password_change is not setting to TRUE whenever existing user password changed or new user created. middleware.py: Whenever force_password_change set to TRUE, then I use middle-ware to redirect to change password view. I have written below code to set profile.force_password_change to TRUE whenever new user is created or user password is changed by admin. class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) force_password_change = models.BooleanField(default=False) def create_user_profile_signal(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) pass def password_change_signal(sender, instance, **kwargs): … -
django cache changed by the database status
I have viewset with cache like this on off by changing False -> True def maybe_decorate(condition, decorator): return decorator if condition else lambda x: x class TweetViewSet(viewsets.ModelViewSet): queryset = Tweet.objects.all().order_by('id') serializer_class = TweetSerializer filter_class = TweetFilter @method_decorator(cache_page(60*60*2)) @method_decorator(vary_on_cookie) @maybe_decorate(False,method_decorator(cache_page(60*60*2))) @maybe_decorate(False,method_decorator(vary_on_cookie)) Then now I have one idea. I can get the update time here SELECT UPDATE_TIME FROM information_schema.tables WHERE table_schema = DATABASE() and TABLE_NAME = 'tweet' I want to check this variable and switch on / off cache Is it possible?? or my idea is good practice?? -
DRF Serializer update method always has empty validated_data object when using PATCH + multipart/form-data
I've been banging my head about this one for a bit as I seem to be missing something obvious in this issue. First off, I have multiple parsers loaded for my DRF setup in settings.py: REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ), } Given the presence of the MultiPartParser I would presume that DRF should be parsing the body correctly. However in my ModelSerializer I am overriding the update handler to handle the files and attach them to the model, however all the fields are empty when I interate through them, even the basic ones like 'id' - however I know it must be interpreting the data, because the correct instance is loaded every time, in this case it's the user that is being updated. class UserSerializer(ModelSerializer): """ Serializer for the Logged in User """ avatar = VersatileImageFieldSerializer( sizes='member_avatar' ) background = VersatileImageFieldSerializer( sizes='member_background' ) class Meta: model = Member fields = ( 'id', 'email', 'username', 'language', 'bio', 'location', 'homepage', 'avatar', 'is_staff', 'groups', 'background', 'created', 'edited', 'last_login', 'slug', 'signature' ) read_only_fields = ['created', 'edited', 'slug'] def update(self, instance, validated_data): """ Update the user. :param instance: user instance :param validated_data: validated form data :return updated user """ updated_fields = … -
How can I create post?
This is my fist django project, so I have some problems to use form. I searched how to create post but I have problem. I don't know why posting is not work. Please help me... I want to save POST and Image FILE. views.py ` @login_required() def postFind(request): if request == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit = False) post.menu = True post.pub_date = timezone.datetime.now() post.up_date = timezone.datetime.now() post.user = request.user post.save() return HttpResponseRedirect(reverse('website:postCheck', args=(post.id))) else: form = PostForm() return render(request, 'postFind.html', {'form' : form}) ` postFind.html {% if user.is_authenticated %} <div class="form"> <form class="post-form" method="post" enctype="multipart/form-data" action="{% url 'website:postFind' %}"> {% csrf_token %} <div class="wrapper"> <div class="box"> <div class="js--image-preview"></div> <div class="upload-options"> <label> {{ form.image }} </label> </div> </div> <p id="info">Species</p> {{ form.species }} <p id="info">Location</p> {{ form.location }} <p id="info">Date</p> {{ form.date }} <p id="info">Feature</p> {{ form.feature }} <button type="submit" class="btn btn-default">Submit</button> <a class="btn btn-default" href="{% url 'website:homePost' %}" role="button" id="button">Cancel</a> </form> </div> {% endif %} form.py ` class PostForm(ModelForm): class Meta: model = Post fields = ['image', 'species', 'location', 'date', 'feature'] ` -
How can I use React.lazy with Django and Webpack 4?
I am building app with django on the backend and react on the frontend. I would like to use React.lazy, but I have some problems with Django, because it can not find other bundels except main.js which I have added to index.html template. This is my Webpack configuration: const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: __dirname + '/dist', filename: 'index_bundle.js' }, plugins: [ new HtmlWebpackPlugin() ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } }, { test: /\.css$/i, use: ['style-loader', 'css-loader'], }, { test: /\.(png|jpe?g|gif)$/i, use: [ { loader: 'file-loader', }, ], }, ] } }; Django view: def index(request): return render(request, 'frontend/index.html') index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="{% static 'frontend/favicon.ico' %}" type="image/x-icon"> <link href="https://fonts.googleapis.com/css?family=Oswald&display=swap" rel="stylesheet"> <title></title> <link rel="stylesheet" href="{% static 'frontend/bootstrap.min.css' %}" /> </head> <body> <div id="app"> <!-- React will load here --> </div> </body> <script src="{% static "frontend/main.js" %}"></script> </html> React app: class App extends Component { componentDidMount() { store.dispatch(loadUser()); } render() { return ( <Provider store={store}> <AppRouter /> </Provider> ); } } and AppRouter const AsyncHome = React.lazy(() => import(/* webpackChunkName: "Home" */ … -
uploding image into database using modelforms in django
I'm trying to upload image with model form using user template into database and it didn't work but it does with admin page , I'm getting all other data except the image , the code is below I know its not great but I'm getting frustrated and I hope someone could help especially with my views.py Thank you so much. Thank you in advance! Models.py import os, random from django.db import models from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.utils import timezone as tz from django.urls import reverse from .utils import unique_slug_generator def get_filename_and_ext(filename): base_name = os.path.basename(filename) name ,ext = os.path.splitext(base_name) return name,ext def upload_file_to(instance, filename): new_filename = random.randint(1,29494923) name, ext = get_filename_and_ext( final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return 'post/{new_filename}/{final_filename}'.format(new_filename=new_filename, final_filename=final_filename) class Post(models.Model): title = models.CharField(max_length=20) slug = models.SlugField(blank=True, unique=True) content = models.TextField() time = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to=upload_file_to, null=True, blank=True) auther = models.ForeignKey(User) def get_absolute_url(self): return reverse("posts:detail",kwargs={"slug":self.slug}) objects = AccountManager() def __str__(self): return self.title def post_pre_save_reciver(sender, instance, *arg, **kwargs): if not instance.slug : instance.slug = unique_slug_generator(instance) pre_save.connect(post_pre_save_reciver, sender = Post) forms.py from django import forms from django.contrib.auth import get_user_model # from . import models from .models import upload_file_to, get_filename_and_ext, Post, Comment from .utils import unique_slug_generator class post_form(forms.ModelForm): class … -
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..