Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problems with get_context_data in ListView (django)
I need to show in a template two models: models.py: class Dimension(TimeStampedModel): level = models.ForeignKey('Level', verbose_name=_('Level'), on_delete=models.CASCADE) name = models.CharField(verbose_name=('Name'), max_length=200) active = models.BooleanField(verbose_name=_('Active'), default=True) sort_order = models.PositiveIntegerField(verbose_name=_('sort order'), default=0) class Meta: verbose_name = _('Dimension') verbose_name_plural = _('Dimensions') def __str__(self): return self.name class Subdimension(TimeStampedModel): dimension = models.ForeignKey('Dimension', verbose_name=_('Dimension'), on_delete=models.CASCADE) name = models.CharField(verbose_name=('Name'), max_length=200) active = models.BooleanField(verbose_name=_('Active'), default=True) sort_order = models.PositiveIntegerField(verbose_name=_('sort order'), default=0) objects = managers.SubdimensionManager() class Meta: verbose_name = _('Subdimension') verbose_name_plural = _('Subdimensions') def __str__(self): return self.name and created a ListView of this views.py class DimensionListView(generic.ListView): model = models.Dimension template_name = 'dimension.html' context_object_name = 'dimensions' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): self.user = self.request.user self.level = self.get_level(pk=kwargs.get('level_pk')) return super(DimensionListView, self).dispatch(request, *args, **kwargs) def get_level(self, pk): level = get_object_or_404(models.Level, pk=pk) return level def get_queryset(self): queryset = super(DimensionListView, self).get_queryset() return queryset.filter(active = True, level = self.level) def get_context_data(self, **kwargs): context = super(DimensionListView, self).get_context_data(**kwargs) context['subdimensions'] = models.Subdimension.objects.filter(active=True, dimension__level=self.level ) return context dimension_list_view = DimensionListView.as_view() I need to created a filter of the same 'dimension' so that in the template show only the subdimensions of that dimension. my template dimension.html: {% include 'base.html'%} {% block content %} <div class="row"> {% for dimension in dimensions %} <div class="col"> <div class="card" style="width: 18rem;"> <a class="">{{dimension.name}}</a> <div … -
Is there a way to set Mixin Django Admin action parameters within the model?
So I have a working Mixin for an action that currently operates on all fields of the queryset. Instead of this, I would like the ability to specify which fields will be used by the action via the code for the Admin page. For context, here is a brief portion of my Mixin: class MyMixin: def my_action(self, request, queryset): model_to_update = apps.get_model( app_label=<my_app>, model_name=queryset.first().__class__.__name__) ... for field in model_to_update._meta.get_fields(): # do cool stuff with all fields ... return render(...) Here is how the mixin is incorporated currently: ... @admin.register(<Model>) class ModelAdmin(MyMixin): ... actions = ["my_action"] ... ... and what I would like to do is something along the lines of: ... @admin.register(<Model>) class ModelAdmin(MyMixin): ... actions = [my_action(fields=['foo', 'bar',]] ... ... where foo and bar are a subset of the fields of ModelAdmin. Thank you in advance for any ideas! Apologies if this has already been asked elsewhere and I'm just phrasing it differently. -
Django custom user not able to log in from web app but works fine in Admin
I have created an App called "myapp" with custom user called "CustomUser" along with a custom user app called "customuser". I am able to successfully login from the admin. But I am not able to login from the app login. Here is the login function: def login(request): if request.method == 'POST': email=request.POST.get('email') password=request.POST.get("password") user = authenticate(request,email=email,password=password) if user is not None: auth_login(request,user) messages.success(request,'You are logged in') else: messages.error(request,"invalid login credentials") return redirect(login) return redirect(request,'myapp/home.html') else: form = AuthenticationForm() return render(request,'customuser/login.html', {'form':form}) Here is the admin from customuser.forms import * from customuser.models import Profiles class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm filter_horizontal=() list_display = ('email', 'FirstName','LastName', 'last_login','is_active','date_joined','is_admin') list_filter = ('is_admin','is_staff') fieldsets = ( (None, {'description': ( "Enter the new user's name and email address and click save." " The user will be emailed a link allowing them to login to" " the site and set their password." ), 'fields': ('email', )}), ('Password', { 'description': "Optionally, you may set the user's password here.", 'fields': ('password',), 'classes': ('collapse', 'collapse-closed'), }), ('Personal info', {'fields': ('FirstName','LastName')}), ('Permissions', {'fields': ('is_admin','is_staff')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password', 'FirstName','LastName', 'is_admin'), }), ) search_fields … -
How to pass variable data into empty dictionaries
I am trying to push data into empty dictionaries while doing this I add two for loops but I want to return two loops in one variable. d = { "result":[], "out":[] } quest = Question.objects.annotate(choice_count=Count('choice')) ans = Answer.objects.annotate(solution_count=Count('solution')) for i quest: d["quest "].append(i) print(d) for i ans: d["out"].append(i) print(d) return Response({'data':{'staus':d}} -
Django forms.DateInput putting leading zeroes in production because of linux
So I have date inputs in my site where I need the dates to have no leading zeroes in the month or day column which works in my development environment which is a windows machine. 'date_filed': DateInput( format=('%#m/%#d/%Y') But when I push this into my azure production which runs on a linux machine the leading zeroes come back because linux uses format=('%-m/%-d/%Y') instead of format=('%#m/%#d/%Y') Anybody have any suggestions than switching machines? Here is the rest of my form class if that matters class FormClass(ModelForm): class Meta: model = SomeModel fields = "some field names" widgets = { 'date_filed': DateInput( format=('%#m/%#d/%Y'),attrs={ }), -
Django many-to-many raw query
I'm working with a Spotify playlist dataset in Django. I have the following models. class Artist(models.Model): uri = models.CharField(max_length=255) name = models.CharField(max_length=255) class Track(models.Model): uri = models.CharField(max_length=255)= name = models.CharField(max_length=255) artist = models.ManyToManyField(Artist) duration_ms = models.IntegerField() class Playlist(models.Model): pid = models.IntegerField() name = models.CharField(max_length=255) collaborative = models.BooleanField(default=False) tracks = models.ManyToManyField(Track) num_followers = models.IntegerField() Django created the through model for playlist_tracks with the fields: class playlist_tracks(models.Model): id = models.IntegerField() playlist_id = models.IntegerField() track_id = models.IntegerField() I have a section in the track detail template where I would like to make recommendations for other tracks. Loop through each playlist and make an entry that tallies all the other tracks in that playlist. If that track appears in the next playlist, increment the counter, otherwise, add it to the table. Once the loop is complete, order by descending, and limit to 10. This SQL query does what I want in the SQLite viewer, however, I can't work out what the django syntax for writing this query should be. SELECT *, count(track_id) as num_occurences FROM spotify_playlist_tracks WHERE playlist_id in ( SELECT playlist_id FROM spotify_playlist_tracks WHERE track_id = 26(***arbitrary pk) ) GROUP BY track_id ORDER BY num_occurences DESC LIMIT 10 Including it as a model … -
how to make the captcha have a bootstrap class?
I have a problem with the captcha, I'm using the ¨Django Simple Captcha¨ the problem is that it doesn't let me place a bootstrap class so that the input has a better appearance. I tried to: I Put widget_tweaks in that input, but it does not send the data correctly and marks errors html <label class="form-label">Captcha</label> {% render_field form.captcha class="form-control" %} From forms I placed a class inside the widget, but it doesn't work forms.py class RegisterForm(UserCreationForm): captcha=CaptchaField(widget=forms.TextInput(attrs={'class': 'form-control'})) I took the input id and edit it in my style.css but the bootstrap class is not visible either style.css #id_captcha_1{ height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.42857143; color: #555; background-color: #fff; background-image: none; border: 1px solid #ccc; border-radius: 4px; } Any ideas for that input to have the bootstrap class? -
Django: Response from two models with one view
I have the following models: class Message(models.Model): timestamp = models.DateTimeField(default=None) messageId = models.CharField(max_length=256) userId = models.ForeignKey(User, on_delete=models.CASCADE) chatId = models.ForeignKey(Chat, on_delete=models.CASCADE) class Meta: abstract = True class Text(Message): message = models.TextField() translation = models.TextField(blank=True) def __str__(self): return self.message def image_directory_path(instance, filename): return '{0}/images/{1}'.format(instance.userId, filename) class Image(Message): image = models.ImageField(upload_to=image_directory_path) description = models.CharField(max_length=128, blank=True) Now I want to make a get request to /endpoint/ and response with a combination of text and images ordered by the timestamp. How can I do that? -
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