Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django password fields placeholder
I try to enable placeholder at my SignUp form with 4 fields: phone, email, password1, password2. For first two fields all correct, but for password field it doesn't work. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from customuser.models import User from django.forms import TextInput,EmailInput,PasswordInput class SignUpForm(UserCreationForm): class Meta: model = User fields = ('phone', 'email', 'password1', 'password2', 'is_client','is_partner') widgets = { 'email': EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email adress'}), 'phone': TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone number +79011234567'}), 'password1': PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password from numbers and letters of the Latin alphabet'}), 'password2': PasswordInput(attrs={'class': 'form-control', 'placeholder': ' Password confirmation'}), } -
Django: Can I use HttpResponseRedirect() and give it any arguments to be rendered on this page?
I have a Django form which upon validation I want to redirect to a success page. I start at "localhost/upload", submit my form, if it is validated I want to go to localhost/upload/success. The following code works, I just want to be able to pass a context dictionary with some variables in there to render to the page. I can only do this using (hashed out in the views.py code below) return render(request, 'results/success.html', context) but this returns to localhost/upload, but with my success.html template - i want to go to upload/success. Here is my code: views.py: @login_required(login_url='/') def upload(request): """ Upload panel or results. """ if request.method == 'POST': paneluploadform = PanelUploadForm(request.POST, request.FILES) if paneluploadform.is_valid(): paneluploadform.upload() context = {'hi': 'helloasdgja'} # return render(request, 'results/success.html', context) return HttpResponseRedirect('success') else: # print(paneluploadform.errors.as_text) pass else: paneluploadform = PanelUploadForm() context = {'paneluploadform': paneluploadform} return render(request, 'results/upload.html', context) @login_required(login_url='/') def success(request): """ Success view """ return render(request, 'results/success.html') urls.py: from django.conf.urls import url from .views import * urlpatterns = [ url(r'^upload/$', upload), url(r'^upload/success/', success) ] I can use the hashed out return render() line to give my test context, but this returns to "localhost:8000/upload" I want to go to localhost:800/upload/success, but get information from … -
Linking between data in one table and another table
I am working on the linking between the data in one table and another table in django. I have three models, they are defined as below: class Genes(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Genes' class Metabolites(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True) compartment = models.CharField(max_length=255, blank=True, null=True) charge = models.CharField(max_length=255, blank=True, null=True) formula = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Metabolites' class Reactions(models.Model): id = models.CharField(max_length=255, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) metabolites = models.TextField(blank=True, null=True) lower_bound = models.CharField(max_length=255, blank=True, null=True) upper_bound = models.CharField(max_length=255, blank=True, null=True) gene_reaction_rule = models.TextField(blank=True, null=True) subsystem = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Reactions' In my 'reactions' models, there are one column named 'metabolites', and the data of the column are in the structure of: '{'A':-1, 'B':1 }', A and B are id. And in another table, which is called 'metabolites', the the primary key is 'id', and the ids of each metabolites are exactly the same mentioned in table 'Reaction'. Is there any method that when I … -
Django: How to populate form data in Template using class based views
My view is below: class ListAndCreate(CreateView): model = xmpp_buddy_groups form_class = xmpp_buddy_groups_form second_form_class = sip_extension_form template_name = "xmpp/index.html" success_url = reverse_lazy('xmpp:index') my form is below: class xmpp_buddy_groups_form(forms.ModelForm): class Meta: model = xmpp_buddy_groups fields = ['group_name'] class sip_extension_form(forms.ModelForm): class Meta: model = SipExtension fields = ['sip_extension'] widgets = { "sip_extension": forms.Select } I want to populate data of sip_extension in template when I use form in template as {{form.as_p}}. But I have no clue how can I do that. -
Have django-precompiler leave <script type="module"> alone in non-production
For development (no DJANGO_PRODUCTION) I want to leave ES6 modules as-is, that means that if something is {% compress js %} <script src="{% static "path/to/some.js" %}" type="module"></script> {% endcompress %} that it should still be type="module" afterwards. Setting COMPRESS_ENABLED to False does not suffice and if I remove the module precompiler then I am getting the "Couldn't find any precompiler in COMPRESS_PRECOMPILERS setting for mimetype 'module'." error message. Now I could just use cat as a precompiler (COMPRESS_PRECOMPILERS = (('module', 'cat'),)) but the script tags would still be changed and type="module" removed. So is there any way how I can easily prevent that? Preferably without too much special-casing of the non-production case? -
How to convert Query set into a string?
I have data in my database(named File1). I want to access the elements of the database and I wanted to use that data as strings. Further, I wanted to write that string into a file. But when I use File1.objects.all() I get a Query Set. I wanted the elements in the Query set as string. views.py def getfile1(a): data=File1.objects.all() return data example1.py from django.conf.urls import include,url import os os.environ['DJANGO_SETTINGS_MODULE']='websitepc.settings' import django django.setup() from plagiarism.views import getfile1 dbf1=getfile1(2) print(dbf1) exf1=dbf1.get() print(exf1) open("examplefile1.py", "w").close() file = open("examplefile1.py", "w") file.write(exf1) My database consists of text (entered through a form, for further understanding of how I entered data into database click here) The output I get is C:\Users\DELL\PycharmProjects\sum\venv\Scripts\python.exe C:/Users/DELL/Desktop/websitepc/plagiarism/example1.py Traceback (most recent call last): File "C:/Users/DELL/Desktop/websitepc/plagiarism/example1.py", line 16, in <module> file.write(exf1) TypeError: write() argument must be str, not File1 <QuerySet [<File1: abcd>]> abcd Process finished with exit code 1 -
Chatbot - Django channels with websockets or Django-Rest-Framework?
I am going to create dialog system which will allow to upload all types of files and which will have online chat with server. I wonder what should I choose Django channels with websockets or Django-Rest-Framework? Or maybe I should use both - Django-Rest-Framework for registration and sending files and Django channels with websockets for chat? What do you think about it? Maybe I should choose something else? -
Jinja2 - Check to see if one query set elements are in another
So I have two query sets, I'm struggling to find a way to check if query set 1 has all it's elements in query set 2. Query set 2 has more elements than Query set 1 however but I just want to check if Query set 1 has all it's elements in the second. Anyone know any solution to this? So far I have used this in my jinja2 template Queryset 1 = group.dependancies Queryset 2 = SelectedGroups But really I want it to display if the dependancies have been satisfied or not instead of simply listing the missing ones. {% for dp in group.dependancies.all() %} {% if dp not in SelectedGroups.all() %} <p>Missing dependancy {{ dp }}</p> {% endif %} {% endfor %} -
javascript: display a <div> block only if a variable has certain value
I want to display a <div> section in my html file only if a variable(passed from a django view) equals "abc". I sort of think that javascript can be of help here but not sure how- new to both. How can this be achieved? -
Django-filter - how to set ModelChoice choices text?
I have a ModelChoiceFilter which filters objects based on User. class MyModel(Model): user = ForeignKey('User') The problem is that text of choices is User.username and I want to display UserProfile.name if userprofile exists else User.username. Is it possible? -
How to get object-level Validation errors with django-rest-framework?
We are using django-rest-framework for a form with a list of objects. All of these have values and have to be validated on an object-level. This is the POST, sending a list of 3 Steps "steps":[ { "start_date":"2016-03-19", ... }, { "start_date":"2018-06-19", ... }, { "start_date":"2018-06-19", ... } ] Answer with an unspecific Validation Error { "steps":[ { "start_date":[ "The start date must be in the future." // Which one? Step 1, 2 or 3? ] }, ] } How can the answer contain an info about the object, which had an error? Thanks for any help on this! Best regards Jens -
trying to connect to web container from celery container in docker
I have a django channels container and a celery worker and I'm trying to connect to my django channels container inside the celery container, however, I'm finding it difficulty to connect. I have a django server running on http://127.0.0.1:8000/. This is how my docker-compose file looks like web: restart: always tty: true build: ./web/ working_dir: /data/web/fileshiffty expose: - "8000" ports: - "8000:8000" links: - postgres:postgres - redis:redis env_file: env volumes: - ./web:/data/web command: bash -c "python3 manage.py runserver 0.0.0.0:8000" postgres: restart: always image: postgres:latest volumes_from: - data volumes: - ./postgres/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d - ./backups/postgresql:/backup env_file: - env expose: - "5432" redis: restart: always image: redis:latest expose: - "6379" worker: build: ./web/ working_dir: /data/web/fileshiffty command: bash -c "celery -A fileshiffty worker --loglevel=DEBUG" volumes: - ./web:/data/web links: - postgres:postgres - redis:redis - web:web data: restart: always image: alpine volumes: - /var/lib/postgresql command: "true" However, inside on my celery tasks it requires it to connect to a web socket with url ws://127.0.0.1:8000/ws/converter/public/. This is how my tasks looks like # Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task import img2pdf import os import websocket import json import boto from boto.s3.key import Key @shared_task def convert_file_to_pdf(file_name_on_cdn): ws = websocket.WebSocket() ws.connect('ws://web/ws/converter/public/') ws.send(json.dumps({ … -
How to find common range of numbers in a list?
I have a list of models whose prices (Model.objects.values_list('price',flat=True) looks like, x= [1,1,1,2,4,5,6,6,6,6,8,9,9,9,9,9,15] where the numbers are dynamic. I would like to get the common ranges of prices for the objects. so the desired result should be something like, y = [(1,5),(6-8),(9,15) How can I get the desired result? Should I loop through all the values or do there exist some magic functions (Django aggregation with ranges? ) someone point me to the direction. No code necessary. -
Django excessive queries with Inlines
In my Django model I have a class C1 that contains references to other classes as attributes. So each class has a dedicated table in the database, and each attribute of C1 is a foreign key. I define what to display on a page in admin.py, and for each instance of C1, I use an Inline to display each one of its attributes. The thing is, to load such page Django produces a number of mysql queries that increases exponentially with the number of attributes in the class C1 that are in turn instances of other classes. And this leads to excessive waiting delays. My preoccupation is to reduce this delay in an efficient way. This question may be seen as a duplicate to this thread: Slow performance for Django admin inline. However I am not sure whether the accepted solution is optimal. Since I'm a bit confused here I'll ask some naive questions: Is displaying many of a class's attribute a viable solution in general? Should I instead create other pages that display and manipulate very specific and targeted elements/attributes of the said class? Should I do some database-side work and understand which are the redundant queries Django does, … -
Python (Django) Remove Items From Choice List
I have a list of times for my web form and I need to remove some choices from the list based on minimum and maximum minute value. For example I want to only display times between 60 and 180 minutes Django Form: time_list = ( ('', 'Select'), ('15', '15 Minutes'), ('30', '30 Minutes'), ('45', '45 Minutes'), ('60', '60 Minutes'), ('75', '1:15'), ('90', '1:30'), ('105', '1:45'), ('120', '2:00'), ('135', '2:15'), ('150', '2:30'), ('165', '2:45'), ('180', '3:00'), ('240', '4:00'), ('300', '5:00'), ('360', '6:00'), ('420', '7:00'), ('480', '8:00'), ('540', '9:00'), ('600', '10:00'), ('660', '11:00'), ('720', '12:00'), ('1440', '24:00'), ) min_time = 60 #defined in DB max_time = 180 #defined in DB Here I'm unsuccessfully trying to filter the list: tmp = [] for i in time_list: if i > min_time and i < max_time: tmp.append(i) time_list = tmp -
How correctly to write views.py what to deduce a content from admin panel? DJANGO
The main page of the application displays posts - "views.post_go" views.py def post_go(request): all_post = posts.objects.all().order_by("-date")[:18] context = {"post_objects" : all_post} return render(request, "pages/post.html", context) It is necessary on the same page to deduce from admin some more values but with other subjects. views.py def full_slider(request): all_slider = slider.objects.all() context1 = {"slide" : all_slider} return render(request, "pages/slider.html", context1 But how do I now display this block with the template also on the main page ?? urls.py urlpatterns = [ url(r'^$', views.post_go), ] -
How can i display only particular login user details on my html page here it is showing all users details
in my project i want after login when user click on display link it should display only login user information like username,first_name,last_name. in my project i want after login when user click on display link it should display only login user information like username,first_name,last_name. in my project i want after login when user click on display link it should display only login user information like username,first_name,last_name. in my project i want after login when user click on display link it should display only login user information like username,first_name,last_name. in my project i want after login when user click on display link it should display only login user information like username,first_name,last_name. in my project i want after login when user click on display link it should display only login user information like username,first_name,last_name. in my project i want after login when user click on display link it should display only login user information like username,first_name,last_name. in my project i want after login when user click on display link it should display only login user information like username,first_name,last_name. in my project i want after login when user click on display link it should display only login user information like username,first_name,last_name. in my … -
Django: How to populate form data in template
So I am trying to have two forms in single class based view. My view is: class ListAndCreate(CreateView): model = xmpp_buddy_groups form_class = xmpp_buddy_groups_form second_form_class = sip_extension_form template_name = "xmpp/index.html" success_url = reverse_lazy('xmpp:index') def get_context_data(self, **kwargs): context = super(ListAndCreate, self).get_context_data(**kwargs) context['object_list'] = self.model.objects.all() extension = SipExtension.objects.values_list('sip_extension', flat=True) obj = SipExtension.objects.filter(sip_extension=1331).first() for buddy_groups in group_names: for sip in buddy_groups.sipextension_set.all(): sip_extension = sip.sip_extension print(sip_extension) context['extension'] = extension SipExtension.objects.exclude(sip_extension__in=extension) print(extension) context['form'] = self.form_class context['form2'] = self.second_form_class(instance=obj) context['extensions'] = SipExtension.objects.exclude(sip_extension__in=extension) return context My form classes: from django import forms from .models import xmpp_buddy_groups from extensions.models import SipExtension class xmpp_buddy_groups_form(forms.ModelForm): class Meta: model = xmpp_buddy_groups fields = ['group_name'] def __init__(self, *args, **kwargs): super(xmpp_buddy_groups_form, self).__init__(*args, **kwargs) self.fields['group_name'].required = False class sip_extension_form(forms.ModelForm): class Meta: model = SipExtension fields = ['real_name','sip_extension'] widgets = { "sip_extension": forms.Select } def __init__(self, *args, **kwargs): super(sip_extension_form, self).__init__(*args, **kwargs) self.fields['sip_extension'].queryset = \ SipExtension.objects.filter(sip_extension=1331) I am accessing form in template as {{form2.as_p}}. The dropdown appears empty. I want it to populate with 1331. How can I do that? -
Can't display the data entered in form in database
The user enters the data in the form. But the data entered in the form doesn't get displayed in the Database. views.py def add(request): if request.method=='POST': form=FilesCreate(request.POST) if form.is_valid(): form.save() return render(request,'plagiarism/page1.html',{'form':FilesCreate()}) models.py from django.db import models class File1(models.Model): #user=models.ForeignKey(User) firstfile=models.CharField(max_length=1000, default="") #secondfile=models.CharField(max_length=1000) def __str__(self): return self.firstfile plagiarism/page1.html <h1>Enter your first file</h1> <form action="file2/" method="post"> {% csrf_token %} {% for field in form %} {{field}} <input type="submit" value="Submit file1"/> {% endfor %} </form> forms.py from django.forms import ModelForm from django import forms from plagiarism.models import File1,File2 class FilesCreate(ModelForm): class Meta: model=File1 exclude=() widgets={'firstfile':forms.Textarea(attrs={'cols':50,'rows':100})} urls.py from django.conf.urls import url from . import views from . import example3 urlpatterns=[ url(r'^$',views.add,name='add'), url(r'file2/$',views.add2,name='add2'), ] -
How do I reverse the URL for an admin action?
I'm posting this because I searched stackoverflow and docs for a long time without finding an answer -- hopefully this helps somebody out. The question is, for testing purposes, how do I find the URL that's related to admin actions for a specific model? Admin model urls can all be found by reverse(admin:appname_modelname_*), where * is the action (change, delete, etc). But I couldn't find one for the admin actions, and since I was defining custom actions, I'd like to get the url. -
How to save data from an HTML registration page to sqlite3 database using python/Django?
We are working on a project where we have to make a web-based application using python and Django. In this application we have a registration page where users register their information, we want to be able to save this information into a database (sqlite3) but we don't know how to do that. Any help is appreciated! -
Django + Docker + SQLite3 How to mount database to the container?
I had sqlite database with some sort of tables on my localhost and i wanted to copy and paste that database to my server which runs on docker. I created paths like this: db_data: there is my sqlite database which i want to run in my django project. web: there is my whole django project in my docker-compose.yml i writed this volume: version: "3" services: web: build: ./web/ ports: - "8001:8001" volumes: - ./web:/code - /home/cosmo/db_data/db.sqlite3:/code/db.sqlite3 command: python manage.py runserver 0.0.0.0:8001 So i thik that docker will get database in my db_data and will make volume inside my web folder (in my project. There i had database on my localhost so it wouldnt be problem.) But i will paste here settings.py: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } So when i will open my db.sqlite3 inside db_data every tables and content are there, but when i will run container the db.sqlite3 in my project folder (web) is empty. When i will run docker ps command there is no database container maybe this is the problem i dont know. … -
Django, Save email instead of username, table doesnt exist
So i'm trying to set up a form so that it saves the email instead of the username. When i click signup, it says table (app_name.pages_user) Doesn't exist? What am i doing wrong exactly? Heres my code models.py class User(AbstractUser): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.EmailField(max_length=254) mobile_number = models.IntegerField(max_length=13) password = models.CharField(max_length=100) def __unicode__(self): return "" Views.py from pages.forms import SignUpForm def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model User = get_user_model() class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('email', 'first_name', 'last_name', 'password1', 'password2', ) -
jquery datepicker using getDay and getDate
i am trying to pass the value of the variable "currentDate" to variable "day" such that for whatever date the user selects i get the corresponding value in the getDay method, example if the user selects a date 03/21/2018, ie value the using the getDay should be '3' implementation:, for every date selected i want the corresponding value using the getDay welcome.html {% extends 'base.html' %} {% load bootstrap %} {% block content %} <title>welcome</title> <p id="demo"></p> <p id = "demo1"></p> <script> var date = new Date(); document.getElementById("demo").innerHTML = d; </script> <form action = " " method = "GET" role="form"> {% csrf_token %} <table> {{form|bootstrap}} <script> $(document).ready(function() { $('.datepicker').datepicker(); var currentDate = $( ".selector" ).datepicker( "getDate" ); var day = currentDate.getDay(); }); </script> </table> <div class = "form-group"> <input type ="submit" value= "CHECK" class="form control"/> </div> </form> {% endblock %} base.html <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"></script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <title>{% block title %}{% endblock %}</title> </head> <body> <div style = "background-color:#9f9"> <h1>Itam Market</h1> </div> <div style = "background-color:#0fc " > <h1>welcome please pick a date</h1> </div> {% block content %} {% endblock %} {% block footer %} … -
How to use multi database in one django app
I have to use two database in one django app, but the documents only have examples for "each app have a database". The allow_migrate method only provide self, db, app_label, model_name=None, **hints args. How can I set my module property for the router to distinguish modules bind with different database?