Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Two divs in same row when click on one expand both tailwind css Django alpine js
image before opening div image after clicking on div CODE SNIPPET <div x-init x-data="{expanded: false}" :class="expanded ? 'h-full' : 'h-12'" class="w-full md:w-48/100 flex flex-col"> <div @click="expanded = !expanded" class="flex items-center px-10 py-4 border-b bg-white rounded-lg cursor-pointer"> <div class="font-bold font-lato text-xsm bg-white">{{ value.question }}</div> <div class="ml-auto p-2"> <svg width="8" height="6" viewBox="0 0 8 6" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M7.77083 0.937549C7.68535 0.850049 7.57545 0.812549 7.46555 0.812549C7.35565 0.812549 7.23354 0.862549 7.16027 0.937549L4.03424 4.11255L0.932622 0.937549C0.847145 0.850049 0.725034 0.800049 0.615134 0.800049C0.505234 0.800049 0.383123 0.850049 0.309857 0.925049C0.138902 1.10005 0.138902 1.38755 0.309857 1.56255L3.71675 5.06255C3.8877 5.23755 4.16856 5.23755 4.33951 5.06255L7.75862 1.57505C7.94178 1.40005 7.94178 1.11255 7.77083 0.937549Z" fill="#080F33"> </path> </svg> </div> </div> <div x-show="expanded" class="px-10 py-4 text-left font-lato bg-gray-50 text-gray-500 flex-1"> {{ value.answer|richtext }} </div> -
Using CSS Grid on a Django Template
I have a div container in my HTML which displays a list of 10 parsed headlines from The Toronto Star. I want to be able to display them in a repeating grid that looks like this: Here's the example image ( I can't add images since I dont have 10 reputation yet ) Here's the django template that I have : <div id="container"> <div class="containers"> {% for n, i in toronto %} <center><img src="{{i}}"></center> <h3>{{n}}</h3> {% endfor %} </div> Would highly appreciate any help :) -
Django: Include a template containing a script tag into another script tag
I want include a html file containing a script tag like this: <script>$('#page-content').html('{% include "title.html" %}');</script> title.html: <script>document.title = "Hello World!"</script> result: <script>$('#page-content').html('<script>document.title = "Hello World!"</script>');</script> Sadly, this will render incorrectly in the browser and I'm not quite sure how to solve it best -
Django error: Relation "<name>" already exists
I am attempting to run migrations on an existing model where i am adding a history field/table via the django-simple-history. I initially ran made and ran the migrations and then ran python manage.py populate_history --auto to generate the initial change for the pre-existing model. This created a new table in the DB and now when i try and re-run migrations, i get the error that relation <name> already exists. Do i have to delete/drop the table for the db? -
what does "weight" in "SearchVector" django?
Can you explain to me what role "weight" play in the SearchVector? for example in this code: vector = SearchVector('body_text', weight='A') + SearchVector('blog__tagline', weight='B') -
django json.loads() of string of list
I'm trying to save a list of ids as a string and then turn it back to a list and use it's values for filtering a queryset. So first I do something like this - my_items_ids = list(Item.objects.filter(....).values_list('id', flat=True)) which returns list of UUIDS - [UUID('ef8905a7-cdd3-40b8-9af8-46cae395a527'), UUID('0904bcc4-7859-4c38-a2f9-94a4a2b93f0a')] Then I json.dumps it so I get - "[UUID('ef8905a7-cdd3-40b8-9af8-46cae395a527'), UUID('0904bcc4-7859-4c38-a2f9-94a4a2b93f0a')]" Later on I want to use those IDs for filtering again. something like - my_items = Item.objects.filter(id__in=my_items_ids) Since it's a string I'm trying json.loads(my_items_ids) first and I get json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1) I also tried to turn the UUIDs in the list to strings before the json.dumps() but I got the same results. -
Django Rest Framework Can't add/edit nested obejct
I'm quite new in drf and I'm trying to display nested objects and have the choices functionality in the ListCreateView at the same time models.py class CarBrand(SoftDeletionModel): CAR_BRAND_NAME_MAX_LEN = 30 name = models.CharField( max_length=CAR_BRAND_NAME_MAX_LEN, ) created_at = models.DateTimeField( auto_now_add=True, ) def __str__(self): return self.name class CarModel(SoftDeletionModel): CAR_MODEL_NAME_MAX_LEN = 30 name = models.CharField( max_length=CAR_MODEL_NAME_MAX_LEN, ) car_brand = models.ForeignKey( CarBrand, on_delete=models.CASCADE, ) created_at = models.DateTimeField( auto_now_add=True, ) updated_at = models.DateTimeField( auto_now=True, ) My logic is to have car brands and then when creating a new car model to specify existing car brand serializers.py class FullCarBrandSerializer(serializers.ModelSerializer): class Meta: model = CarBrand fields = ('id', 'name', 'created_at') class IdAndNameCarBrandSerializer(serializers.ModelSerializer): class Meta: model = CarBrand fields = ('id', 'name') class FullCarModelSerializer(serializers.ModelSerializer): car_brand = IdAndNameCarBrandSerializer(many=False) class Meta: model = CarModel fields = ('id', 'name', 'created_at', 'updated_at', 'car_brand') When I don't have car_brand = IdAndNameCarBrandSerializer(many=False) the creating part with the choices of the car brands works correctly correct_choices_img, but that's not the way I want to display the JSON incorrect_nested_field_img(it shows only the id, but I want id and name) however when I add that same line again I get what I want in the JSON which is like this correct_nested_field_img, but the functionality of choosing exciting … -
How do I check if a user has entered the URL from another website in Django?
How do I check if a user has entered the URL from another website in Django? Like how do I check if they are coming directly from another website? -
Unable to connect to redis server through docker-compose, I am using django_q framework as an async task queue and redis as broker
This is my docker-compose file configuration: version: '3' services: redis: image: redis:alpine ports: - 6300:6379 db: image: postgres:12.8-alpine restart: always volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.dev.db ports: - 5400:5432 web: build: context: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/ps_survey ports: - 8000:8000 env_file: - ./.env.dev depends_on: - redis - db django-q: build: . command: python manage.py qcluster volumes: - .:/ps_survey env_file: - ./.env.dev ports: - 8001:8000 depends_on: - redis volumes: postgres_data: This is my qcluster configuration: Q_CLUSTER = { 'name': 'ps_survey', 'workers': 4, 'recycle': 500, 'timeout': 60, 'compress': True, 'save_limit': 250, 'queue_limit': 500, 'cpu_affinity': 1, 'label': 'Django Q', 'redis': { 'host': '127.0.0.1', 'port': 6300, 'db': 0, } } This is exception I am receiving: django-q_1 | connection.connect() django-q_1 | File "/usr/local/lib/python3.10/site-packages/redis/connection.py", line 563, in connect django-q_1 | raise ConnectionError(self._error_message(e)) django-q_1 | redis.exceptions.ConnectionError: Error 111 connecting to 127.0.0.1:6300. Connection refused. -
Pls anyone help!! I keep getting no such file or directory trying to create mynewproject with Django. Py pip Django I installed all. Thanks
I install py 3.10.1 , have pip in it, so I upgrade everything to latest. Create a venv and install Django in the venv. I checked the installation by checking version 4.0 But whenever I use django-admin startproject myprojectname It gives me a no such file or directory err msg. Pls I’m new someone help. I wanna start my first project but I’m stuck at the moment. Thanks -
viewAppointment() missing 1 required positional argument: 'appointment_id'
while running my code i have encountered this kind of error which is i dont know how it happened this is my views.py def viewAppointment(request, appointment_id): appointment = Appointment.objects.filter(id=appointment_id) return render(request, 'appointment_form.html', {'Appointment': appointment}) this is urls.py from unicodedata import name from django.urls import path from django.contrib import admin from django.urls import re_path from . import views app_name = "Project" urlpatterns = [ path('', views.index , name='index'), path('counter', views.counter, name='counter'), path('Register', views.Register, name= 'Register'), path('login', views.login, name='login'), path('logout', views.logout, name = 'logout'), path('post/<str:pk>', views.post, name = 'post'), path('appointment', views.viewAppointment, name='appointment'), re_path(r'^appointment/appointment=(?P<appointment_id>[0-100]+)/AddDiagnonsis', views.addDiagnosis, name='AddDiagnosis') ] -
Django OperationalError no such table
I'm making a sign up page. html {{message}} <form action="{% url 'signup' %}" method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control" autofocus type="text" name="username" placeholder="Username"> </div> <div class="form-group"> <input class="form-control" type="email" name="email" placeholder="Email Address"> </div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <div class="form-group"> <input class="form-control" type="password" name="confirmation" placeholder="Confirm Password"> </div> <input class="btn btn-primary" type="submit" value="Register"> </form> django def signup(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirmation = request.POST['confirmation'] if password != confirmation: return render(request, 'lms/signup.html', { 'message': 'Passwords must match.' }) else: try: user = User.objects.create_user(username, email, password) user.save() except IntegrityError: return render(request, 'lms/signup.html', { 'message': 'Username already taken.' }) return HttpResponseRedirect(reverse('index')) else: return render(request, 'lms/signup.html') When I submit the form, I get this error: OperationalError at /signup no such table: lms_user I've already done the migrations command. I also deleted tried deleting migrations and pycache folder's content and db.sqlite3 file and did the migrations again but that didn't help either. -
Adding object type as a value in a dictionary
I need to add an object as value in a dict, So dict looks like dict1={"key":"value,"other":"other"} Then I need the newly created Model object as instance to be used later in the code, so instance = MyModel.objects.create(name="name",someother="some") I need to update the dict to add the instance dict1['request'] = instance // it will throw an error other_def.delay(dict1) // use the contents of dict in celery function `exception Object of type MyModel is not JSON serializable` Because I have another model that have relation to MyModel as many-to one other_def.py instance = args['instance'] ChildModel.objects.create(parentinstance=instance,....) I can't use the instance.id since it will return an error must be an instance dict1['request']=instance.id //not working `Cannot assign "5"...must be a MyModel instance How do you add an instance to a dict? Regards -
OperationalError: table "webapp_profile" already exists
I tried to migrate and I got this error: OperationalError: table "webapp_profile" already exists -
CSS not rendered well in chrome, but works fine in Microsoft edge
I am doing a project on Django- python web framework. I was following Otchere's tutorial from his github repository- https://github.com/OtchereDev/django_netflix_clone ; but for unknown reason it is not displayed in a full screen, at the middle as shown in the image below in chrome browser. screenshot from chrome browser -
how to get data (mp3) from local storage and can be played in html - DJANGO FORMS
i was new in django. i want to get my mp3 song what was i uploaded it and can be pass to html. how to get the song and return it? forms.py : from django import forms class Audio_store(forms.Form): password=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) audio=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) the song have variabel audio. so in my html, the song can be played -
How to do migrations in your old models?
I created 2 models: from django.db import models class Company(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name class Puzzle(models.Model): name = models.CharField(max_length=200) number_of_pieces = models.IntegerField() ean_code = models.CharField(max_length=13, unique=True) description = models.TextField() company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='puzzles') product_code = models.CharField(max_length=50) image = models.ImageField(upload_to='images/', blank=True, null=True) website = models.URLField(blank=True, null=True) created = models.DateField(auto_now_add=True) And I added some sample models. Now I want to change model Company add new field for example: class Company(models.Model): name = models.CharField(max_length=150, unique=True) description = models.TextField(blank=True, null=False) When I do: py manage.py makemigrations I have error: Traceback (most recent call last): File "E:\code\Django\FanPuzzle\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "E:\code\Django\FanPuzzle\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: puzzle_company.description The above exception was the direct cause of the following exception: Traceback (most recent call last): File ".\manage.py", line 22, in <module> main() File ".\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\code\Django\FanPuzzle\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "E:\code\Django\FanPuzzle\venv\lib\site-packages\django\core\management\__init__.py", line . . . File "E:\code\Django\FanPuzzle\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "E:\code\Django\FanPuzzle\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: puzzle_company.description What do I do wrong? Here is my whole project: https://github.com/MatRos-sf/Django-FanPuzzle -
google Engine ModuleNotFoundError: No module named 'storages'
I´m receiving this error where I deploy my app on Google Engine. When I run it locally it works. I already have that dependency in my requirements file. I checked the logs on google console and it show that in the build it installed django-storages. File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/opt/python3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/srv/main.py", line 1, in <module> from app_admin.wsgi import application File "/srv/app_admin/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models … -
query postgres jsonb field with django orm when is a list of objects
I have and object similar to his: { "products":[{"cpu":"something here", description:"intel core i9, 30 gb ram"}, {"cpu":"another here", description:"amd raizen, 20 gb ram"} ] } now i want to search with a "like" something in the description, with direct query on postgres i solve with the next query, select distinct id from mytable, JSONB_ARRAY_ELEMENTS(jsonfield->'products') products where products->>'description' like '%raizen' but now i need to do something similar with django ORM, the only code that i can found is the next one: bf = mytableobject.objects.filter(jsonfile__products__contains=[{"CPU":"0x3"}]).first() the code above works just with an exact equals,but i need a like search, i mean, the next code does not work: bf = mytableobject.objects.filter(jsonfile__products__contains=[{"description":"raizen"}]).first() I found that i can search specifiying the index , something similar to this: bf = bucketizerfiles.objects.filter(jsonfile__products__0__description__contains="raizen").first() in fact this code works, however, i do not know how many products i have in the list and to be honest the solucion of searching index by index is not optimal at all. so, i want to know if there is a manner to perform a "like" search in a list of object in a jsonfield using django orm just for clarification, this is not my real information and i do not search … -
Django Test Coverage - not covering function contents, just definition
Before you say it, yes, i saw this post, and yes, i'm having the same problem, but with Django testing, that theoretically uses unittest module, but that didn't work for me, does anybody now how to make it cover the whole function with django? I tried adding if __name__ == "__main__": TestCase.run(MyTestCase) but didn't work, it still shows that i only cover function definitions. -
Are there any fields in a django model that the user doesn't fill in but the computer does? (CS50 Project 2)
I have created a django form that creates and saves comments to listings. I want the comment to only save to the listing that it is commented to (right now it saves to all the listings). Is there any way to tell the webpage which listing to save it to and which user wrote the comment? models.py class Comments(models.Model): comment = models.CharField(max_length=500) views.py @login_required(login_url='login') def listing(request, id): listing = Listings.objects.get(id=id) form = CommentForm if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save() comment.save() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": form, "comments": Comments.objects.all() }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": form, "comments": Comments.objects.all() }) html <img src ="{{ auction_listing.image }}" style = "height: 10%; width: 10%;"> <h4 class = "text">{{ auction_listing.title }}</h4> <h6>Description: {{ auction_listing.description }}</h6> <h6>Category: {{ auction_listing.category }}</h6> <h6>Price: ${{ auction_listing.bid }}</h6> <form action = "{% url 'listing' auction_listing.id %}" method = "POST"> {% csrf_token %} {{ form }} <input type = "submit" value = "Save"> </form> {% for comment in comments %} <h6> {{ comment.comment }} </h6> {% endfor %} Thanks for all the help! -
Assign a value of two dimensional array to inner html in Java script
var data = JSON.parse("{{ data|escapejs }}"); for(var x in data){ // console.log(data[x]) console.log(data[x][0]) console.log(data[x][1]) var x = document.getElementById("dynamic") var string = data[x][1]; document.getElementById("dynamictitle").innerHTML = data[x][0]; document.getElementById("dynamicimg").src = data[x][1]; } **here i am taking value for data from views , trying to pass img source and image title....data[x][0] has some text and data[x][1] has image url....can anyone tell why the values are not passing...if i give direct url like .src = 'https:///imageurl' it is working and same for innerhtml ** -
How to get only the date from datetimefield grouped by date
Struggeling for many hours now and don't know what do do. I have a database table with some stuff like below: id date_time uuid_id status_id room_label_id 1 2022-06-06 11:15:00 228451edc3fa499bb30919bf57b4cc32 0 1 2 2022-06-06 12:00:00 50e587d65f8449f88b49129143378922 0 1 3 2022-06-06 12:45:00 d1323b0ebd65425380a79c359a190ec6 0 1 4 2022-06-06 13:30:00 219af9da06ac4f459df2b0dc026fd269 0 1 With many more entries. date_time is a datetimefield. I want to display several columns from this table in a html, grouped by date_time. But firstly i want to display the date out of the datetimefield grouped by date. With: <table> <tr> <th>Field 1</th> </tr> {% for terms in term %} <tr> <td>{{ terms.date_time.date }}</td> </tr> {% endfor %} </table> and my view: def schedule(request): term = appointment.objects.all() return render(request, 'scheduler/schedule.html', {'term' : term}) I get as result: Field 1 6. Juni 2022 6. Juni 2022 6. Juni 2022 6. Juni 2022 6. Juni 2022 6. Juni 2022 6. Juni 2022 7. Juni 2022 7. Juni 2022 7. Juni 2022 7. Juni 2022 7. Juni 2022 7. Juni 2022 7. Juni 2022 8. Juni 2022 8. Juni 2022 8. Juni 2022 8. Juni 2022 So far, so good. But i need only the date from the datetimefield like the following: Field … -
Solution for deleting by "name"
I need solution for deleting Profesor by his 'name': class Profesor(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) suername = models.CharField(max_length=200, null=True) Imagine is to ask user on html page to input 'name' of Profesor that he want to delete And then in views.py to delete Profesor by that 'ime' How can i do that? -
Django POST Question for Hangman Game - Cant Update More Than One Letter
I'm working on a Hangman game using Django and trying to update the correct letters guessed in the word on the page. It seems I can get one letter at a time but not more than one to update the word as the game progresses. Its almost like a new list is initializing each time the function is called. Any suggestions? Here is my code, the 'else' is defaulted off a post request. Any buttons clicked from the keyboard are sent to a function where I handle the POST request, one button at a time. I'm a little unfamiliar working with HTTP requests/responses so any help would be appreciated. else: game_id = int(request.POST['game_id']) letter_guess = request.POST['letter'] game = Game.objects.get(game_id=game_id) game.guess = letter_guess split_answer = game.answer.split() answer1 = split_answer[0] len1 = int(len(game.display1) / 2) word1 = list(range(len1)) for x in range(len1): if answer1[x] == letter_guess: word1[x] = answer1[x] + " " else: word1[x] = "_ " word1 = "".join(word1) game.display1 = word1 game.save()