Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Not Validating my Date fields
I have a Search form that includes the query box, some checkbox items, and a start and end date. I am getting my information when I enter a query, so I know it is performing the search_results action, but the start and end date is not getting validated at all. I have yet to add the code to handle the start and end date in my results, but the issue is there is no client side validation happening on the form. My form looks like this: class SearchForm(forms.Form): q = forms.CharField(max_length=64,required=False) service_choices = forms.MultipleChoiceField( required=True, widget=forms.CheckboxSelectMultiple, choices=CustomUser.SERVICE_CHOICES, ) start_date = forms.DateField(required=False) end_date = forms.DateField(required=False) I tried using Class Based View, but did not get any fields at all, so I tried using a function based view to get my search criteria. The view looks like: def get_search(request): form = SearchForm() return render(request, 'get_search.html', {'form':form}) My template is: <!-- templates/get_search.html --> {% extends "base.html" %} {% block title %}Search{% endblock title %} {% block content %} {% if user.is_authenticated %} <br><br> <TABLE BORDER="0" WIDTH="100%"> <TR> <TD ALIGN="Left"><B>Track X - search</B></TD> <TD ALIGN="Center"><B>User:&nbsp;{{ user }}</B></TD> <TD ALIGN="Right"><B>Service:&nbsp;{{ user.service }}</B></TD> </TR> </TABLE> <form action="{% url 'search_results' %}" method="get""> {% csrf_token %} <TABLE BGCOLOR="#66CCCC" … -
Django don't save ModelMultipleChoiceField in admin
I want to filter skill_ids fields and create 3 "abstract" fields for every SkillType, but now it's not saving this hard_skills field in admin site. Model class Task(models.Model): name = models.CharField(max_length=255) category_id = models.ForeignKey('Category', on_delete=models.RESTRICT, null=True) level_id = models.ForeignKey('Level', on_delete=models.RESTRICT, null=True) permission_ids = models.ManyToManyField('Permission', blank=True) skill_ids = models.ManyToManyField('Skill', blank=True) Form class TaskForm(ModelForm): hard_skills = ModelMultipleChoiceField(Skill.objects.filter(skill_type=SkillType.HARD_SKILL), widget=FilteredSelectMultiple("Hard Skills", False), required=False) class Meta: model = Task exclude = ['skill_ids'] Admin @admin.register(Task) class TaskAdmin(admin.ModelAdmin): list_per_page = 25 list_display = ['name', 'category_id', 'level_id', 'get_permissions'] list_filter = ['category_id'] filter_horizontal = ['permission_ids', 'skill_ids'] form = TaskForm def save_model(self, request, obj, form, change): for hard_skill in form.cleaned_data.get('hard_skills'): obj.skill_ids.set(hard_skill) super().save_model(request, obj, form, change) -
How to know which button was pressed in flask form? (Flask, HTML)
I have used a for loop to populate spotify song links and embed them on a web page. After each song is a button called "like" and "dislike" - here is the html: {% for (song_name, song_uri, submission_id) in songs: %} <br> <form action="" method="post"> <div name="song" value="{{submission_id}}, {{song_name}}"><iframe src="https://open.spotify.com/embed/track/{{song_uri}}" height="80" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe> <input type="submit" value="Like"></input> <input type="submit" value="Dislike"></input> </form> {% endfor %} Let's pretend there are 4 songs listed, with submission_id's of 1, 2, 3, 4, respectively. I would like to then count whether the user clicked the "like" or "dislike" button for a specific song. If the user clicks "Like" on song #1 (submission_id = "1"), then I will extract the link of that song and use it in my backend. I'm not sure how to have each button correspond to a request from my flask app so when a user clicks "Like", I know they meant song #1 (submission_id = "1"). So far I've tried this in my flask app: @app.route('/curator', methods=["GET","POST"]) def curator(): songs = load_songs.load_songs() if request.method == "POST": song_number = request.form['submission_id'] This however results in the following error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could … -
Can i switch of <link href=""> using django?
is that possible to make a switch button that change my styleesheet using django framework ? ''' By example, in my head html i got this : <link href="{% static 'website/assets/css/style.css' %}" rel="stylesheet"> And i would like to get the bellow stylesheet IF my button ( on the body html is clicked ) <link href="{% static 'website/assets/css/style.css' %}" rel="stylesheet"> ''' -
How to display record one by one using Django template (html) and model
In my code below all the questions & related images stored in my table are coming on same page at one go but I want only first question and its image to appear and than when user clicks on next button the second question along with its image should come, this should repeat till end of records in the table. from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from quiz.models import Quiz, Question def playQuiz(request): data=Question.objects.filter(__isnull=False) res=render(request,'quiz/quiz_play.html',{'data':data}) return res <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> {% for data in data %} <div><h1> {{data.qs}} </h1></div> <div> <img src="{{ data.qip.url }}" height=300> </div> <input type="button" name="next-btn" value="NEXT"> {% endfor %} </body> </html> -
AttributeError at /profile/chandan 'tuple' object has no attribute 'another_user'
I am trying to get follower system to work but it just wont work class Followers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) another_user = models.ManyToManyField(User, related_name='another_user') def __str__(self): return self.user.name def profile(request, user_name): user_obj = User.objects.get(username=user_name) session_user = User.objects.get(username=user_name) session_following = Followers.objects.get_or_create(user=session_user) following = Followers.objects.get_or_create(user=session_user.id) check_user_followers = Followers.objects.filter(another_user=user_obj) is_followed = False if session_following.another_user.filter(username=user_name).exists() or following.another_user.filter(username=user_name).exists(): is_followed=True else: is_followed=False param = {'user_obj': user_obj,'followers':check_user_followers, 'following': following,'is_followed':is_followed} if 'user' in request.session: return render(request, 'users/profile2.html', param) else: return redirect('index') I am getting the error: AttributeError at /profile/chandan 'tuple' object has no attribute 'another_user' -
Get DRF token from python-social-auth backend
I am trying to integrate Social Authentication in my DRF backend. I decided to go with python-social-auth. If I serve my social login through Django (and an HTML view), I can see my login in successful. I also figured that I can redirect after successful social authentication as outlined here. Until now, my frontend (a Nuxt app) was using DRF tokens. Even though: I can create valid tokens for social accounts. My frontend can redirect the users to -> complete authorization with OAuth sites e.g. Google, Twitter -> return back to the frontend. Is it possible for me to somehow manage to redirect a successfully authenticated user to the frontend with the associated and valid DRF token as a query parameter? -
How to fill in a ModelForm within django view
I'm using a Django form that will be filled out multiple times by the same user. I would like to populate the form with data from previous submissions (I have a Foreignkey to the user that will be filling out the form), however, it is important that this is done server side as to not have the auto-populated data accessible user-side. Is there a way to fill in specific fields that I don't want filled out again by the user within views.py before calling is_valid? Views.py: def home(request): if request.method == "POST": form = ptForm(request.POST) if form.is_valid(): report = form.save(commit=False) report.pt_user = request.user report.save() form = ptForm() else: print(messages.error(request, "Error")) print(form.errors) else: form = ptForm() context = {'form': form, 'ptz_data': pt_data.objects.all() } return render(request, 'home.html', context) -
Nginx/React/Django: CORS issue
On a ubuntu server I am using nginx as a reverse proxy to serve a react app listening on port 3000 (the front is built and is served using the npm package "serve"). The front app uses axios to call a django backend listening on port 8000. However, I keep getting a CORS blocked error whenever I try to send requests to the backend (e.g sign in fails), I tried many solutions from similar questions but none worked for me. For the record, the project works fine on my local machine with django-cors-headers, the problem only occurs when I put it on the server and included nginx. Here are the relevant configs: Nginx config ... server_name <server_ip>; location / { #try_files $uri $uri/ =404; proxy_pass http://localhost:3000; add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } Django CORS settings ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False CORS_ALLOWED_ORIGINS = [ "http://localhost:3000" ] #CORS_ALLOW_ALL_ORIGINS = True ALLOWED_HOSTS = ['*'] ... Axios config export const axiosInstance = axios.create({ baseURL: "http://localhost:8000/", timeout: 5000, headers: { Authorization: "JWT " + localStorage.getItem("access_token"), "Content-Type": "application/json", accept: "application/json", }, }); axiosInstance.interceptors.response.use( (response: any) => response, … -
Have can i find out where is a mistake in my registration form?
So, i have a problem. I've created a register form and a model User that inherites models.Model class User(models.Model): CHOICES = ( (1, 'Author'), (2, 'Customer'), (3, 'Author and Customer') ) username = models.CharField(unique=True, max_length=32, blank=False, verbose_name='') password = models.CharField(max_length=32, blank=False, verbose_name='') email = models.EmailField(unique=True, max_length=128, blank=False, verbose_name='') first_name = models.CharField(max_length=64, blank=False, verbose_name='') last_name = models.CharField(max_length=64, blank=False, verbose_name='') patronymic = models.CharField(max_length=64, blank=False, verbose_name='') role = models.CharField(max_length=32, choices=CHOICES, default='Customer') age = models.PositiveSmallIntegerField(verbose_name='', blank=False) about = models.TextField(max_length=512, verbose_name='') Photos of form with data and without: Also i have such form: class RegisterForm(ModelForm): class Meta: model = User fields = "__all__" widgets = { 'username': widgets.TextInput(attrs={ 'class': 'form-email', 'placeholder': 'Username' }), 'first_name': widgets.TextInput(attrs={ 'class': 'form-email', 'placeholder': 'First name' }), 'last_name': widgets.TextInput(attrs={ 'class': 'form-email', 'placeholder': 'Last name' }), 'patronymic': widgets.TextInput(attrs={ 'class': 'form-email', 'placeholder': 'Patronymic' }), 'age': widgets.NumberInput(attrs={ 'class': 'form-email', 'placeholder': 'Age' }), 'email': EmailInput(attrs={ 'class': 'form-email', 'placeholder': 'Email' }), 'role': widgets.Select(attrs={ 'class': 'form-select', }), 'password': PasswordInput(attrs={ 'class': 'form-password', 'placeholder': 'Password' }), 'about': widgets.Textarea(attrs={ 'class': 'form-email', 'placeholder': 'A few words about you' }) } And this is a view for registration def register(request): if request.method == "GET": form = RegisterForm() return render(request, 'account/register.html', {'form': form}) form = RegisterForm(request.POST) if form.is_valid(): form.save() return HttpResponse("Successfull!") What can … -
Django highly compress video into multiple resolutions
I have this app like YouTube and I want to be able to compress my videos into multiple resolutions. Such as 360p, 480p, and 720p. Here is my code: #blog/models.py class Post(models.Model): # Other Stuff video = models.FileField(upload_to='videos/%y', blank=True, validators=[video_file_size]) video_thumbnail = models.ImageField(upload_to='videos/%y/thumbnails', blank=True, validators=[video_thumbnail_file_size]) So I know how to compress an image like this using PIL: class Post(models.Model): # Stuff From Before def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) So my question is can I do something like this, except to compress a video? -
My view will only update if I restart my Django server
I am fetching data from a database and displaying it on the webpage. However, if I make a change to the table in the database my view will not update on a page reload. The view only displays the most recent changes when I restart my django server. Why is this happening? views.py def home(request): read_table = f"""SELECT DISTINCT name_value FROM {table_attributes};""" table_names = db.read(sql_statement=read_table, connection=connection) table_names_dict = dict(table_names['table_value']) context = {'table_names': table_names_dict.values()} return render(request, 'home.html', context) -
Can we make Notes management system app completely in Python?
I want to make an notes management app in python.Is it possible to make that app completely in python? if it possible then how i start -
not able to query foreign key in graphene django
i have a models in which there is a foreign key which is (User) and a charfield , on my schema.py i have set up everything but on api i am only able to call the charfield and the id of the object, i am not trying to filter i just want to get all data of that model models.py class Accounts(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) bio = models.TextField() def __str__(self): return f'{self.username} account' schema.py class AccountsType(DjangoObjectType): class Meta: model = Accounts fields = ['username','bio','id'] class Query(graphene.ObjectType): accounts = graphene.List(AccountsType) def resolve_accounts(root,info): return Accounts.objects.all() schema = graphene.Schema(query=Query) -
How to Ajax in Django with django query?
Like when you search a page with conditions, the results come out in ajax. I want to put the html page of 'test.html' in the of 'index.html'. pass the value I received in form in 'index.html' to 'views.py' in ajax and bring in 'test.html'. How should I handle it with ajax? index.html ... <FORM NAME="myForm" method="GET"> <label for="0"><INPUT TYPE="radio" NAME="gender" value="F" id="0">Female</label> <div class="dropDown"> <a class="btn_drop">select</a> <div class="dropBox"> <ul> <li><label for="10"><INPUT TYPE="checkbox" NAME="age" ONCLICK="toggleShow2(this)" value='10' id='10'>10</label> <div id="sub10" Class="sub"> <label for="101"><INPUT TYPE="checkbox" NAME="category_name[]" value="sci" id="101">sci</label> <label for="102"><INPUT TYPE="checkbox" NAME="category_name[]" value="cartoon" id="102">cartoon</label> <label for="103"><INPUT TYPE="checkbox" NAME="category_name[]" value="teen" id="103">teen</label> </div> </li> </ul> </div> </div> <input type="submit" value="search" id="search_button"> </form> <div id="contentsArea"> </div> ... test.html {%for i in library_list%} <img src="{{i.url}}" alt=""> {{i.book_name}} {%endfor%} views.py def test(request): queryset2 = LibraryList.objects.all() age = request.GET('age') gender = request.GET['gender'] category_name = request.GET.getlist('category_name[]') query2 = Q() for i in category_name: query2 = query2 | Q(category_name__icontains=i) queryset2 = queryset2.filter(query2) result = LibraryList.objects.all().filter( query2 & Q(gender__icontains=gender)) context = { 'library_list': result, } return render(request, 'test.html', context) -
Download documents in docx and csv format
I make a website on Django I have a code with filling out documents in docx and csv format CSV: FILENAME = "static.csv" with open(FILENAME, "w", newline="") as file: columns = ["Date","Price"] writer = csv.DictWriter(file, fieldnames=columns) writer.writeheader() i = 0 a = 0 while i<len(date): while a < len(price): users = [ {"Date": date[i],"Price": price[a]}, ] writer.writerows(users) i+=1 a+=1 docx: doc = DocxTemplate('template.docx') dates = date prices = price tbl_contents = [{'expirationdate': expirationdate, 'price': price} for expirationdate, price in zip(dates, prices)] context = { 'tbl_contents': tbl_contents, 'finalprice': sum(prices) } doc.render(context) doc.save("Static.docx") I need to download these documents. How can this be done? -
Custom Serializers - serializers that do not map directly onto a model
My questions are with regards to Django Rest Framework, and specifically, Custom Serializers - serializers that do not map directly onto a model. I have really done my best to summarize. Assume we have two tables, User Table and User Information table linked by a one-to-one relationship (user being a field in User Information). I created a custom Serializer which combines all fields of both tables and when save() is called, creates a record in both User Table and User Information Table. Observations In the view, serializer.data will be empty. Probably because the serializer does not commit to the db (given that the serializer does not map to one specific model) and therefore serializer.data is not populated. Is this possibly the (most) correct implementation? I cannot get it to work for both read and write (see code below). It seems to work for reading or writing but not both. If the serializer is not mapped to a model, can it read and write or just write? Maybe my Serializer is poorly done? SERIALIZER first_name = serializers.CharField( write_only=True, required=True ) last_name = serializers.CharField( write_only=True, required=True ) phone_number = serializers.CharField( write_only=True, required=True ) email = serializers.CharField( write_only=True, required=True ) national_id = serializers.CharField( … -
Query degenerates into a PK scan when order by is added
I have a query that results in a couple of rows and executes in microseconds, but turns into a primary key scan once an order by is added. explain select * from mcqueen_base_video as v1 left join mcqueen_base_visit as v2 on v1.visit_id = v2.id where v2.protocol_id = 191 and v1.is_valid = TRUE order by v1.id limit 10; QUERY PLAN ----------------------------------------------------------------------------------------------- Limit (cost=0.99..284.38 rows=1 width=543) -> Nested Loop (cost=0.99..23421737.58 rows=82648 width=543) -> Index Scan using mcqueen_base_video_pkey on mcqueen_base_video v1 (cost=0.56..3191817.90 rows=44436676 width=470) Filter: is_valid -> Index Scan using mcqueen_base_visit_pkey on mcqueen_base_visit v2 (cost=0.42..0.45 rows=1 width=69) Index Cond: (id = v1.visit_id) Filter: (protocol_id = 191) (7 rows) This query is generated by Django's ORM and the reason for the order by v1.id limit 10 is the way that django does pagination. I know that order by/limit is a terrible way to paginate large datasets, but even though the table is large, the filters usually result in small result sets. The problem is that the query planner decides to do an index scan and filter on is_valid before determining the join results. I've already tried adding an index on visit_id,is_valid but that did not alter the query plan. If I manually resolve the … -
Slow Django many to many query
I have 9 Million records. It will be 200M soon. It can take 15min + to fetch this: class Follower(): hashtags = models.ManyToManyField( "instagram_data.Hashtag", verbose_name=_("hashtags_name")) class Hashtag(models.Model): name = models.CharField(_("HashtagName"), max_length=150, null=True, blank=True, unique=True) def __str__(self): return self.name Ubunto htop: I think it reverse lookup for all values. I think it will have maybe 2000 records found. What am I doing wrong ? -
Send tasks to two separate workers in celery
I have two tasks in celery and would like to send them to different workers to complete but I am not sure how to do this. I have looked at the task_routes section of the celery documentation and have tried a few things from stackoverflow but no luck. tasks.py @app.task def task1(): does something @app.task def task2(): does something else I have two celery workers and I would like them to focus on one task each so worker1 on task1 and worker2 on task2 celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.conf.timezone = 'Europe/London' app.config_from_object('django.conf:settings') app.conf.update(BROKER_URL=str(os.getenv('REDIS_URL')), CELERY_RESULT_BACKEND=str(os.getenv('REDIS_URL')), broker_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }, redis_backend_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }) app.autodiscover_tasks() Then procfile - web: gunicorn project.wsgi --log-file - worker1: celery -A project worker -l INFO --concurrency=1 -Ofair -n worker1.%h worker2: celery -A project worker -l INFO --concurrency=1 -Ofair -n worker2.%h How do I set the queues up so that worker1 = task1 and worker2 = task2? -
How to get all remaining data after returning data using offset and limit in django
I responded the data result, using offset and limit. After that, what should I do in django when a request to reponse all other than the response data comes in? first_response = Foo.objects.all()[:10] after_response = Foo.objects.all()[10:] ??? -
How does one display a list in Django + JavaScript element by element?
To start, the version of my problem I'm presenting here is simplified to make my question clearer. Let's say I want to make a Django web app, which takes some data from user, runs some Python logic and returns a list of objects. An object has 2 values, I want to display the values of each list member one by one, moving on to the next object after X seconds or after the user presses the button. I understand that I'll probably have to get JavaScript involved...I'm really a newbie to JS and I was wondering whether you faced a similar issue and have some useful links or advice. Thanks in advance :) -
Django Heroku: Adding secret key to heroku does not work
I'm trying to add my SECRET_KEY environment variable to heroku using the command: heroku config:set SECRET_KEY='mysecretkey' The command won't even be executed because it says to a part of my secret key "cannot be processed syntactically at this point" (it may be a bit different in english, my command line runs in german. That's just my translation). -
NameError: name '_' is not defined in django
class Food(models.Model): File "D:\Django\restaurant\foods\models.py", line 7, in Food description = models.CharField(("توضیحات"), max_length=50) NameError: name '' is not defined -
Static file (images & CSS for admin) is not loading
On my Django website When I am making DEBUG = True Images are not loading. Please find my Dir structure and code. Settings.py STATIC_DIR=os.path.join(BASE_DIR,'static') STATIC_URL = '/static/admin/' STATICFILES_DIRS=[ STATIC_DIR, ] MEDIA_URL = "/abcd/" MEDIA_ROOT = BASE_DIR INSTALLED_APPS = [ ------ 'django.contrib.staticfiles', -- - - - - - ] Models.py class Product(models.Model): " " " - -- - - -- - - image = models.ImageField(upload_to='upload/products/', default='',null=True, blank=True) """"""""" class PostImage(models.Model): post = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='upload/products/') urls.py from django.conf.urls.static import static urlpatterns = [ """"""", ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML file: {% if product.image %} <img class="rounded-circle" src="{{product.image.url}}" alt=".." height="45px" width="45px"> {% endif %} here If I am changing Debug=False It is working as expected but when it is True images are not loading and I admin page CSS is not working. Can anyone help me with steps on how to resolve this problem?