Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get the list of related objects in django
I have 3 models: class Node(models.Model): ID = models.DecimalField(max_digits=19, decimal_places=10) name = models.CharField(default='node', max_length=32) connexion = models.CharField(max_length=255) # Many2one fields | Foreign keys: firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True) class ScheduledAction(models.Model): date = models.DateTimeField(default=datetime.now, blank=True) firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True) node_ids = models.ManyToManyField(Node) I want in ScheduledAction form to show, for a selected firm, the list of its related nodes. Normally I should do this by get: class ScheduledActionForm(forms.ModelForm): date = forms.DateTimeField() firm = forms.ModelChoiceField(queryset=Firme.objects.all()) node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.get(firm_id=firm.id), widget=forms.CheckboxSelectMultiple) class Meta: model = ScheduledAction fields = [ 'date', 'firm', 'node_ids' ] But I got this error: AttributeError: 'ModelChoiceField' object has no attribute 'id' How can I fix this? -
Django websockets auth
I use tornado + sockjs for websockets and Django rest framework for main app. Also I use rest-framework-jwt for auth on Django app. Now I have to determine user in tornado. How I see it: 1. User send jwt in message when sockjs connected to tornado server. 2. Tornado server parse jwt and determine is valid jwt or not? But for this solution I have to read database. But this operation is sync which is not good, because tornado is async. Also I thought use Celery. When user connected to tornado, tornado creats task for celery and in this task jwt will be parsed. In that case solution is not blocking tornado. But how then to notice user via websockets about check jwt? -
Changing border of group of cells in excell to thick box border with xlsxwriter
I am trying to change box border of some excell cells to "Thick Box Border". I am using django 1.9.5 and python 2.7.5 and xlsxwriter for excell. import xlsxwriter workbook = xlsxwriter.Workbook('bordertest.xlsx') worksheet = workbook.add_worksheet() format = workbook.add_format({'border': 2}) worksheet.write('B3', 'Border2', format) This is working for one cell. But i want to apply thick box border around some group of cells like below. I couldn't figure it out. I want to apply thick border to rectangle block of cells between B4-G4 & B8-G8. Between red dots the lines will be bold. But cells in the red dotted rectangle area, will be normal border. So different color group of cells will be seperated with thick border. -
Remove decimal point from number passed to django template?
I am using stripe to process payments with a django web application. The prices in the database are stored in decimal format, e.g. 100.00 Stripe takes this as $1, and ignores everything to the right of the decimal point. I need to remove the decimal point when passing this number to Stripe. Can I do this within the django template? -
Django - Supervisor : exited too quickly gunicorn-error.log(ValueError: Empty module name)
I'm fairly new to coding, this is my first deployment. I'm following this guide for deployment on digitalocean. When running sudo supervisorctl status mhh I get this error Exited too quickly (process log may have details) and log/gunicorn-error.log contains following [3000] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/victor/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/victor/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/victor/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi=self.app.wsgi() File "/home/victor/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable=self.load() File "/home/victor/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/victor/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/victor/local/lib/python2.7/site-packages/gunicorn/utils.py", line 350, in import_app __import__(module) ValueError:Empty module name Here are the relevent config /home/victor/bin/gunicorn_start #!/bin/bash NAME="mhh" DIR=/home/victor/mhh USER=victor GROUP=victor WORKERS=3 BIND=unix:/home/victor/run/gunicorn.sock DJANGO_SETTINGS_MODULE=mhh.settings DJANGO_WSGI_MODULE=mhh.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- /etc/supervisor/conf.d/mhh.conf [program:mhh] command=/home/victor/bin/gunicorn_start directory=/home/victor/mhh/mhh user=victor autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/victor/logs/gunicorn-error.log -
"error": "invalid_client" django-oauth-toolkit
I am using django rest framework with django-oauth-toolkit. When i request access token on my localhost it gives me the access token as shown below ~/django_app$ curl -X POST -d "grant_type=password&username=<Your-username>&password=<your-password>" -u"<client-id>:<client-secret>" http://localhost:8000/o/token/ {"access_token": "8u92BMmeZxvto244CE0eNHdLYWhWSa", "expires_in": 36000, "refresh_token": "faW06KKK71ZN74bx32KchMXGn8yjpV", "scope": "read write", "token_type": "Bearer"} But when i request the access token from the same project hosted on live server, it give me error as invalid_client. ~/django_app$ curl -X POST -d "grant_type=password&username=<Your-username>&password=<your-password>" -u"<client-id>:<client-secret>" http://<your-domain>/o/token/ { "error": "invalid_client" } I am not able to understand where is the problem coming from. I have searched a lot and didn't find the right answer. Please advise me what to do to get rid of this error. -
Displaying dynamic data in google barchart using django and jquery
I have a table with a long list of ward number and other data. Many of the ward number are duplicates. I want to display the list of ward number without any duplicate ward number in x-axix and the sum of repeated ward number in y-axis. I'm unable to display the json data in barchart. I pass json data from view to template as given below: Array(52)0: {ward_no: "9"}1: {ward_no: "11"}2: {ward_no: "5"}3: {ward_no: "12"}4: {ward_no: "1"}5: {ward_no: "10"}6: {ward_no: "11"}7: {ward_no: "12"}8: {ward_no: "14"}9: {ward_no: "11"}10: {ward_no: "1"}11: {ward_no: "11"}12: {ward_no: "13"}13: {ward_no: "11"}14: {ward_no: "2"}15: {ward_no: "9"}16: {ward_no: "5"}17: {ward_no: "5"}18: {ward_no: "6"}19: {ward_no: "7"}20: {ward_no: "1"}21: {ward_no: "2"}22: {ward_no: "1"}23: {ward_no: "12"}24: {ward_no: "3"}25: {ward_no: "3"}26: {ward_no: "4"}27: {ward_no: "1"}28: {ward_no: "2"}29: {ward_no: "3"}30: {ward_no: "8"}31: {ward_no: "2"}32: {ward_no: "5"}33: {ward_no: "2"}34: {ward_no: "3"}35: {ward_no: "2"}36: {ward_no: "12"}37: {ward_no: "11"}38: {ward_no: "11"}39: {ward_no: "11"}40: {ward_no: "11"}41: {ward_no: "4"}42: {ward_no: "11"}43: {ward_no: "11"}44: {ward_no: "11"}45: {ward_no: "11"}46: {ward_no: "11"}47: {ward_no: "11"}48: {ward_no: "11"}49: {ward_no: "11"}50: {ward_no: "11"}51: {ward_no: "11"}length: 52__proto__: Array(0) Models.py class NewRegistration(models.Model): fiscalyear = models.ForeignKey(system_settings.models.FiscalYear) registration_date = models.DateField(max_length=20) date_and_time = models.DateTimeField(auto_now_add=True) houseowner_name_np = models.CharField(max_length=50) ward_no = models.ForeignKey(system_settings.models.Wardno) construction_type = models.ForeignKey(system_settings.models.ConstructionType) cen = models.IntegerField() is_forwarded = models.BooleanField(default=False) … -
Can't deploy django app with django-allauth to heroku
When I want to deploy my Django app to heroku with git push heroku master, I got an error like this: remote: -----> Python app detected remote: ! No 'Pipfile.lock' found! We recommend you commit this into your repository. remote: -----> Installing pip remote: -----> Installing python-3.6.7 remote: -----> Installing dependencies with Pipenv 2018.5.18… remote: Installing dependencies from Pipfile… remote: -----> Installing SQLite3 remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'allauth' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update … -
how to upload snapshot from webcam of client side to image field in Django?
welcome, I don't Know how to upload snapshot from webcam of client side to image field in Django I try to do some thing but I can't to do it . here is my code: models.py class Attendance_Model_IN(models.Model): First_Name= models.CharField(max_length=40) Last_Name= models.CharField(max_length=40) User_Name=models.CharField(max_length=40) Date_Time_IN=models.DateTimeField() Image= models.ImageField(blank=True,upload_to="chapters/%y/%m/%D/") class Attendance_Model_Out(models.Model): First_Name= models.CharField(max_length=40) Last_Name= models.CharField(max_length=40) User_Name=models.CharField(max_length=40) Date_Time_OUT=models.DateTimeField() Image= models.ImageField(blank=True,upload_to="chapters/%y/%m/%D/") html code <html> {% load staticfiles %} <head> <link rel="stylesheet" type="text/css" href="{% static 'app/content/main.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'app/content/site.css' %}" /> </head> <body> <div class="booth"> <video id="video" width="400" height="300"></video> <a href="#" id="capture" class="booth-capture-button">Take Photo</a> <canvas id="canvas" width="400" height="300"></canvas> <img src="" alt="photo of you" id="photo"/> </div> <div id="signdiv" style="display:none;"> <form method="POST"> {% csrf_token %} <input type="submit" name="signin" value="Sign In" class="btn btn-default" /> <input type="submit" name="signout" value="Sign Out" /> </form> </div> <script src="{% static 'app/scripts/photo.js' %}"></script> </body> </html> JavaScript code (function() { var video = document.getElementById('video'), canvas = document.getElementById('canvas'), context = canvas.getContext('2d'); photo = document.getElementById('photo'), vendorUrl = window.URL || window.webkitURL; navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; navigator.getMedia({ video: true, audio: false }, function(stream) { video.srcObject = stream; video.play(); }, function(error) { }); document.getElementById('capture').addEventListener('click', function () { context.drawImage(video, 0, 0, 400, 300); photo.setAttribute('src', … -
Django - Logout Redirect to Login Page
i am trying to redirect to login page after logout but some issues are coming. urls.py This is my actual logout routes and it works for me but it does not redirect me to login page path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), Changing logout.html -> login.html It destroys the session and logout the user but the problem is that when i click logout it redirects to login page but login input fields are not showing path('logout/', auth_views.LogoutView.as_view(template_name='users/login.html'), name='logout'), And if i am using below path(route). It is not destroying session nor logout path('login/', auth_views.LogoutView.as_view(template_name='users/login.html'), name='logout'), -
Django - Grabbing data from a sequence of forms and saving them at once
Using django, I want to grab data from multiple forms before saving it to database, the purpose is to force user to enter all the data required. How can I achieve this? Note: Currently I'm using html tabs for my sequence of forms. Thanks, Majid -
Function takes too much time to process in loop from database(3000 times)
I am calling a function in loop of 3000 time . I am calling that function and getting some dictionary from that function but it takes time . I am fetching data from database which gives me approximately 3000 rows and i am looping that rows and calling function in that loop which fetch data from database and returns dictionary but it takes time . Code: def test(request, uni_id): try: Obj = get_object_or_404(tabl_name, id=uni_id) except: Obj = None dict = {} if Obj:outlet_info dict['data1'] = Obj.id dict['data2'] = Obj.name dict['data3'] = Obj.eg dict['data4'] = Obj.access return dict cursor.execute('''SELECT cd.name, cd.no,ofk.demo_id FROM `main_table` as myo LEFT JOIN `table1` as emt ON emt.some_id = myo.some1_id LEFT JOIN `table2` as ofk ON ofk.id = myo.kit_id LEFT JOIN `table3` as cd ON cd.eg_id = myo.eg_id WHERE emt.type='test'''' result = dictfetchall(cursor) tmp_list, tmp_dict = [], {} for res in result: tmp_dict['name'] = res['name'] tmp_dict['no'] = res['no'] info = test(request,res['demo_id']) tmp_dict['data1'] = info['data1'] tmp_list.append(tmp_dict.copy()) Here I am getting demo_id from query and passing that to another query using function test to fetch data therefore it is taking too much time . Can anyone tell me how to improve the speed or include demo_id to main query … -
nginx index page coming instead of actual website in route 53 with ec2 instance
I have hosted my django website in aws ec2 instance with below ip and pointed to below domain 18.221.162.213 http://govtcarrier.in/ When i am going 18.221.162.213 in my browser it is coming my website but when i am going http://govtcarrier.in/ it is showing nginx welcome page. Please check the screenshots below -
Django models field import
As an extension of the polling app tutorial from the Django docs, I'm creating user profiles and I want to grab a particular user's response to each question and store it in the database, and be able to list all the responses of a user to all the questions when the user signs in. And also all responses to a question from all the users. The tutorial creates two models : Question and Choice.(many2many). But how do I attach a particular question's choice selected by a particular user, to that same User? Will I have to change the built-in User model for that? In particular, the problem I faced was I tried creating a new model called 'Answers'. It can have either 'User' as the foreign key' OR 'Question' as the FK. But a particular answer belongs to BOTH - USER & QUESTION, i.e, it is the answer to a particular QUESTION marked by a particular USER. So that answer should have reference to BOTH the QUESTION (to which it is the answer/choice) and the USER (who marked that as her/his answer/choice to that particular QUESTION). I'm unable to figure out how to have the 'Answer' link BOTH to the … -
How to do group by on a different attribute and sum on a different attribute in Django?
models.py: class Student(models.Model): total_fees = models.PositiveIntegerField(blank=False) roll_number = models.PositiveIntegerField(blank=False) class StudentTransaction(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, blank=False) amount = models.PositiveIntegerField(blank=False) timestamp = models.DateTimeField(auto_now_add=True, blank=True) admin.py: class StudentTransactionModelAdmin(admin.ModelAdmin): list_display = ['__str__', 'time', 'amount'] def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'student': x = StudentTransaction.objects.order_by().annotate(Sum('amount')).filter(amount__sum__lt=student__total_fees) kwargs["queryset"] = [i.student for i in x] return super().formfield_for_foreignkey(db_field, request, **kwargs) While doing annotate I want to get all transaction amounts summed up for every student in the function formfield_for_foreignkey. I want the actual Student objects, so this can't be done using values. To make it simpler, consider that there are 3 Student objects. One of them has made 2 transactions, another one has made 4 transactions, and the third one hasn't made any transactions. The sum of transaction amounts per student doesn't exceed the student's total_fees. The formfield_for_foreignkey should return all Student objects those who haven't paid their fees yet. The condition is: sum(<all transactions of each student>) is less than <total_fees of that student> Note: Some details are intentionally removed to keep the code as short as possible. If something is missing or will produce an error, do report it. -
How to add more fields in admin while creating AbstractUser
I m trying to create an AbstractUser but when using default UserAdmin form I don't get enough fields in admin. How to add more fields to UserAdmin -
How to perform multiple author search in google books api ? eg: q = author1 or author 2 or author3
I set up a system for based on google books api, I need to get books from a list of authors as user recommendations. is there any way to pass multiple author names in google books api ? I have tried with comma separated author list, but not working -
Queryset based on ForeignKeys in Django
While learning Django I am creating an example app in which I have two types of users; students and educators. Educators can create Study sections and students can choose which they would like to participate in (just a BooleanField yes or no). I would like to create a "view participants" page for each study so that the educators can see which students are participating in each section. To do this for each study section I need to query all of the student users who marked "yes" to participate in that study section. I am a bit stuck on how to use Django's QuerySet methods to do this. Here is my models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_educator = models.BooleanField(default=False) class Interest(models.Model): ... class Study(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='studies') name = models.CharField(max_length=255) interest = models.ForeignKey(Interest, on_delete=models.CASCADE, related_name='studies') def __str__(self): return self.name class Detail(models.Model): ... class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) interests = models.ManyToManyField(Interest, related_name='interested_students') def get_details(self, study): details = study.details.all().order_by('start_date') return details def __str__(self): return self.user.username class StudentAnswer(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='study_answers') study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='study_participate', null=True) participate = models.BooleanField('Correct answer', default=False) I would like to write a views.py function like this: @method_decorator([login_required, educator_required], name='dispatch') class StudyResultsView(DetailView): … -
Dockerfile ADD . is adding wrong directory
. |-- business_logic | .... | |-- docker-compose.yml |-- src | `-- backend | |-- Dockerfile | |-- manage.py | |-- requirements.txt | `-- webapp | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- utils.py I want Docker to copy ./src/backend/ to /code/ on the container and when I'm running this compose file: version: '3' services: db: image: postgres web: build: context: ./src/backend/ command: ls -l . volumes: - .:/code/ ports: - "8000:8000" depends_on: - db With the Dockerfile under backend: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ I would expect that the Dockerfile-position in the file tree or the context would be the relative path "." in the Dockerfile, but it seems as if "." points to the directory where docker-compose.yml lies. Because the output is following: web_1 | drwxr-xr-x 14 root root 448 Jan 2 01:51 business_logic web_1 | -rw-r--r-- 1 root root 207 Jan 2 03:10 docker-compose.yml web_1 | drwxr-xr-x 3 root root 96 Jan 2 02:34 src web_1 | -rw-r--r-- 1 root root 657 Jan 2 01:51 utils.py How to copy only everything below the backend-folder into code? -
How to override list_editable save?
class MenuPromoAdmin(admin.ModelAdmin): list_editable = ('position', 'sort_by', 'sort_number') list_display = ('id','product', 'category', 'label', 'sort_by', 'position', 'sort_number') raw_id_fields = ('product', 'category') list_filter = [] ordering = ('position','sort_number') fieldsets = [ "Position and Sorting", { 'classes': ('grp-collapse grp-open',), 'fields': ['position', 'sort_by', 'sort_number'] }), "Data", { 'classes': ('grp-collapse grp-open',), 'fields': ['url', 'label', 'title', 'css', 'product', 'category'] }), ] def save_model(self, request, obj, form, change): # do something super(MenuPromoAdmin, self).save_model(request, obj, form, change) admin.site.register(Menu_Promo, MenuPromoAdmin) I tried that, but it simply doesn't work for "mass save" -
Django - OneToOneField Not Populating in Admin
I’m trying to get the username of the current logged in user using OneToOneField to populate in the admin once the user submits a form. The username should go in the user column of admin.py. I’ve tried various methods and still no luck. I’m new to this and this is my first Django application I’m building so I’m not sure what I’m missing. I’m stuck and have no idea what I’m doing so any help is gladly appreciated. Can someone please help? What am I missing? Thanks! Code Below: user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) cc_number = models.CharField(max_length=100) cc_expiration = models.CharField(max_length=100) cc_cvv = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['user']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from user_profile.models import Listing # Register models here. class UserProfileAdmin(admin.ModelAdmin): … -
Django - Variable is not getting send with POST request
Hey im using for my django project typescript to get a specific section from a text to my view but it somehow doesnt work and I dont really know why. Here is my template in which I want the "currentgap" sent to my view after clicking on the submit button. The getSelectionText() method just sets the id 'gap' to a specific string: <form action="editorgapcreate" id=create method="POST"> <script src="../static/textselector.js"></script> <div id="app" onmouseup="getSelectionText()"> This is a test section. </div> {% csrf_token %} <b>Your current selected gap:</b> <p id="currentgap"></p> <input type="hidden" name="gap" id="currentgap"> <button type="submit" name="create_gap">Create gap</button> </form> and here is my view in which I tried calling it: def editorstart(request): if request.method == 'POST': gap = request.POST['gap'] print(gap) return render(request, 'editor_start.html') else: return render(request, 'editor_start.html') The first time using currentgap in my template it displays it correctly but trying to send it to my view with a POST request doesnt work and the print is empty and I dont really know why. -
Protect pages by raising 404
I am learning Django, and I want to protect certain pages by raising 404 if request is not from certain login user. I already foreginkey topic to user. Here is the code to protect topic page. @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: raise Http404 I wonder are there better ways if I want to protect a lot of pages so I don't have to add the same code in every function? -
Django - Custom User Model Username Not Populating in Admin
I’m trying to get the username of the current logged in user that submits a form from the user_profile to populate in the Django admin. The custom user model is located in the users folder & I would like that username to populate under the username field in the Django admin for user_profile. I’ve tried various methods and still no luck. I’m new to this and it’s my first Django application I’m building so I’m not sure what I’m missing. I’m stuck and have no idea what I’m doing so any help is gladly appreciated. What am I missing? Thanks! Code Below: user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import HomeForm from users.models import CustomUser from .models import Listing # Register models here. class UserProfileAdmin(admin.ModelAdmin): model = CustomUser list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'username'] list_filter = ['name', 'zip_code', 'created', 'updated', 'username'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.conf import settings class Listing (models.Model): username = models.CharField(max_length=100, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) … -
How to Access to Already Uploaded Docx Files in Django to search needed words?
I want to edit the needed uploaded file on webpage by searching and replacing the wanted words. How can I get the text of that doc file? I have a filefield in my models and I get the doc files in a list on my webpage,where I am able to delete the needed file or upload a new one. I try to edit the wanted uploaded doc file by creating a function in my views.py. I have tried to use docx module to open the uploaded file, and also have tried io.StringIO() but I did not manage to get the desired output. models.py class DocFile(models.Model): title = models.CharField(max_length=50) agreement = models.FileField(upload_to='') views.py def edit_file(request, upload_id): instance = get_object_or_404(DocFile, id=upload_id) content = instance.agreement.open(mode='rb') variables = [] for line in content: match = re.findall(r"\{(.*?)\}", line.text) variables.append(match) return render(request, 'uploads/file_detail.html', { 'variables': variables }) or def edit_file(request, upload_id): instance = get_object_or_404(DocFile, id=upload_id) # content = instance.agreement.open(mode='rb') content = instance.agreement(upload_id) with open(content, 'rb') as f: instance.agreement = File(f) source = io.StringIO(f) document = Document(source) variables = [] for paragraph in document.paragraphs: match = re.findall(r"\{(.*?)\}", paragraph.text) variables.append(match) for table in document.tables: for row in table.rows: for cell in row.cells: match = re.findall(r"\{(.*?)\}", cell.text) variables.append(match) source.close() …