Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where can I find my pg_hba.conf file (for django app on a2hosting)
I'm deploying my first ever website (it's a Python 3.7, Django 2.2.9 site on a2hosting) and I'm getting the following error when trying to run migrations. django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "xx.xx.xxx.xx", user "xxxxxx", database "xxxxxx", SSL off Googling around, I've gathered that I have to add an entry in the pg_hba.conf file for the particular user. Problem is this is my first experience with Linux, and I can't seem to locate the pg_hba.conf file to test this solution. Please, where can I find this file (relative to my approot)? PS: I've successfully installed Postgresql and SSL for the site. -
How to send an excel file downloaded from a web page when clicked on export to excel through selenium web driver to django app
I have below requirement. 1.Once Django Form is Submitted,when request.POST occurs,call a method passing url,uname and pwd details to open a web page through selenium chrome web driver. 2.click on export to excel button which downloads an excel file. 3.I want this excel file immediately to send as an email attachment through celery tasks. 4.kindly suggest how to proceed further. views.py: def conclude_key_issues(request,id=None): if id: action = 'edit' model = get_object_or_404(ApplyGSP, pk=id) else: action = 'submit' model = keyIssues() if request.method == 'POST': form = keyIssueForm(request.POST, instance=model) if form.is_valid(): new_key_issue_request = form.save(commit=False) new_key_issue_request.user = request.user.username new_key_issue_request.save() form.save_m2m() get_key_issue_list_send_email(sas_url,uname,pwd) return HttpResponseRedirect('/swat_app/') else: form = KeyIssueForm(instance=model) context = {'form': form, 'action': action} selenium.py: def get_key_issue_list_send_email(sas_url,uname,pwd): if getattr(sys, 'frozen', False): print("inside frozen") #Running from exe, so the path to exe is saved in sys._MEIPASS chrome_driver = os.path.join(sys._MEIPASS, "chromedriver.exe") else: print("Inside chrome driverpath") chrome_driver = "C:\Python3.6.0\MyScripts\seleniumwebdriver\chromedriver.exe" # Creating webdriver instance for chrome driver = webdriver.Chrome(executable_path=chrome_driver) driver.set_page_load_timeout(30) while True: try: driver.get(sasurl) # get the Session id of the Parent parentGUID = driver.current_window_handle; print(parentGUID) except Timeoutexception: print("Time out retrying...") continue else: break driver.maximize_window() # Maximizes the browser window driver.implicitly_wait(20) # Implicit wait for 30 secs username_field = driver.find_element_by_xpath("//*[@id='loginForm']/table/tbody/tr[1]/td[3]/input") username_field.send_keys(uname) #sendKeys method is basically used to type … -
Azure webapp deployment docker container not responding to HTTP pings
I am trying to deploy a Django application using Azure Linux WebApp. Looking at the deployment logs for my application itself shows no errors. But there are errors in the Docker logs: ERROR - Container xxx for site xxx has exited, failing site start ERROR - Container xxx didn't respond to HTTP pings on port: 8000, failing site start. See container logs for debugging. I am not familiar with Docker containers and I don't have access to the config file for it. I've tried setting PORT, WEBSITE_PORT, WEBSITES_PORT to 8000 in my Azure application settings but this did not work. Does anybody has some suggestions for how to fix this error? -
Django, How to create multiple mysql database users and grant permission to perform CRUD operations?
I am new to django. I am doing basic sample project on localhost. I know how to do basic CRUD operations on mysql database using django, But before performing CRUD operations on mysql database, I want to create a web-page(HTML) that page will add multiple mysql database users via registration form(With its login credentials) and grant privileges to those users to perform CRUD operations, Because in settings.py file by default we give root username and its password, But how can we add multiple mysql database users to perform CRUD operations on mysql database in django project app? -
Unable to fire a docker build build for Django and Mysql
I am building an application with Djnago and MySql. I want to use docker for the deployment of my application. I have prepared a requirement.txt, docker-compose.yml and a Dockerfile docker-compose.yml version: "3" services: law-application: restart: always build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" depends_on: - mysql_db mysql_db: image: mysql:latest command: mysqld --default-authentication-plugin=mysql_native_password volumes: - "./mysql:/var/lib/mysql" ports: - "3306:3306" restart: always environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=root - MYSQL_USER=root - MYSQL_PASSWORD=root requirements.txt django>=2.1.3,<2.2.0 djangorestframework==3.11.0 mysqlclient==1.4.6 Dockerfile FROM python:3.7-alpine MAINTAINER Intersources Inc. ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN apt-get update RUN apt-get install python3-dev default-libmysqlclient-dev -y RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D jeet USER jeet settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my-app-db', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'mysql_db', 'PORT': 3307, } } I have been trying to run the command docker build . to build an image from docker file but I get this error. Looks like there is some issue with the MySql connector. I have tried searching for the solution but couldn't found any thing to fix this. I am able to build the image if I … -
Django with Chartjs using csv
Iam trying to use Graphos with my Django html template to grab data from csv, and display a graph. I tried from the documentation https://pypi.org/project/django-graphos/, but the template isnt showing anything. In my views in do this from graphos.sources.csv_file import CSVDataSource def graphos_chart(request): csv_file = open("order_dashboard/Book1.csv") data_source = CSVDataSource(csv_file) return render(request, 'order_dashboard/home.html', {'chart': data_source}) template <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); </script> {{ data_source|safe }} Book1.csv ,January,February,March,April,May,June,July Temperature,7,7,10,15,20,23,26 Precipitation,8.1,14.9,41.0,31.4,42.6,57.5,36.0 What am i doing wrong? Please help me out here. -
Solution this error: Error loading MySQLdb module: No module named MySQLdb?
I'm not professional to work in Django I know this problem has been asked a lot in StackOverflow but I need the end answer to fix this problem with me. I'm using Django 1.9 and python 2.7 and I need to link both of MySQL with Django, I tried everything and I had taken a long time looking for the end of the solution but it's bad. I got nothing I used Pymysql, Mysql-connector-python, Mysql-connector and I tried to install Mysqlclient but I get failed and now I get really disappointed because of this problem. so, this is my last trying and I get this error too: Error loading MySQLdb module: No module named MySQLdb error message. so, How can I run MySQL in any way I mentioned above (Pymysql, etc....) sorry, I'm not fluent at English if there was any wrong DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'students', # the name of database 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': '', 'OPTIONS': { 'autocommit': True, }, } } -
Putting together a complex and changeable query to filter a table
I want to enable filtering on a table. Some of the filters are simple, eg a dropdown to select user. But others are more complex, eg the from date needs to display table rows that have a date that's greater than the filter date. And the search box should search multiple fields in the table. I started attacking the problem by using a lot of IF statements to built a search query based on the filters the user has applied. I then apply the query to model.objects.filter(a_string_built_depending_on_filters). So far so good but it looks like I'm going to have to start using Q() objects. I'm not sure if I can string together Q() queries in the same way. @login_required def entries_show_all(request): journal_entry_filter_form = JournalEntryFilterForm() line_item_filter_form = LineItemFilterForm() order_by = request.GET.get('order_by', '-journal_entry') filter_query = dict() url_params = "" if request.GET.get('user') and int(request.GET.get('user')): filter_query['journal_entry__user'] = str(request.GET.get('user')) url_params+='user='+urllib.parse.quote_plus(str(request.GET.get('user')))+'&' if request.GET.get('type'): filter_query['journal_entry__type'] = request.GET.get('type') url_params+='type='+urllib.parse.quote_plus(request.GET.get('type'))+'&' if filter_query: #logger.warning('Filter query:') #logger.warning(filter_query) #logger.warning('URL Params:'+url_params) line_items = LineItem.objects.filter(**filter_query).order_by(order_by) else: logger.warning('Filters have not been set') line_items = LineItem.objects.all().order_by(order_by) paginator = Paginator(line_items,20) page = request.GET.get('page') line_items2 = paginator.get_page(page) return render(request,"journal/entries_show_all.html", {'line_items': line_items2, }) The URL Params variable is used in the template to add to the pagination links, so … -
Conditional validation based on two inputs
I have a model with two fields: class Books(model.Models) status = models.IntegerField( null = False, blank = False, default = None, choices = [(1,'in stock'),(2,'out of stock'),(3,('other, specify below')] ) other = models.TextField( blank = True, null = True, ) I then use a RadioSelect in my form widget to render status and all is well with the world. However, I want to make other required if option 3 in status is selected. How can I do this server side via form validation? E.g. the form should fail validation if choice 3:'other' is selected and other remains blank or null. -
django: inspectdb not generating model file
I am trying to connect to secondary database using ORM but need to create models.py for it. I have read-only access to database. When I am running inspectdb getting below output. Command: python manage.py inspectdb --database my_oracle Output: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models Database entry:setttings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase', }, 'my_oracle': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xyz:1234/ABCDB', 'USER': 'ABC', 'PASSWORD': '1234' }, } -
Adding new field in Django model
I am currently working on a Django project with around 30 models and there are lots of relations(For example, foreign key relations) between the models. My doubt is "After 6 months, let's say I want to add a new field(s) in one of the model/table(s) in models.py, and make migrations, the new migration files will get created without affecting the initial migration files which were created 6 months ago." Will the relations be maintained after adding new columns in different tables? (or) do I have to go to pgadmin console and tweak them accordingly? One way is to erase all the migrations and start fresh, but this is not recommended often especially if there is production data (or) there are frequent changes in the database schema. -
Why django forms instead of html forms?
Hello I am new to Django. I am finding it hard to understand how Django forms work. My question is why to use Django form when we can use HTML forms? -
How to display model help_text in template
I have a model with help_text: class Books(models.Model): title = models.CharField( max_length=255, verbose_name='Book title', help_text='Please enter the book title' ) In my template it is easy enough to display the book title: views.py: class BookDetail(DetailView): model = Books context_object_name = 'book' template.html: {{ book.title }} However, how can I reference the help_text associated with the title model field. E.g. {{book.title.help_text}} -
i can not solve 'set' object is not subscriptable in django rest framework
My django project stopped working recently and is showing me 'set' object is not subscriptable error . I want to know how this error can be solved Here is my 'urls.py' ''' //this is the urls.py and the error arises from here## Heading ## from django.contrib import admin from django.urls import path,include from rest_framework import routers from hotel.views import BookedRoomsViewSet,roomsViewSet,userViewSet,eventViewSet router = routers.DefaultRouter() router.register(r'BookedRooms',BookedRoomsViewSet) router.register(r'Rooms',roomsViewSet) router.register(r'Users',userViewSet) router.register(r'Events',eventViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('',include(router.urls)) ] Here is the 'models.py' file ''' from django.db import models from datetime import date from django.utils import timezone # Create your models here.//models.py class Room(models.Model): Room_no = models.IntegerField() Type = models.CharField(max_length=30) Booked = models.BooleanField(default= False) class BookedRooms(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) phonenumber = models.CharField(max_length=30) roomtype = models.CharField(max_length=20) room = models.ForeignKey(Room,on_delete = models.CASCADE,null = True) class Users(models.Model): username = models.CharField(max_length=30) email = models.EmailField(max_length=30) password = models.CharField(max_length=10) class Events(models.Model): name = models.CharField(max_length=100) details = models.TextField(max_length=300) startDate = models.CharField(max_length=12) startTime = models.TimeField() endDate = models.CharField(max_length=12) endTime = models.TimeField() ''' Here is the 'serializers.py' file ''' from rest_framework import serializers from .models import BookedRooms,Room,Users,Events class RoomSerializers(serializers.HyperlinkedModelSerializer): class Meta: model = BookedRooms fields = ('id','firstname','lastname','phonenumber','roomtype','room') class roomSerializers(serializers.HyperlinkedModelSerializer): class Meta: model = Room fields = ('id','Room_no','Type','Booked') class userSerializers(serializers.HyperlinkedModelSerializer): class Meta: … -
DisallowedHost at / Invalid HTTP_HOST header: 'mydomain'. You may need to add u'mydomain' to ALLOWED_HOSTS
I created droplet with django in digitalocean and added changed my domain name servers to digitalocean's and added my ip as A record. When Debug = False: HTML page when trying to connect website using ip adress: Not Found The requested resource was not found on this server. HTML page when trying to connect website using domain name: Bad Request (400) When Debug = True: HTML page when trying to connect website using ip adress: It worked! Congratulations on your first Django-powered page. Next, start your first app by running python manage.py startapp [app_label]. You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work! HTML page when trying to connect website using domain name: DisallowedHost at / Invalid HTTP_HOST header: 'mydomain'. You may need to add u'mydomain' to ALLOWED_HOSTS. . . . I changed ALLOWED_HOSTS = ip_addresses() to ALLOWED_HOSTS = ['mydomain', ip_addresses()] System Information that may be required: Ubuntu 18.04.3 (LTS) x64 django.VERSION -> (1, 11, 11, 'final', 0) python 3.6.9 nginx/1.14.0 psql (PostgreSQL) 10.10 gunicorn 19.7.1 What is wrong with that? 'How to add domain name to django application' is general question, i guess. -
FloatField in Django is not storing decimal places of a number
In the 'List' class of models.py 'cred' was previously IntegerField which I later updated to FloatField. While getting a number input from user, the integer ones are successfully being saved but lets say user selects 4.5; in such case only 4 is being saved. class List(models.Model): item=models.CharField(max_length=200) desc=models.TextField(default='description!') cred=models.FloatField(default=0) <form action="{% url 'updatecred' %}" method="POST"> {% csrf_token %} <input type="number" min="1" max="25" step=".5" name="Credits" required> <input type="submit" value="Update Credits"> </form> Here,curr is a global variable which is an object of the 'List' class obtained in another function in views.py : def updatecred(request): if request.method=='POST': newcred=request.POST['Credits'] global curr cr=float(newcred) curr.cred=cr curr.save() return redirect('Info') When I try to access curr.cred somewhere else, it doesnt show any decimal point. I even tried using DecimalField but even that doesnt work -
Best approach to define overridable settings in django app?
Fairly new to this, I am coding a reusable Django App and I find myself needing the set up many constants that configure how the application works. However I'd like these constants to be overridable by the final user on its own settings.py file. Which is the best industry-standard approach to achieve this? I need these constants to be available everywhere int the application (models, views, templates, template tags...) I took a look here but I need a bit more explanation. Thank you. https://docs.djangoproject.com/en/3.0/ref/applications/ -
How to raise frontend validation error for UnsupportedFormat in Django import-export
I have my Django-import-export setup. After setting it up, I noticed that only files with .xls, .xlsx and .json extensions are uploadable with CSV, HTML and others raising UnsupportedFormat error. I am having issues raising validation error for these files on the frontend. views.py: def country_data_import(request): if request.method == 'POST': dataform = CountryUploadForm(request.POST, request.FILES) if dataform.is_valid(): country_resource = CountryResource() dataset = Dataset() file = dataform.cleaned_data['file'] import_data = dataset.load(file.read()) result = country_resource.import_data(dataset, dry_run=True) if not import_data: messages.warning(request, 'The data you are trying to upload is wrongly formatted or empty. ' 'Please see the instructions below and try again') return render(request, 'DataManagement/country_import.html') elif not result.has_errors(): country_resource.import_data(dataset, dry_run=False) messages.success(request, 'Data upload was successful') return redirect('data-import-options') else: messages.warning(request, 'The data you are trying to upload is wrongly formatted or empty. Please read ' 'the instructions below and try again.') return render(request, 'DataManagement/country_import.html') else: messages.warning(request, 'Data upload error. Please choose a file') return redirect('country-data-import') return render(request, 'DataManagement/country_import.html') -
how to set a foreign key in setter of django models
I have a property called object that has some values in it witch i need to set one of witch is the id of a foreign key. I parse the values and use setattr() function but i get this error: File "/home/hezardastan/.pyenv/versions/bepa2/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 219, in __set__ self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "'259fe104-cb7f-4cc7-b32f-4bf4d39038ed'": "Rule.workspace" must be a "Workspace" instance. and if i send the object instead of the pk i get this error: File "/home/hezardastan/Desktop/work/bepa2/bepa2/src/rbac/models.py", line 100, in object setattr(self, k, v) File "/home/hezardastan/.pyenv/versions/bepa2/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 223, in __set__ if instance._state.db is None: AttributeError: 'Rule' object has no attribute '_state' here is my setter and workspace is a foreign key and one of the key values of the dict coming back from parse_rri: @object.setter def object(self, value): for k, v in self.parse_rri(value).items(): setattr(self, k, v) -
Django ORM: How to query secondary database which is in read-only mode and no reference in model.py file
I want to query secondary database which is basically a production database. Currently I am using direct query but want to use ORM. My current models.py file looks like below. Here user is providing TABLE name. from django.db import connections # Create your models here. def my_custom_sql(TABLE): with connections["my_oracle"].cursor() as cursor: cursor.execute("select * from {0} where server = 'XYZ';".format(TABLE)) row = cursor.fetchall() return row I want to run same query using Django ORM. Can someone help how to connect to secondary database. I refer to this link but it imports model.py file which i dont think is possible in my case as database is already existing and in read-only mode. -
How to save an extended user in Django?
I'm getting the following error upon registration of a new extended User. Am extended User model is called Player. UNIQUE constraint failed: tournament_player.user_id Here's the view's function that create a new user. view.py def register_player(request): if request.method == 'POST': user_form = UserForm(request.POST) player_form = PlayerForm(request.POST) if user_form.is_valid() and player_form.is_valid(): print('forms are valid') user = user_form.save(commit=False) user.set_password( user_form.cleaned_data['password']) user.save() player = player_form.save(commit=False) player.user = user user.save() messages.success(request, 'Your profile was successfully updated!') return redirect('dashboard') else: user_form = UserForm() player_form = PlayerForm() return render(request, 'registration/register.html', { 'user_form': user_form, 'player_form': player_form }) And these are my forms. Player form has only 2 additional fields. forms.py class UserForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Repeat password'})) username = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})) first_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'})) last_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'})) email = forms.EmailField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] class PlayerForm(forms.ModelForm): phone = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone'})) classement = forms.ChoiceField( choices=Player.PLAYER_CLASSMENT_CHOICES) class Meta: model = Player fields = ('phone', 'classement') -
Django Channels failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
I am stuck in this error,I have tried to change many things to fix but still getting error: (index):42 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/user2/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET Here's below my code: Client Side: var roomName = {{ room_name_json }}; var formdata=$("#form"); var input_val=$("#id_messages"); var chatHolder=$("#chat-items"); loc=window.location; // get the addresses console.log(window.location); var chatSocket = new WebSocket("ws://" +'127.0.0.1:8000' + '/ws/chat/' + roomName + '/'); console.log(chatSocket); // client side receives the message chatSocket.onmessage = function(e) { console.log("message",e) }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; chatSocket.onopen = function(e){ console.log("open",e); formdata.submit(function (event) { event.preventDefault(); var msgText=input_val.val(); var finalData={ 'message':msgText }; chatSocket.send(JSON.stringify(finalData)); formdata[0].reset() }) }; chatSocket.onmessage=function(e){ var chatdata=JSON.parse(e.data); chatHolder.append("<li>"+chatdata.message+ " via "+ chatdata.username +"</li>") }; chatSocket.onerror= function(e){ console.log("error",e) }; Consumer.py: def __init__(self, scope): super().__init__(scope) self.chat_room="" async def websocket_connect(self,event): me=await self.get_user("user") other_user="user2" # let pass static value for now for user 2 thread_obj=await self.get_thread(me,other_user) chat_room=f"thread_{thread_obj.id}" self.chat_room=chat_room await self.channel_layer.group_add( self.chat_room, self.channel_name ) await self.send({ "type": "websocket.accept" }) print(thread_obj) #await asyncio.sleep(10) async def websocket_disconnect(self, event): print("disconnected",event) async def websocket_receive(self, event): front_text=event.get('text',None) if front_text is not None: load_dict_data=json.loads(front_text) msg=load_dict_data.get('message') user=self.scope['user'] username="default" if user.is_authenticated: username=user.username myResponse = { 'message': msg, 'username': username } # broadcast the message await self.channel_layer.group_send( self.chat_room, { "type": "chat_message", "text":json.dumps(myResponse) } … -
How to set forms.RadioSelect() as a required field
I have a simple model: class Books(models.Model): on_loan = models.BooleanField(null=False, blank=False) And a simple form: class BooksForm(forms.ModelForm): class Meta: model = Books fields = '__all__' widgets = { 'on_loan': forms.RadioSelect(choices=[ (True, 'Book is on loan.'), (False, 'Book is not on loan'), ], ) } This form renders fine, with two radio inputs for true/false. However, when I submit the form it still validates as passing. Surely it should fail as the field is required and blank/null? What am I missing? -
Django container cannot find its mysql container
I have built my django docker with hostname server_default and with --network=server_default and ran mysql with same network(mysql container has ran before django server) when I check my mysql container everything is ok but when I run my django server it fails with error : "Can't connect to MySQL server on 'server_default' ([Errno -2] Name or service not known)" I attached to my server container and I couldn't connect to mysql container. server_default is a bridge type. -
Do I have an access to data from ManyToManyField inside overridden save() method?
I have overridden save() method and I tried to iterate my ManyToManyField like: for d in self.service.all(): self.price = 'Something' But it doesn't work. Of course I did "super().save(*args, **kwargs)" before that. Maybe I can't have an access to retrieve data from ManyToManyField inside Model?