Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make the div wide enough when I scroll the screen?
How should I adjust the CSS for the div class="breadcrumbs", if the table is wider than a screen and then background is not till the end. screenshot, where is the problem I would like the dark blue bar to be till the end of the horizontal scroll (not just width of the screen). Now it is like this: div.breadcrumbs { background: var(--breadcrumbs-bg); padding: 10px 40px; border: none; color: var(--breadcrumbs-fg); text-align: left; width:100%; margin:0; } -
Code from bootstrap documentation doesn't work
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarTogglerDemo03"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> I copy pasted this code from bootstrap to make a responsive navbar that turns into a collapsed menu with a button. I copy pasted into the body tag of an empty template in django. bootstrap is loaded, I get everything, even the button when the screen size is small enough. but when I click on the button the menu doesn't expand, the button does nothing. -
why Django admin short_description function not working?
I am trying to make some changes in my django admin panel such as want to show "title" instead of "blog_tile" but I am not understanding why changes not reflecting. class BlogAdmin(admin.ModelAdmin): readonly_fields = ['blog_publish_time', 'blog_update_time'] list_display = ['blog_title', 'blog_status', 'blog_publish_time', 'blog_update_time'] def rename_blog_title(self, obj): return obj.blog_title[:10] rename_blog_title.short_description = "title" admin.site.register(Blog, BlogAdmin) where I am doing mistake? -
How to get the path to your saved image in django
I created a form model using the code below class TrainImageForm(forms.ModelForm): class Meta: model = TrainImage fields = ( 'image', ) def customSave(self): lv = self.save(commit=False) lv.save() return lv.image.name And this is how I saved uploaded image. But any time I try to retrieve the image, I get a "FileNotFoundError" def testnetwork(request): if request.method == "POST": form = TrainImageForm(data=request.POST, files=request.FILES) if form.is_valid(): filename = str(form.customSave()) img_array = imageio.imread("media/train_images/" + filename,as_gray=True) img_data = 255.0 - img_array.reshape(784) img_data = (img_data/255.0 * 0.99) + 0.01 global n output = n.query(img_data) label = numpy.argmax(output) But when I input the path of the file manually (in the imageio.imread), it works without any error. Please how do I go about this -
Heroku Deployment Failed for a Django App while deploying current state of Git branch [duplicate]
I have synced the heroku app with my GitHub Source code so far it only did one successful build and the App gives an Application Error when I open the app. I have followed all the steps, added procfile added requirements.txt added runtime.txt added URLs in the ALLOWED_HOSTS = [''] in settings.py my project structure is as the following --Project Root --DjangoBase --API --Files --Files The error I get is the following -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/app/.heroku/python/lib/python3.10/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input ! Requested runtime (��python-3.10.2) is not available for this stack (heroku-20). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed -
Django filter models with a list of related items
For a simple Book model with a related Tag table, I'd like to filter out Books that have a list of tags: class Book(models.Model): name = models.Textfield() class Tag(models.Model): value = models.Textfield() book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="tags") If I want to search all Books that have a both a "red" Tag and a "blue" tag, I can't simply run: Book.objects.filter(Q(tags__value="red") & Q(tags__value="blue")) because that tries to find an impossible Tag that has both the value "blue" and "red". Note that OR-ing the conditions is not correct either since I'm looking for Books that have both a "red" and a "blue" tag; a Book with just one or the other should not be returned. -
Migrate command error in Django with djongo
I am getting error while using the migrate command in djongo with Django. The error is djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: CREATE TABLE "django_content_type" ("id" int NOT NULL PRIMARY KEY AUTOINCREMENT, "name" string NOT NULL, "app_label" string NOT NULL, "model" string NOT NULL) Params: None Version: 1.3.6 -
Add a FileField path in django
I have a map in my app and im trying to 'paint' some territories with kml files. I can get the outlined version if i hardcode the absolute path but since i have multiple kmls im trying to do it with a for loop with a field.kml.path (kml being the Filefield in my model) as per django instructions but it doesnt work . Any idea how to fix that ? view : def map(request): field_list = models.Field.objects.all() context = { "title": "Map", "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) My original map.html var polygon = omnivore.kml("{% static '../media/kml/Arnissa_cherry.kml' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); New version that doesnt work: {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name}}")); //friendly name var polygon = omnivore.kml("{% static '{{field.kml.path}}' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); {% endfor %} -
Django GinIndex on a specific JSON key
There is a solution how to create an index for search against Django JSONField operations = [ migrations.RunSQL("CREATE INDEX JsonFieldNameIndex ON contracts_clause((custom_indexed_content->'name'));"), ] However, if I try to use Django GinIndex, that does not affect the search speed class Clause(CustomModel): title = models.CharField(max_length=255) not_indexed_content = models.JSONField(blank=True, null=True) manually_indexed_content = models.JSONField(blank=True, null=True) db_indexed_content = models.JSONField(blank=True, null=True, db_index=True) gin_indexed_content = models.JSONField(blank=True, null=True) class Meta: indexes = [GinIndex(fields=['gin_indexed_content'])] Django debug toolbar queries timeline Is there a way to create an index for a specific JSON field using Django ORM syntax, rather than using raw SQL? -
Can't edit django project
I installed django and python multiple times. Every time when i run django-admin startproject projectname it creates a project which is not responding. Anything I do just doesn't apply to website. It's in views.py or any of urls.py. I am using command: python3 manage.py runserver. It doesn't work with pipenv either. Problem is not in code I put in project because I worked by tutorial. -
Django webscraping JSONDecodeError
I'm trying to scrape data and it works fine if the {fplid} for url is like 30 for example. How do I fix this method, so it gets the user input and gets the data from the url without a decode error. This is the traceback ''' C:\Users\krish\OneDrive\Desktop\FPLHangout\scrape\views.py, line 31, in home data = get_html_content(fplid) … Local vars C:\Users\krish\OneDrive\Desktop\FPLHangout\scrape\views.py, line 9, in get_html_content managerdata = json.loads(r.text) def get_html_content(fplid): url = 'https://fantasy.premierleague.com/api/entry/{fplid}/event/30/picks/' r = requests.get(url) managerdata = json.loads(r.text) bootstrap = 'https://fantasy.premierleague.com/api/bootstrap-static/' bootstrapdata = requests.get(bootstrap) bootstrapjson = json.loads(bootstrapdata.text) for pick in managerdata['picks']: pick = (pick['element']) #correct id location = 0 for player in bootstrapjson['elements']: if player.get('id') == pick: break location += 1 #position = (pick['position']) firstname = bootstrapjson['elements'][location]['first_name'] secondname = bootstrapjson['elements'][location]['second_name'] return firstname + " " + secondname def home(request): if 'fplid' in request.GET: # fplid = request.GET.get('fplid') data = get_html_content(fplid) return render(request, 'scrape/home.html', {'fpldata': data}) return render(request, 'scrape/home.html') -
Django get models by model name
In Django I know that there is one and only one model with name foo, but I don't know the app that this model is registered with! How can I get the model with only model_name? -
Format data to pass to Javascript chart
Sorry in advance for the confusing post. I have some questionnaires that are used to score a project across different areas, like marketing, costs etc. I'm trying to build a chart that shows the score of each project across each area. The format for the chart needs to be name: 'Project Name', data: [2,5,1,4,4,5,6,2] }], with each number being the score of each area. I've managed to get as far as collecting the score for each project for each area, but it duplicates the project name for each questionnaire. [projectName1, Questionnaire1, Score] [projectName1, Questionnaire2, Score] [projectName2, Questionnaire1, Score] ... I'm not sure of the approach I need to take: for project in all_projects: for q in questionnaires: print("getting ", q.title, "responses for", project.name, project.id) if ProjectQuestionnaireResponse.objects.filter(project_name_id=project.id, questionnaire_id = q.id).exists(): q_response = ProjectQuestionnaireResponse.objects.get(project_name_id=project.id, questionnaire_id = q.id) q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False).count() if q_answered > 1: q_count = (100 / ProjectQuestionnaireQuestion.objects.filter(questionnaire_id = q.id).count() * q_answered) else: q_count = 0 q_rounded = (5 * round(q_count / 5)) # Scoring Calculator # # Get Questionnaire Range total_questions =ProjectQuestionnaireQuestion.objects.filter(questionnaire_id = q.id).count() score_range = (4 * total_questions) green = 2 red = -2 green_answer_value = (ProjectQuestionnaireAnswer.objects.filter(response = q_response,answer__choice_value="Green").count() * green) red_answer_value = (ProjectQuestionnaireAnswer.objects.filter(response = q_response,answer__choice_value="Red").count() … -
Can you load data from database into Bootstrap modal using Python?
I have a Django project where you can do CRUD operations. I am trying to make it so that when someone tries to edit, a modal will pop up with the data of x or y. I have a strong python background so I'm trying to do this in python. I tried doing it in javascript but I don't know where to start. Any help would be appreciated. -
Get_or_create or form validation then create?
I know this is a somewhat common thing to do but I'm struggling to grasp how to make it work from examples. I want to have a form where the user inputs an object ID (similar to an ISBN for a book). I want to check if that object exists in the db, if not, I want to create the entry based on some info I'll pull from a script using that ID. It seems like I could go two ways. I could use get_or_create, or I could do this with the cleaned data in the form and then I haven't been able to make either work but I think I have some basic misunderstanding of how they work. What is the best way of going forward? -
Django/Daphne/Nginx Websockets not connecting
I am using django with daphne and nginx to run my websockets. Everything was working fine for months in production, however just a couple days ago my websockets wouldn't connect saying "WebSocket connection to 'wss://mydomain:8001/clips/509/' failed: ". I checked the server logs and this is in the output 2022-04-07 16:57:22,970 ERROR [Failure instance: Traceback: <class 'AttributeError'>: 'NoneType' object has no attribute 'replace' Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/autobahn/websocket/protocol.py:2839:processHandshake Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/txaio/tx.py:366:as_future Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/twisted/internet/defer.py:151:maybeDeferred Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/daphne/ws_protocol.py:72:onConnect Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: --- <exception caught here> --- Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/twisted/internet/defer.py:151:maybeDeferred Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/daphne/server.py:200:create_application Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/routing.py:54:__call__ Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:35:__call__ Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:53:valid_origin Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:72:validate_origin Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:73:<genexpr> Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:97:match_allowed_origin Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /usr/lib/python3.8/urllib/parse.py:376:urlparse Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /usr/lib/python3.8/urllib/parse.py:430:urlsplit Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: ] I don't understand why this happened all of the sudden, is it maybe a dependency got updated or depracted? Any ideas are helpful cause I am mad stuck. -
Django 4.0.3 and mssql-django 1.1.2 will not connect to SQL Server Express 2019
I have been going by this tutorial for mssql-django https://docs.microsoft.com/en-us/samples/azure-samples/mssql-django-samples/mssql-django-samples/ My setup is Django 4.0.3 and mssql-django 1.1.2 will not connect to SQL Server Express 2019 on Windows 10, with the SQL Server Express 2019 running locally. I have searched both GitHub and Stack Overflow for examples of mssql-django configurations, but not much is turning up. I am not sure what I am doing wrong. The main things I have been trying is betting on the NAME, USER or HOST parameter being incorrect, as the others seem to be correct. Should NAME be: avxdb or mxlaptop\\avxdb or something else? Should USER be: pyadmin@mxlaptop or just pyadmin? Should HOST be: mxlaptop\SQLEXPRESS, mxlaptop\ss2019, mxlaptop, or 127.0.0.1? DATABASES = { 'default': { "ENGINE": "mssql", "NAME": "avxdb", "USER": "pyadmin@mxlaptop", "PASSWORD": "Python", "HOST": "mxlaptop\SQLEXPRESS", "PORT": "1433", "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", }, } } I have a normal Python script that can connect to the database via pyodbc: connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};' 'SERVER=mxlaptop;' 'DATABASE=avxdb;' 'UID=pyadmin;' 'PWD=Python;') -
Django user updates profile picture and the other users receive this changes too
I created a form so that every user can update its profile. What it's happening is that when a user changes the profile picture of its account, also it changes the profile picture of the other users and of course, I don't want that. This is my code: signals.py def create_user_profile(sender, instance, created, **kwargs): if created: profile = Profile(user=instance) profile.save() post_save.connect(create_user_profile, sender=User, dispatch_uid="profilecreation-signal") forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = [ "first_name", "last_name", "image", "description", "website" ] views.py def profile_page(request, username): form = ProfileForm(data=request.POST, files=request.FILES, instance=request.user.profile) if request.method == "POST": if form.is_valid(): form.save() return redirect(request.META['HTTP_REFERER']) context = { "profile_form": form, } return render(request, "profile.html", context) The profile_page view has username also as attribute because there is more code related to it. Could someone help me? Thanks! -
Django - Comment Xtd - implement title attribute in admin model
I am using the django-comments-xtd app to handle comments and replies. I want to replace the object id in the admin panel with the object title but I am struggling to do that. The code that is in models.py can be found here. I am not pasting it here because it is a long piece of code. Below is my "customized" XtdCommentsAdmin model: class XtdCommentsAdmin(CommentsAdmin): list_display = ('name', 'comment', 'content_type', 'object_pk', 'submit_date', 'is_public', 'is_removed', 'title') ... def title(self, obj): return obj.object_pk.title #what am I doing wrong here? I tried to return obj.title, obj.object_pk.title in my title attribute but I get this output <built-in method title of str object at 0x000001F3BC859120> I also tried to use lookup directly in list_display like object__title but the only thing I get is this: The value of 'list_display[3]' refers to 'object__title', which is not a callable, an attribute of 'XtdCommentsAdmin', or an attribute or method on 'django_comments_xtd.XtdComment'. Could you please tell me how to display the object title instead of the object id? -
AttributeError: 'str' object has no attribute 'text' PyTelegramBotAPI
I was creating a bot that measures the size of a rectangle using the pytelegrambotapi library. I created a database using Python django. Purpose: When a bot is used by more than one user, the bot retrieves the parameters entered by each user from the database and returns a response to them. But the following error is observed in my code: AttributeError: 'str' object has no attribute 'text' I don’t understand where and why this error is happening. BOT.PY ... ... float_pattern = r'^\d{1,7}\.\d{1,2}$' int_pattern = r'^\d{1,7}$' ... ... def perimeter(message): if re.match(int_pattern, message.text) or re.match(float_pattern, message.text): p = float(message.text) chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param1=message.text ).save() print(p, type(p), 'Parameter (p) from:', chat_id) bot.send_message(message.chat.id, "Good") msg = bot.send_message(message.chat.id, "Enter height:") bot.register_next_step_handler(msg, height) return p else: msg = bot.send_message(message.chat.id, "Only number!") bot.register_next_step_handler(msg, perimeter) def height(message): if re.match(int_pattern, message.text) or re.match(float_pattern, message.text): h = float(message.text) chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param2=message.text ).save() print('Parameter (h) from:', chat_id) bot.send_message(message.chat.id, "Good!") msg = bot.send_message(message.chat.id, "The answer is f'{str(result())}'") return h else: msg = bot.send_message(Only number!) bot.register_next_step_handler(msg, height) def result(): p = '' # perimeter h … -
Custom Permissions for admin for get and delete only
In Django rest framework, I want only owner can CREATE, PUT and DELETE but Admin can only have permission for GET and DELETE only not PUT method -
DJANGO int() argument must be a string, a bytes-like object or a number, not 'list'
Hello sir i have in DJANGO a problem tryin to get my algorithm right please help, much appreciated: MYERROR: int() argument must be a string, a bytes-like object or a number, not 'list' MYCODE: def subs(request, pk): sw = Swimmers.objects.filter(id=pk).values('sessions') sw_list = int(list(sw)) res = sw_list +1 print('Data:',sw) return JsonResponse(res, safe=False) -
ProgrammingError at /user_booking not all arguments converted during bytes formatting
The idea is to display user's booking information like booking_name, package etc. I am fetching the data from database in my views.py like this. def user_booking(request): id = request.session['u_id'] booking_data = Booking.objects.raw('select * from booking WHERE id = %s',id) return render(request,'user_booking.html',{'view_data':booking_data}) Now in user_booking.html is displaying data. I have used a proper template to display data in tabular format. Problem is when some data is returned from data base it works perfect. When there is a query for which no data can be found the page breaks and shows "ProgrammingError at /user_booking not all arguments converted during bytes formatting" Instead of all the formatting I resorted to basic code which looks like this <html> {% for b in view_data %} {{b.b_name}} {% endfor %} </html> It gives me the name "ajay" as output and does not break the page, also note that record for ajay's ID is present in my database. Now if ID is changed and then I refresh the lage again it gives me error. What I am trying to do is if there is any data coming from the database then display it otherwise just display "no data here" msg. How do I achieve it? -
How do I get rid of "Inconsistent Migration History" error on Python using Django framework in Docker environment?
The error itself: This is the structure of my app file system: -
can't access database values of django MultiSelectField in an external script
I have a simple scenario where i have a django multiselectfield and the choices are: jobs_multiple_choice = ( (1, 'Social Media Manager'), (2, 'Online Tutor'), (3, 'Bookkeeper'), (4, 'Personal Trainer'), (5, 'Email Marketer'), (6, ' Freelance Writer'), (7, 'Website Designer'), (9, 'Instagram Influencer'), (8, 'SEO Expert '), (10, ' Facebook Ads Specialist '), (11, 'Graphic Designer'), (12, 'Voiceover Artist'), (30, 'Stock Photographer '), (62, 'Data Entry Worker'), ) i want to save number as an id of the jobs, now i want to get the data of the model into an external python script i did the usual import but i have an issue. script.py: import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') django.setup() from practice.models import Jobs a = Jobs.objects.all().first() print(a.name) the output its giving is representative value and not the number like ['1', '2', '42','4', '24'] etc but getting: Social Media Manager, Online Tutor, Bookkeeper, Personal Trainer, Email Marketer, Website Designer, Graphic Designer, Voiceover Artist, Data Entry Worker but! when i do that in manage.py shell, its giving me the desired value like below >>> from practice.models import Jobs >>> a = Jobs.objects.all().first() >>> b = Jobs.objects.all().last() >>> a.name ['1', '2', '3', '4', '5', '7', '11', '12', '62'] >>> b.name …