Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use existing table for django authentication
I am migrating an App from Java To Django. Since this app has a legacy database how can i use existing table(members) for django authentication without changing its schema. Below is members table Column | Type | Collation | Nullable | Default | Storage | Stats target | Description --------------------+------------------------+-----------+----------+---------+----------+--------------+------------- member_id | bigint | | not null | | plain | | membertypeid | integer | | | | plain | | email | character varying(100) | | | | extended | | password | character varying(100) | | | | extended | | challenge_question | character varying(100) | | | | extended | | challenge_answer | character varying(100) | | | | extended | | datedisabled | character varying(255) | | | | extended | | disabled | boolean | | | | plain | | profiletype | integer | | | | plain | | What i have tried is from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin, BaseUserManager ) class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') try: user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user except: … -
Postgres pgadmin4 error: Unable to connect to server: timeout expired on docker
I'm running a dockerised django app with db settings: docker compose file I want to connect the db to pgadmin4, for that created a pgadmin4 container using docker run -p 5555:80 --name pgadmin -e PGADMIN_DEFAULT_EMAIL='postgresdb' -e PGADMIN_DEFAULT_PASSWORD='password' dpage/pgadmin4; and logged in on chrome with <docker-machine ip>:5555 Initiated a new server there with Host name/address: <ip of running db service> (attained using docker inspect on the running db container) port: 5432 (which is shown as the default port open for db service) When trying to connect its delays for a second and shows this timeout error: "Unable to connect to server: timeout expired on docker" Any workaround for this issue. Although, I can connect using terminal with docker exec -it <container-id> bash, is there any way I can connect using pgadmin4. I'm new to both docker and PostgreSQL. (to check the issue, I've closed the django app and, initiated another postgres container manually using, docker run --name local-db -e POSTGRES_PASSWORD=incorrect -d -p 5432:5432 postgres:alpineand try to connect to pgadmin4 using same way it connects well, but with the django server it fails..) -
DRF nested serializers. Write only primary key, but on read get whole object
I don't need nested create/update operations. I just want to write pk of created object to FK/M2M field and after creating main object get object from this FK/M2M field. Not its primary key. For instance, I got ValueRel and Value models. This is how they are related: class ValueRel(BaseModel): table = models.ForeignKey( Table, on_delete=models.PROTECT, ) object_id = models.CharField(max_length=36) @property def related_object(self): related_model = self.table.get_model() related_object = related_model.objects.filter(pk=self.object_id).first() return related_object class Value(BaseModel): profile = models.ForeignKey( Profile, on_delete=models.SET_NULL, blank=True, null=True, related_name="app_values", ) # I want to write into this field `pk` and get its object value_rel = models.ManyToManyField( ValueRel, blank=True, related_name="values", ) ... After creating ValueRel's instance and writing it to value_rel of Value's instance I want to get ValueRel's instance like object. Actual result (JSON response from API) "value_rel": [ "6a740343-0d37-4e6b-ba56-0c60ac51477f" ] Expecting this: "value_rel": [ { "pk": "6a740343-0d37-4e6b-ba56-0c60ac51477f" "table": "Speciality", "object_id": "02548144-a27d-4c17-a90b-334ccf9e1892", "related_object": "Information system" } ] Is there a way not to adding another field just for expected object representation and get it from value_rel? -
{% translate s %} passed in {% include ... with s=s %} not in .po file
I have a basic feed I am trying to render in my Django project. I have created a feed.html file as a base template for slight variations of the same type of feed. Among those variations, is the header of the feed. Importantly, I want that header to be translated into multiple languages. I have implemented this "variation" idea using {% include "feed.html" with variation=variation %}. However, I am having problems translating those variations. I am trying the following in feed.html: {% translate header %} Then in one of the templates where I want a variation of feed.html I have: {% include "feed.html" with header="Header" %} The problem is, the string "Header" does not make it into any of my .po files and therefore remains untranslatable. What am I doing wrong? Should I use different syntax? -
How to set DB in Django forms.py and models.py, if we are using manual method for multiple database
I'm using manually method to use multiple database with one app and one model. Adding DB details in settings.py Updated views.py queries with "using('dbname')" Because I have set my template, in such a way that user can select the database from dropdown, once it is selected that details are passed to urls.py and inturn to views, so this is dynamic. Could you please help me to understand how we can export this selected DB details to forms.py and models.py, so that my form data will match with the DB which is selected by the user. Thanks and Regards, Hema -
How can i record user audio in my django chat app?
I have a simple chat app like WhatsApp, but users are complaining for not being able to record a voice message as WhatsApp or messenger, I have been searching for over a week but didn't find anything that could help me, I have the audio model ready but what I can't do is record audio from my app directly instead of the user having to leave the website to record audio and save it as a file and then send it. Here is my models.py class Message(models.Model): chat_box = models.ForeignKey( ChatBox, related_name='chat_box', null=True, on_delete=models.CASCADE) message_sender = models.ForeignKey( User, related_name='message_sender', null=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) message = models.TextField(blank=True, null=True) file = models.FileField( upload_to='social_group_message_images', blank=True, null=True) image = models.ImageField( upload_to='social/friend_message_images', blank=True, null=True) audio = models.ImageField( upload_to='social/friend_message_audio', blank=True, null=True) video = models.ImageField( upload_to='social/friend_message_video', blank=True, null=True) my views.py (I'm going to change it later to make it work with ajax): def send_friend_file_message(request, pk): friend = get_object_or_404(User, pk=pk) friend = get_object_or_404(User, pk=pk) chat_box = ChatBox.objects.filter( user_1=request.user, user_2=friend).first() if not chat_box: chat_box = ChatBox.objects.filter( user_1=friend, user_2=request.user).first() message = Message(chat_box=chat_box, message_sender=request.user, file=request.FILES.get('file'), image=request.FILES.get('image'), video=request.FILES.get('video'), audio=request.FILES.get('audio')) message.save() return redirect('social:chat_friend', pk=pk) Finally the html that sends document/video/AUDIO messages: <div class="modal-body"> <div> <!-- Send file --> <form action="{% url 'social:send_friend_file_message' … -
Transferring session from PHP to Django
What is the best and secured way to transfer a session from PHP to Django. I have tried sending parameters through setting sessions and cookies and also in POST method but I was unable to fetch in Cookies and Sessions from PHP. I got the parameters through POST method but I read that sending through POST form action is not secured enough. Why am I not able to get the data from request.COOKIES.get() method ? Is there any other safest and secured way to achieve this and also I want redirect back to PHP when logging out. Here is the code from PHP that I have tried. <?php // Start the session session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Set session variables $_SESSION["Username"] = "username"; $_SESSION["Password"] = "Password"; echo "Session variables are set."; echo $_SESSION["Username"]; echo "<br>"; echo $_SESSION["Password"]; echo "<br><br><br>"; $cookie_name = $_SESSION["Username"]; $cookie_pass = $_SESSION["Password"]; setcookie($cookie_name, $cookie_pass, time() + (86400 * 30), "/"); // 86400 = 1 day if(!isset($_COOKIE[$cookie_name])) { echo "Cookie Username '" . $cookie_name . "' is not set!"; } else { echo "Cookie Username '" . $cookie_name . "' is set!<br>"; echo "Cookie password: " . $_COOKIE[$cookie_name]; } if(isset($_POST['submit'])) { echo $_POST['Username']; echo $_POST['password']; … -
Django: Redirect between two apps from views.py
There are two apps: app_user and app_test. app_user contains a login.html (with custom login forms). The login is realized using a POST request in JS, which calls a function api_login in app_user.views.py. This is my very simple login function (for testing): def api_login(request): # Get post data post = json.loads(request.body) # Get username and password username = post.get('username', None) password = post.get('password', None) # Returned data object data = { "success": False, "username": username, } # Username and password if username == "" or password == "": data['success'] = False return JsonResponse(data) # Check if input is correct user = authenticate(username=username, password=password) if user is not None: data['success'] = True login(request, user) # return JsonResponse(data) <-- No data response, there should be a redirect return redirect('app_test:test-home') else: data['success'] = False return JsonResponse(data) This works well but I want to make a redirect from http://localhost:8000/login/ (included by app_user) to http://localhost:8000/test/ (included by app_test) when the login was successful. My main url pattern (urls.py). from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('test/', include('app_test.urls'), name='app_test'), path('login/', include('app_user.urls'), name='app_login'), ] Url pattern from app_user from django.urls import path from . import views urlpatterns = [ path('', views.view_login, … -
Pass django context data to frontend without inline script in template
I'm already passing django context data to my frontend part using inline scripts in my template file: <script> var variable = "{{ variable }}"; </script> But for security reasons I'm no longer able to do this. My Content Security Policy settings should be configured in a way to prevent inline scripts. Can you help me? Any ideas? -
How to check relation of one object in another models while deleting the object
When we delete object from dajngo admin side dashboard .it gives all the relation of the objects. Refer image.So how can we do this in coading ? Is there any method for that ? -
How to get template field values to Django class based view
Here is my class, I want to take values to this class from my template 'registeredUsers.html' class registeredusers(RegistrationView, PersonnelView): template_name = 'registeredUsers.html' def get_context_data(self, *args, **kwargs): context_dict = {} context_dict['employeeform']= RegistrationForm empDetails= Employee.object.all() return context_dict Template fields <input class="email" type="email" value="{{i.email}}"> <input class="email" type="email" value="{{i.email}}"> -
Django form not saving data to database with custom form
I trying to create a form for a parking lot for the user and the form will input their RFID card, their log history, license plate, name and active or not but I can't get Django form to save it to the database here is my models.py from django.db import models class data(models.Model): RFID = models.CharField(max_length=10) Name = models.CharField(max_length=10) Log = models.TextField() License_Plate = models.CharField(max_length=10) Active = models.BooleanField(default=True) My forms.py from django import forms from .models import data # import data from models.py class data_form(forms.ModelForm): class Meta: model = data fields = ['RFID', 'Name', 'Log', 'License_Plate', 'Active'] class data_custom_form(forms.Form): RFID = forms.CharField( widget=forms.TextInput(attrs={'id': 'user-rfid'}), ) Name = forms.CharField(widget=forms.TextInput( attrs={'id': 'user-name', 'cols': 40, 'rows': 1 })) Log = forms.CharField( widget=forms.TextInput(attrs={'id': 'user-log'}) License_Plate = forms.DecimalField() Active = forms.BooleanField() My views.py from django.shortcuts import render # Create your views here. from .models import data from .forms import data_custom_form def custom_form_view(request): custom_form = data_custom_form() if request.method == 'POST': custom_form = data_custom_form(request.POST) if custom_form.is_valid(): print(custom_form.cleaned_data) else: print(custom_form.errors) info = { 'form': custom_form } return render(request, 'parking.html', info) And my template <DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>parking</title> </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> … -
Heroku Redirect non-www to www on Django website
I currently have a website domain with Bluehost. Bluehost cannot redirect https://example.com to https://www.example.com using 301 redirects since I am not hosting with them. Now in my DNS settings, I have a CNAME (Alias) record that points @ to <string1>.herokudns.com and I have another CNAME (Alias) that points www to <string2>.herokudns.com. I have contacted Bluehost and they said one solution would be to point both www and @ to <string1>.herokudns.com but that does not seem to be a redirection to me. How can I manage to redirect the naked domain to www within Heroku on Python? I cannot test them a lot since Bluehost TTL is 4 hours and I cannot manage to change my configurations fast. Appreciate any help in advance! -
ImportError: cannot import name 'sysconfig' from 'distutils' (/usr/lib/python3.8/distutils/__init__.py)
I installed pip3 using sudo apt-get install python3-pip after that when I run the following command to install django sudo pip3 install django I get this error: Traceback (most recent call last): File "/usr/bin/pip3", line 9, in from pip import main File "/usr/lib/python3/dist-packages/pip/init.py", line 14, in from pip.utils import get_installed_distributions, get_prog File "/usr/lib/python3/dist-packages/pip/utils/init.py", line 23, in from pip.locations import ( File "/usr/lib/python3/dist-packages/pip/locations.py", line 9, in from distutils import sysconfig ImportError: cannot import name 'sysconfig' from 'distutils' (/usr/lib/python3.8/distutils/init.py) How do I fix this? -
Permission.objects.get() method is not working while creating the test database for Unit tests in Django
I Written the Django signals for creating the groups and assign permissions to theses groups for the different user roles but when I am running my test cases then I am getting permission error for creating test database. signal.py from django.contrib.auth.models import Permission, Group def create_group(): permission = Permission.objects.get(codename=codename, contant_type=contant_type) This is working fine for me when I run my migrations but when I am trying to run my test cases then I ma getting error for creating test database. django.contrib.auth.models.DoesNotExist: Permission matching query does not exist. -
Why am I not able to load youtube embed url in django template?
Currently I have been working on django templates with Angular js & I am binding data into django templates. I am facing difficulty when binding youtube video url using Angular js. My code as below. <div class="col-12 col-lg-6 col-xl-5 pb-3 pb-lg-0"><iframe class="agent-video-iframe border-0" height="326px" ng-src="{{agent.video_url }}" width="100%"></iframe></div> <!-- <div class="col-12 col-lg-6 col-xl-5 pb-3 pb-lg-0"><iframe class="agent-video-iframe border-0" height="326px" src="https://www.youtube.com/embed/KYPRQStfRWo" width="100%"></iframe></div>--> When I am loading page with static youtube url , I am able to successfully load youtube video url. When I am loading page with dynamic youtube url(binding using AngularJs), I am not able to load youtube video url. I am not also getting any error message. Please let me know if anyone has idea or solution. Thanks. -
How to retrieve values from the related table created by Django itself?
Recently I am developing a project where I have to create a table that contains 2 many to many fields and 1 foreign key. Through this table Django implicitly creates a related table (for mapping). Now my question is I need to fetch the values from the mapping table. This particular table has no existence in models.py but this is there in the database.How shall I query this one in views.py and what shall I import to make this table visible in views.py. p.s. I am a noob in Django. Any help would really be appreciable. -
Django Oauth Toolkit as SSO server
I want to know can we use Django oauth Toolkit (DOT) as SSO server? I am using Django Rest Framework in backend. Steps I need to achieve : On clicking the Login Button in the client server, it redirects to the server asking to authorise. If already logged in it will return the auth code. If not logged in open the log in prompt. On successful login step 2 will followed. Thanks. -
How to display python output to the page in django
Hey I am making a website with django, I already have the design of the website all that i need is to display a timer, history, different graphs, and other python backend code. I am confident i can write it in python I am just confused on how i can display the output from python to the page. Please help! -
How to genrate fingerprint using NAB Transact in django?
I am using NAB Transact with Python/Django. I found 2 documentation for Nab: Document 1 - https://sourdough.com/sites/default/files/PDF/DirectPostIntegrationGuide.pdf Document 2 - https://www.nab.com.au/content/dam/nabrwd/documents/forms/payment-andmerchants/nab-ecommerce-merchant-application-form.pdf I tried to generate a Fingerprint but couldn't get any response. <form action="https://transact.nab.com.au/test/directpost/genfingerprint" method="post" target="_blank"> <input type="hidden" name="EPS_MERCHANT" value="XYZ0010"> <input type="hidden" name=”EPS_PASSWORD” value=”txnpassword”> <input type="hidden" name="EPS_REFERENCEID" value="Test Reference"> <input type="hidden" name="EPS_AMOUNT" value="100.00"> <input type="hidden" name="EPS_TIMESTAMP" value="20140224221931"> <input type="hidden" name="EPS_RESULTURL" value="https://www.resulturl.com"> <input type="submit" value="OK"> </form> -
How to Upload Image in React js and Django?
I am trying to upload an image using react js on django backend but wheni try to upload pic and check it console.log() image FILE exist there and once i submit the form image file object shsows {} empty i don't why all the time when i submitted for its shows uploaded but all the time image shows null, Here is my code so far what i did. here is also a link of code sandbox link . https://codesandbox.io/s/thirsty-varahamihira-fnusu?file=/src/App.js:0-1494. Thanks. import React, { Component } from "react"; import "./styles.css"; class App extends Component { constructor(props) { super(props); this.state = { image: null }; } handleInputChange = async (event) => { await this.setState({ [event.target.name]: event.target.files[0] // image: event.target.files[0] }); }; handleSubmit = (e) => { e.preventDefault(); const formdata = new FormData(); formdata("image", this.state.image); fetch(`https://inback.herokuapp.com/api/1/blog/image/list/`, { method: "POST", headers: { "Content-Type": "multipart/form-data", Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw" }, body: formdata }) .then((response) => { if (response.ok) { alert("Success"); } else { alert("error"); } }) .catch((err) => { console.log(err); }); }; render() { return ( <div id="other" className=""> <p className="mod" style={{ marginTop: "10px" }}> Uplaod </p> <hr></hr> <form onSubmit={this.handleSubmit}> <input type="file" name="image" onChange={this.handleInputChange} /> <button>Submit</button> </form> </div> ); } } export default App; -
Cannot send mail when close terminal AWS
I deployed a Django app on AWS and when I connect to AWS Linux terminal, it worked. But when close the terminal, the web server cannot send mail anymore. I use EmailMessage in Django. I run server with nginx and gunicorn. -
Django Hosting that has unlimited hosting apps for my Projects
Is there any website which gives unlimited apps to create for django hosting... Means I can upload as many django website as I want for my projects because heroku only gives 5 apps at max -
Django forms not adding textbox & not sending what user looked up
So the django file is not showing the form and at first, I got angry at that so I just used HTML code to create a form but I realized that when I submit it on the form it does not send it to where I want it to send. I was just wondering if you could help. I think the problem with the file is between the relationship between util.py file and the index.html file but I can't see it for some reason. Thank you!! util.py file class Form(forms.Form): searched = forms.CharField(max_length=128, help_text="Please enter the category name.") def get_name(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): searched = form.cleaned_data['searched'] return searched else: form = Form return render(request, "wiki/index.html", { "form" : form }) wiki.urls.py - main urls file from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include("encyclopedia.urls")), path('wiki/', include("encyclopedia.wurls")) ] encyclopedia.urls file from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] views.py file from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "lookUp": util.get_name(request) }) def title(request, name): return render(request, "encyclopedia/titlePage.html", { "entries": util.list_entries(), "name": name, "entry": … -
add a field to a Django model
I am working on this project: https://github.com/mirumee/saleor I want to add a "user_id" column to the product table. So, I added the following code to line 248 https://github.com/mirumee/saleor/blob/master/saleor/product/models.py#L248 account_user = models.ForeignKey( Account_User, related_name="products", on_delete=models.CASCADE, ) However, Django says "NameError: name 'Account_User' is not defined". How could I solve this problem? Thanks