Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting difficulty in loading image in react django project
Have tried all available solutions. My settings.py is here STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) Home.js file, which is the front end home page is here <Image bordered rounded size="large" src={"/static/2461.jpg"} /> <div> <img src={'/static/2461.jpg'} /> </div> <div> <img src={'/static/https://images-na.ssl-images-amazon.com/images/M/MV5BMDg2YTI0YmQtYzgwMi00Zjk4LWJkZjgtYjg0ZDE2ODUzY2R'} /> </div> and have placed assets folder topmost in the hierarchy. I would be helpful if someone can help me in resolving this issue. -
Django/Python: update select options with value of another select
I have a Django project with a randomization app I want data to be displayed based on user's site and right associated with this site by default, data displayed are data associated with user profile (site and right) I use ajax request to update data In the 2nd picture below, user can select a site and links in the dropdown list "Randomization" are displayed or not, based on site selected I have use a custom middleware (to initialize and update data), context_processor (to make data available in all templates) and session datas (to make data available in all views) to manage data associated with user and site selected I don't know if it is the correct way doing this but it seems to work but I have another select 'Patient code number' (picture below) I would like to update with ajax also based on site selected and I do not manage to do it. I am lost in my algo list of patients (name 'patients') seems to be is correctly updated in stock function called via ajax I try to add an another ajax request in script.js that is called after the first ajax request on the same click event … -
Stream dynamic audio file with django
I have a Django web application, I want to stream a dynamically generated audio file after a http request. I know that I can generate a stream link using ffmpeg, but I wonder if there is any other ways? -
static image/media files in django
i am unable to load static files with django in my template my files are shown below Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Theme' ] STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIR = [ STATIC_DIR, ] Template/index.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>First App</title> </head> <body> <h1>Hello this is index.html!</h1> <img src="{% static 'images/mark.jpg' %}" alt="My image"> </body> </html> project Direstory This is the projec t directory` -
Get a particular choice from ENUM in django field
I have a model. Lets say class Colors(models.Model): type = models.PositiveIntegerField(choices=choices(Type)) And there is also a ENUM class class Type(Enum): Red = 0 Green = 1 Blue = 2 As I have to use Inlines in Admin so I have used Proxy model inheritence class ColorIns(Colors): class Meta: proxy=True And we have Boy and Girl class having fav color. So that a boy and girl can have same fav color class BoyGirlMap(models.Model): color = models.ForeignKey(ColorIns) boy = models.CharField(max_length=100, null=True, blank=True) girl = models.CharField(max_length=100, null=True, blank=True) Now I have to get only Blue color from the ENUM class. Excluding red and green. How can we filter it out so that in admin only Blue color will come excluding Green, Red. How can I override type field from Colors model in ColorIns model? -
getting error : Cannot start service db: error while creating mount source path '/var/www/trialriskincident-backend/db-init':
i am new here in docker my project is in django python, When i run sudo docker-compose up command, i am getting below error in terminal, can anyone please help me to resolve this issue ? Starting trialriskincident-backend_db_1 ... Starting trialriskincident-backend_app_1 ... error Starting trialriskincident-backend_db_1 ... error ir /var/www: read-only file system ERROR: for trialriskincident-backend_db_1 Cannot start service db: error while creating mount source path '/var/www/trialriskincident-backend/db-init': mkdir /var/www: read-only file system ERROR: for app Cannot start service app: error while creating mount source path '/var/www/trialriskincident-backend': mkdir /var/www: read-only file system ERROR: for db Cannot start service db: error while creating mount source path '/var/www/trialriskincident-backend/db-init': mkdir /var/www: read-only file system ERROR: Encountered errors while bringing up the project. -
Adding data to created sqlite database in Django
I have created two classes in models.py in my application. models.py from django.db import models # Create your models here. class User(models.Model): first_name = models.CharField(max_length=264, unique=True) last_name = models.CharField(max_length=264, unique=True) email = models.CharField(max_length=264,unique=True) def __str__(self): return self.first_name class NewUser(models.Model): categorie = models.ForeignKey('User',on_delete=models.DO_NOTHING) area = models.CharField(max_length=264) def __str__(self): return self.name as shown in my image my (User and New users)tables are created. data is getting added to my (User) table. But when I try to add data to my (New users) table I get this error -
Django database connection with Host and Instances with MSSQL
Im using mssql as the backend for the database.In the setting.py file,I need to use the host name with instance. Due to this, I got the error given below, The above exception (('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]TCP Provider: No connection could be made because the target machine actively refused it.\r\n (10061) (SQLDriverConnect); [08001] [Microsoft][SQL Server Native Client 11.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 11.0]Invalid connection string attribute (0); [08001] [Microsoft][SQL Server Native Client 11.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (10061)')) was the direct cause of the following exception: In setting.py file, DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'xxxxx', 'USER': 'xxx', 'PASSWORD': 'xxxx', 'PORT': '1433', 'HOST': 'aaa\bbb',(hostname\instance) 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', }, } } how could i resolve this error and connect with my DB. Thanks in advance.Please help me sort out. -
Gunicorn not loading react frontend in django react nginx configuration digitalocean
i am trying to deploy django react app on digitalocean with nginx gunicorn. i have created the virtualenv and when i trying to run: gunicorn --bind 0.0.0.0:8000 myproject.wsgi its doesn't load the react front but django backend loading. i am aware of that gunicorn does not static but it loading white page with error: You need to enable JavaScript to run this app. -
How do i notify the user about a webhook In django
Hello ive been having problems with web hooks in django i need a way to notify a user that he/she has made a successful payment am notified about a successful web hook from adding a URL to my processor that sends a payment successful request to my web hook how can i show this to the user to notify if its successful -
Mock Prestodb connection in Django unittest
I have following setup in my project: Django as API server, Postgres as database, Prestodb for my datastore queries. Postgres is storing django related stuff only while data is stored and fetched through prestodb using raw queries. My challenge is that I want to mock connection of prestodb and all its methods in unit-tests and assert my APIs. Currently I am able to mock main query method of presto client that returns mocked data but when connection is not available tests are failed. Mock for query method decorator looks like this @mock.patch.object(PrestoClient, 'get_select_query_data', mocked_presto_response) If I mock connection class then all other methods like cursor and execute doesn't work. What should be the parameters for mocked connection or is there a better way to mock databases? -
Calling of ajax as dynamic values coming from python list value in html inside for loop in django template
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <title>Images uploaded by you</title> </head> <style> .column { float: left; width: 30%; padding: 0 10px; } .imgButton{ text-align: left; margin-left: 44px; ; } .button { background-color: #818181; color: black; font-size: 16px; padding: 5px 20px; border-radius: 5px; border: 0px; } </style> <p> <h2>All Posts:</h2> <div> {% for btnid,imag,cnt in tuple %}--these variable is coming from python tuple where 3 col are presnt <p><li style="list-style-type: none"><img src="{{media_url}}{{imag}}" style="max-width: 100%"></li></p> <div class="imgButton" > <table> <tr> <td><input type="button" id = {{btnid}} class = "button" name = "button1" value="like" onclick="saveLike();"/> Markdown works * fine* till here . function saveLike() { var token = '{{csrf_token}}'; alert(btn_id); $.ajax({ type: 'GET', url: '/like/', headers: {"X-CSRFToken": token}, contentType: "application/json", data: { 'btn_id': {{ btnid }} }, dataType: 'json', success: function (data1) { document.getElementById("{{ btnid }}").innerHTML = data1.message + " " +"Likes"; alert(data1.message); alert("getelementbyid is:likehit"+ "{{ btnid }}") }, error: function() { console.log('fail'); } }); alert("savelike called!!"); </script> {% endfor %} </div> </body> </html> -
How to use a nested serialize for serializing and deserializing data? django-rest-framework
I have following serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') class ProfileSerializer(ModelSerializer): user = UserSerializer() class Meta: model = Profile fields = ('id', 'user', 'name', 'address') when I want to create a profile I should send following data: { "user":{ "username": "test_username", "password": "123456789" }, "name": "David", "address": "Baker St" } my question is, is it possible to just send "user": 5 instead of sending dictionary in case of POST request? -
i'm try django+ajax load the html,but them does't work
No solution has been found yet. I actually want to load the page locally through ajax, I don't need to load it all django code #views.py def test(request): if request.POST: a = request.POST['a'] b = request.POST['b'] data = a + b return HttpResponse(data) return render(request, 'test.html') html code <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> {% load static %} <script src="{% static 'js/csrf.js' %}"></script> <form method="POST"> {% csrf_token %} <input type="text" name="a" id="a"> <input type="text" name="b" id="b"> <input type="submit" value="提交" id='go'> </form> <script> $(document).ready(function(){ $("#go").submit(function(){ var a = $("#a").val() var b = $("#b").val() .ajax({ type: "POST", url: 'test', data: {a: a, b:b, csrfmiddlewaretoken: '{{ csrf_token }}'}, success:function(res){ alert(res); }, }); return false; }); }); </script> Your answer is important to me -
UI for javascript and jquery modules in Django application
I have a django application with all js and jquery modules embedded in django templates between 'script' tags, {% extends "myfile/base.html" %} {% load static %} {% block content %} <!doctype html> <html> <body> <h2>Welcome</h2> <button id="mybtn" ></button> </body> <script type="text/javascript"> $("#mybtn").on("click",function(){ //process some user data //manipulate DOM elements } function myFun(par1,par2){ return par1+par2; } </script> </html> {% endblock %} i wanted to write Unit Test cases for the above jquery and js functions, is it possible to do with this kind of template or do i need to separate the js from this template in to a '.js' file,and load that js in to this template? Is it valid to perform UT for js in django? -
Send linux command with websocket in django and javascript
I need to send a command when opening the terminal I use websocket at the moment and during the execution the server receives the information but does not execute the command this is my code //send data with websocket` var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var ws_url = ws_scheme + '://' + window.location.host + '/ws/'; var ws = new WebSocket(ws_url); setTimeout("go()",2000); function go(){ ws.send(JSON.stringify(["command", "text", "terminal" ])); } and in consumer.py i write this if isinstance(data, list) and data[0] == u'command': command = data[1].strip('\n') self.queue.publish( self.message.reply_channel.name, ['stdin', '{0}\r'.format(command), 'command']) logger.debug('i received ') -
i am working on django for the first time and i got some kind of errors, my hoapital app could not read static files in django
medical_care/setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, #os.path.join(BASE_DIR,'static' ), ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') #it merge and put in the same directory medical_care/templates/index.html {% load static %} Free Medical Hospital Website Template | Smarteyeapps.com <link rel="shortcut icon" href="{% static ' fav.jpg'%} "> <link rel="stylesheet" href="{% static ' css/bootstrap.min.css'%}"> <link rel="stylesheet" href="{% static ' css/fontawsom-all.min.css '%} "> <link rel="stylesheet" href="{% static ' css/animate.css '%}"> medical_care/hospital_app/views.py from django.shortcuts import render Create your views here. def index(request): return render(request, 'index.html') my directory: medical_care/medical_care/ /hospital_app/ /static/images /css /js /templates/index.html the error i have is GET http://127.0.0.1:8000/static/%20css/bootstrap.min.css net::ERR_ABORTED 404 (Not Found) hospital:13 GET http://127.0.0.1:8000/static/%20css/fontawsom-all.min.css%20 net::ERR_ABORTED 404 (Not Found) hospital:15 GET http://127.0.0.1:8000/static/%20css/style.css%20 net::ERR_ABORTED 404 (Not Found) -
Django Custom Email Fields
I was wondering if it was possible to add custom fields to the send_mail function. Following the documentation, I have been able to successfully send an email but the form I am building requires more fields such as date and time. It would look something like this send_mail(event_name, message, date, time, type ,[your_email]) https://docs.djangoproject.com/en/2.1/topics/email/#emailmessage-objects -
The forbidden of migration for the host postgresql django
When I try to use python manage.py migrate for remote postgres db I get a message !!!! The forbidden of migration for the host 192.168.1.235 what i shoud to do? -
Django Template Loop Not Showing & Form Problems
I am having some issues with my template for loop and a few other things. https://dpaste.org/PJGi 1) The loop is not showing up ever since I made changes to views.py. I want to make sure that the views.py is correct. I think it might have to do with the def get() statement? 2) This keeps getting passed into my URL when I click submit: ?csrfmiddlewaretoken=TOKEN. Is that normal? Regular HTML without forms.py never did this. 3) Recaptcha is not printing the result statements to the console when I click submit. Is that normal for GET requests? I want to make sure the recaptcha is working. object_list is the default context object that has been passed in from the class based view CourseListView. The object_list is a list of all the course models in model = Course -
LOGIN_URL nao redireciona para home [closed]
setting.py está assim: ` LOGIN_URL = '/' LOGOUT_REDIRECT_URL = 'LOGIN_URL' ` login.html está assim: ` <form action="." method="GET"> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{ form|crispy }} <button type="submit" class="btn btn-primary btn-block" >Login</button> </form> ` projeto/urls está assim: ´ path('accounts/', include('django.contrib.auth.urls')), ´ mas quando entro na url account/login e adiciono o login senha e envio o formulario rececbo o seguinte erro: ´ Using the URLconf defined in projeto.urls, Django tried these URL patterns, in this order: admin/ [name='task-list'] task/<int:id> [name='task-view'] newtask/ [name='new-task'] edit/<int:id> [name='edit-task'] delete/<int:id> [name='delete-task'] accounts/ login/ [name='login'] accounts/ logout/ [name='logout'] accounts/ password_change/ [name='password_change'] accounts/ password_change/done/ [name='password_change_done'] accounts/ password_reset/ [name='password_reset'] accounts/ password_reset/done/ [name='password_reset_done'] accounts/ reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/ reset/done/ [name='password_reset_complete'] The current path, accounts/profile/, didn't match any of these. ´ podem me ajudar? -
How to autocomplete field by selecting a data from dropdown in django template?
I have 2 models. I am posting Instruction course. want to display kos_no from Membership model when i select MemberShip from a dropdown in django template but i unable to do that.Here is my code. #1st model class MemberShip(models.Model): name = models.CharField(max_length=10, null=True, blank=True) kos_no = models.PositiveIntegerField(blank=True, null=True) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return str(self.name) #2nd model class InstructionCourse(models.Model): title = models.TextField(blank=True, null=True) chief_instructor_name = models.ForeignKey(MemberShip, on_delete=models.SET_NULL, blank=True, null=True,related_name='chief_auther_ofinst') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.title #views.py def Add_InstructionCourse(request): if request.method == 'POST': add_inst = InstructionCourse() add_inst.title = request.POST['title'] add_inst.chief_instructor_name_id = request.POST['chief_instructor_name'] add_inst.save() member_name_list = MemberShip.objects.all() returnrender(request,'instructioncourse/add_instruction_course.html'{'member_name_list':member_name_list}) //add_instruction_course.html <div class="form-group row"> <label class="col-sm-2 col-form-label control-label">Chief Instructor's name:</label> <div class="col-sm-10"> <select required id="mem_id" style="width:auto" name="chief_instructor_name" class="form-control select2_demo_1"> <option value="" selected="" disabled=""></option> {% for each in member_name_list %} <option value="{{ each.id }}">{{ each }}</option> {% endfor %} </select> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label control-label">Kos no:</label> <div class="col-sm-10"> <select required id="kos_id" style="width:auto" name="kos_no" class="form-control select2_demo_1"> <option value="" selected="" disabled=""></option> {% for each in member_name_list %} <option value="{{ each.id }}"></option> {% endfor %} </select> </div> </div> -
django rest framework how to save mutiple phone number and email?
In Django framework, I have a model like this: class Employee(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE,related_name='organization_user') added_by = models.ForeignKey(Hr, on_delete=models.CASCADE, related_name='added_user') email = models.CharField(max_length=30, null=True, blank=True) phone = models.CharField(max_length=30, null=True, blank=True) The Employee is not a Django auth user, and I need to save the employee with multiple emails and phone numbers. I am using the SQLite database it's not having ArrayField as a model option. Already tried like this : phon1='9400' (already in db) phon2='9411' (input number) phon = phon1 +','+phon2 '9400,9411' But here is the chance to create duplicate phone numbers. Then how can I save the employee with multiple fields? -
sending emails to users registered to a django application
I am working on a django project. I the django project, I have a form for registering users to a service. Once the users are registered, I should be able to send promotional emails to them. For sending the emails itself, I am using mailchimp. THis is my code so far models.py class RegistrationModel(models.Model): firstName = models.CharField(max_length=200) lastName = models.CharField(max_length=200) email = models.EmailField(max_length=70) phone = models.IntegerField() address1 = models.CharField(max_length=200) address2 = models.CharField(max_length=200, blank=True) city = models.CharField(max_length=200) state = models.CharField(max_length=200) pincode = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) def publish(self): self.save() def __str__(self): return self.email forms.py from .models import RegistrationModel class RegistrationForm(forms.ModelForm): class Meta: model = VittalParivar widgets = { 'firstName': forms.TextInput(attrs={'placeholder': 'First Name'}), 'lastName': forms.TextInput(attrs={'placeholder': 'Last Name'}), 'email': forms.TextInput(attrs={'placeholder': 'Email'}), 'phone': forms.TextInput(attrs={'placeholder': 'Phone Number'}), 'address1': forms.TextInput(attrs={'placeholder': 'Address1'}), 'address2': forms.TextInput(attrs={'placeholder': 'Address2'}), 'city': forms.TextInput(attrs={'placeholder': 'City'}), 'state': forms.TextInput(attrs={'placeholder': 'State'}), 'pincode': forms.TextInput(attrs={'placeholder': 'Pincode'}), } fields = ('firstName', 'lastName', 'email', 'phone', 'address1', 'address2', 'city', 'state', 'pincode') settings.py MAILCHIMP_API_KEY = 'I have added the api key here' MAILCHIMP_DATA_CENTER = 'I have added the data center here' MAILCHIMP_EMAIL_LIST_ID = 'I have added the audience id here' views.py from django.conf import settings from django.shortcuts import render, redirect from django.core.mail import send_mail from django.http import HttpResponseRedirect from .models import RegistrationModel from … -
trying to get data from text file to insert into database
I am got stuck to read data from text file which I want to insert into database. here's my models.py file ..the text file is saved in static folder. settings.py: STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR,'static_cdn') STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] urls.py: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py: from django.db import models import os from django.conf import settings # Create your models here. class Book(models.Model): title = models.CharField(max_length=100) author=models.CharField(max_length=20,blank=True) @classmethod def create(cls, title,author): obj = cls(title=title,author=author) # do something with the book return obj file=open(os.path.join(settings.BASE_DIR,'/static/product.txt','r')) line=file.readline() for lines in line: split_line=lines.split("|") a=split_line[0] b=split_line[1] obj=Book.create(a,b) obj.save() please help me ..thanks in advance