Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: type object 'AdminSignUpForm' has no attribute 'as_view' why is this not working?
Creating a simple multiple users app. The as_view method is working with all the other views but not on this particular one. I have no clue why. Here are my models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) class Admin(models.Model): admin = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField() def __str__(self): return f'{self.user.username} Admin' class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) quizzes = models.ManyToManyField(Quiz, through='TakenQuiz') interests = models.ManyToManyField(Subject, related_name='interested_students') def get_unanswered_questions(self, quiz): answered_questions = self.quiz_answers \ .filter(answer__question__quiz=quiz) \ .values_list('answer__question__pk', flat=True) questions = quiz.questions.exclude(pk__in=answered_questions).order_by('text') return questions def __str__(self): return self.user.username Here are my forms.py class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('students:quiz_list') class AdminSignUpView(CreateView): model = User form_class = AdminSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'admin' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('home') Here is the traceback Traceback (most recent call last): File "C:\Program Files\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Program Files\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\mikha\issue_env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\management\base.py", line 487, in check … -
Export to excel in django not working quite as i hoped it would
I am a django beginner, Trying to export an excel writer to excel in a django front end app using the results of function1 in function2 which contains the code to export/download the file but i can't seem to get it to work. It works when i include the export to excel code in function1 in my views.py (its a project with quite some sensitive data hence why i wont be sharing the actual code here). Each function has a button that run it to provide the required output but This doesnt work, i appreciate any help on this def function1(request): #post method request with filters from the frontend #use filters to read in the data df = read_sql("query with filters") #created a writer output = BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') #called functions that send output to writer sheets, see example below check_for_duplicates(df,writer) #create context to render some sample output on the frontend return render(request, 'home.html', context) def function2(request): function1(request) # gets me the results i want to export to excel writer.save() output.seek(0) response = StreamingHttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename=customers_{lebook}.xlsx' return response I tried to put the code that appears in function2 in function1 and it worked but in … -
Websocket does not receive a message from django channels server even though they are connected
I am currently building an application with django channels. I have a websocket connected to a server. Looking at my terminal, it seems like the websocket is successfully connected to the server. HTTP GET / 200 [0.01, 127.0.0.1:62087] HTTP GET /static/video/js/websocket.js 200 [0.00, 127.0.0.1:62087] WebSocket HANDSHAKING /ws/video [127.0.0.1:62089] WebSocket CONNECT /ws/video [127.0.0.1:62089] However, the websocket does not receive the message sent from the server. Here are my codes: consumers.py import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class VideoConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(json.dumps({'message': 'you are connected!'})) websocket.js const address = 'ws://' + window.location.host + '/ws/video' const websocket = new WebSocket(address) const btn = document.getElementById('myButton') websocket.onopen = (event) => { console.log('websocket connected!!!') } websocket.onmessage = (event) => { console.log(event.data) } I would like to receive the message "you are connected!" on my browser's console. I looked into the official django channels document and google searched for a solution but I failed to solve my issue. What am I missing here? -
Include and Static statements are not being recognized with GitPages
I am new to GitPages and have successfully built and ran my page. However, the {% include %} and {% static %} methods in my index.html aren't being registered. As you can see here. Additionally, my two static files referenced in this file (circleselfie.png and home.css) have weird characters in their static paths when inspecting the page. Here is my project: https://github.com/jishli113/JSite/tree/master. What is causing this? -
nginx: Django X-frame options "DENY"
I am working with Django, Nginx, Gunicorn creating a printing file. For printing I am using templated docs. I have successful test cases for everything except loading a signature using jsignature. Loading the jsignature can be done many ways, however each time I add a {% load 'tag' %} in my document, nginx returns a X-Frame Options DENY/ 404. Removing the tag causes everything to work as normal. Nginx config: server { listen 80; server_name 3.142.15.65; index index.html index.htm; root /home/ubuntu/chippedoutauto; #path_to_your_directory # Forbidden files or directories location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md) { return 404; } # Directory verification related settings for one-click application for SSL certificate location ~ \.well-known{ allow all; } location /static/ { autoindex on; alias /home/ubuntu/chippedoutauto/chippedOutERP/static/ ; } location /static/js/ { alias /home/ubuntu/chippedoutauto/chippedOutERP/static/js/; } location /templatetag/jsignature/{ alias /home/ubuntu/venv/lib/python3.8/site-packages/jsignature/templatetags/; } location /static/admin/ { alias /home/ubuntu/chippedoutauto/chippedOutERP/static/admin/; } location /static/bootstrap_datepicker_plus/{ alias /home/ubuntu/chippedoutauto/chippedOutERP/static/bootstrap_datepicker_plus/; } location / { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; #Persistent connection related configuration add_header X-Cache $upstream_cache_status; #Set Nginx Cache add_header Cache-Control no-cache; expires 12h; } access_log /home/ubuntu/chippedoutauto/bin/logs/chippedOutEPR.log; error_log /home/ubuntu/chippedoutauto/bin/logs/chippedOutERP.error.log; } I have attempted to use both the built in image tag from templated docs while using "draw_signature" from jsignature, as … -
Don't "s()" and "si()" work properly in Django?
I have add() task in tasks.py in Django as shown below. *I use Celery 5.2.7 and django-celery-results in Django on Windows 11: # "store/tasks.py" from celery import shared_task @shared_task def add(x, y): return x + y Then, I called add.delay(3, 4) in test() in views.py as shown below: # "store/views.py" from .tasks import add from django.http import HttpResponse def test(request): add.delay(3, 4) # Here return HttpResponse("Test") Then, I could properly get the result below: Task store.tasks.add[...] succeeded in 0.06s: 7 # Here But, when calling add.s(3, 4) and add.si(3, 4) in test() as shown below, nothing were displayed: # "store/views.py" from .tasks import add from django.http import HttpResponse def test(request): add.s(3, 4) # Here add.si(3, 4) # Here return HttpResponse("Test") So, don't s() and si() work properly in Django? -
Django - ImageField with multiple images
I have a model that has an ImageField. I want users to be able to upload multiple images for an object of the model - not only a single image. How can this be done? Whether with and image field or another approach. -
How to call an async function from template?
When the user clicks a specific button, I want to call an synchronous function inside the already used view function, but passing a parameter from JavaScript. How can I do it? Template: <input class="form-check-input" type="checkbox" value="{{ subject.id }}" id="flexCheckDefault{{ subject.name }}" onclick="checkRequisite(this.defaultValue)"> Javascript: function checkRequisite(id){ } View: if request.user.is_authenticated and request.user.groups.filter(name='student'): subjects = subject.objects.all() async def checkResquisite(id): requisite = Requisite.objects.filter(subject_requisite_id=id) context = {'subjects': subjects, 'requisite': requisite} template = loader.get_template('student/subject/select.html') return HttpResponse(template.render(context, request)) elif request.user.is_authenticated and request.user.groups.filter(name='teacher'): return render(request, 'admin/home/index.html', {}) else: return redirect('login') -
Django Rest Framework - How to create nested objects validation in serializers
I'm learning drf and wanted to move part of my creation logic into serializer but I've stucked. I have the following models. class Created(models.Model): id = models.AutoField(primary_key=True) created = models.DateField(default=timezone.now) class Meta: abstract = True class UniqueName(Created): name = models.CharField(unique=True, max_length=200) class Meta: abstract = True class Categories(UniqueName): ... class Answers(Created): name = models.CharField(max_length=200) correct = models.BooleanField(default=False) class Questions(UniqueName): category = models.ForeignKey(Categories, on_delete=models.CASCADE) answers = models.ManyToManyField(Answers, related_name="question") @property def correct_answer(self): return self.answers.filter(correct=True).first() Any my json input looks like following: { "category":"Harry Potter2", "questions":[ { "name":"What is Harrys Name", "answers":[ { "name":"Potter", "correct": true }, { "name":"blabla" } ] }, { "name":"What is Hermion Name", "answers":[ { "name":"Grenger", "correct": true }, { "name":"blabla" } ] } ] } Currently I'm handling this in my view (what is not elegant). category, _ = models.Categories.objects.get_or_create(name=data.category) for q_obj in data.questions: question, _ = models.Questions.objects.get_or_create( name=q_obj.name, category=category ) for a_obj in q_obj.answers: if not question.answers.filter(name=a_obj.name).first(): answer = models.Answers.objects.create( name=a_obj.name, correct=a_obj.correct ) question.answers.add(answer) I'd like to move this logic into serializer but I have no idea how I could combine them together. I'd appreciate any hints. Thanks! -
Django: Get latest N number of records per group
Let's say I have the following Django model: class Team(models.Model): name = models.CharField(max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True) I want to write a query to fetch the latest N number of records per team name. If N=1, the query is very easy (assuming I'm using postgres because it's the only DB that support distinct(*fields)): Team.objects.order_by("name", "-created_at").distinct("name") If N is greater than 1 (let's say 3), then it gets tricky. How can I write this query in Django? -
Django - How to Filter Nested Loop in Views
{% for race_team in race_team_list %} <tr> <td>{{ race_team.tactic }}</td> <td>{{ race_team.token }}</td> <td>{{ race_team.budget }}</td> <td>{{ race_team.team.name }}</td> {% for team_race_driver in race_team.team.race_drivers.all %} {% if team_race_driver.race == race %} <td>{{ team_race_driver.driver }} <small class="text-muted d-block">{{ team_race_driver.total_point }}</small> </td> {% endif %} {% endfor %} </tr> {% endfor %} In my Django template, this part puts every database line in RaceTeam model in a table row and for each driver attending the race, adds these drivers in the row. race_team_list is the context which includes teams from only that particular race (1st race let's say). However, in race_team.team.race_drivers.all it lists all instances of race_driverswhich team had, for example, my team had Driver A in race1 and race2, DriverB only in race2. In order to filter out the instances with race2, i have a if block in the template but I don't think it's the best way to put the code logic which should have been in views.py. However, I am not able to put it in views.py because I cannot filter out the race_team.team.race_drivers instances. I thought about joining the race_team and race_driver instances or making a ternary relation named RaceDriverTeam but due to having attributes on RaceTeam and … -
How to prevent Django serializer get method executes multiple times
I have a serializer making calls to other serializers in order to produce one Article object containing all data required for the frontend. Everything works as expected except the get_sentiment() method is called multiple times and I can't figure out why. I tried to copy the behaviour from the Tag serializer, which produces one list containing all of the tags required. For some reason the article_sentiment field produces multiple lists. If there is any insight on why DRF is producing the behaviour it'll be much appreciated. Here are the serializers. class TagSerializer(serializers.ModelSerializer): class Meta: fields = ( 'tag', ) model = Tag class SentimentSerializer(serializers.Serializer): sentiment=serializers.SerializerMethodField() class Meta: fields = ( 'sentiment', ) model = Reaction def get_sentiment(self, obj): likes = Reaction.objects.filter(article_id=obj.article_id, sentiment=1).count() dislikes = Reaction.objects.filter(article_id=obj.article_id, sentiment=2).count() if likes + dislikes == 0: return 0 else: percent = (likes / (likes + dislikes)) * 100 print(obj.article_id.title + str(percent)) items = [likes, dislikes, percent] return items """ Gets the full details of an Article """ class ArticleSerializer(serializers.ModelSerializer): article_tags = TagSerializer(many=True, read_only=True) article_sentiment = SentimentSerializer(many=True, read_only=True) class Meta: fields = ( 'id', 'title', 'content', 'article_tags', 'pub_date', 'preview_image', 'author', 'author_profile_name', 'article_sentiment', ) model = Article Here is the ouput thank you -
Django codes for solving common issues
Any common issues and solution that anyone would like to throw up here ? Below are some of the solutions to the common errors/problems that I ran into in the past. Thank you Q1: "if error, no such table" Ans: try run :" python manage.py migrate --run-syncdb " this command will look into which tables were not created and will create all the needed tables Q2: "if encounter....".... migration admin.0001_initial is applied before its dependency ...._initial on database 'default '. " Ans: just delete the 001 initial .py from migration folder and delete db.sqlite3 then run migration , migrate -
504 Gateway Time-out django mail
I use nginx. I get this error when I try to send an email. The SMTP data is completely correct. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.yandex.ru' EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_HOST_USER = "123@yandex.ru" EMAIL_HOST_PASSWORD = "1234" DEFAULT_FROM_EMAIL = "123@yandex.ru" send email message = render_to_string('user/email_confirmation.html', context=context) email = EmailMessage( '124', message, to=[user.email], ) email.send() On the other server, everything is exactly the same and everything works. But here there is an error. -
How do I ensure validation of my django form?
I am attempting to create a form in which a user can enter two dates to specify a block. However if there already exists a block with dates that overlap the ones the user enters then an error message should be displayed. Additionally I want to ensure that the start date of the block is before the end date. However every time I run my view method, the user is allowed to defy both constraints with no error message displayed. This is my views.py method def set_block_dates(request): if request.method == 'POST': form = BlockForm(request.POST) if form.is_valid(): if (form.check_overlap and form.check_time): form.save() return redirect('home') else: messages.add_message(request, messages.ERROR, "The dates cannot overlap and start date must be before end date!") else: form = BlockForm() return render(request, 'setBlockDates.html', {'form': form}) This is my forms.py class class BlockForm(forms.ModelForm): class Meta: model = Block fields = ['start', 'end'] def check_time(self): return True if self.cleaned_data.get('start') < self.cleaned_data.get('end') else false def check_overlap(self, *args, **kwargs): overlapping_start_dates = Block.objects.filter(start__gte=self.cleaned_data.get('start'), start__lte=self.cleaned_data.get('end')).count() overlapping_end_dates = Block.objects.filter(end__gte=self.cleaned_data.get('start'), end__lte=self.cleaned_data.get('end')).count() overlapping_dates = overlapping_start_dates > 0 or overlapping_end_dates > 0 if overlapping_dates: return False else: return True def save(self): super().save(commit=False) block = Block.objects.create( start_date = self.cleaned_data.get('start'), end_date = self.cleaned_data.get('end'), ) The user is allowed to submit … -
I can't add a value to this user model field
I'm trying to do a system where an user gains points if he asks a question but the points field isn't increasing when a user does that. my model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='post') category = models.ForeignKey(Category, on_delete=models.PROTECT) type = models.CharField(max_length=30, choices=TYPE, default='Question') title = models.CharField(max_length=100, unique=True) content = models.TextField() views = models.IntegerField(default=0) votes = models.ManyToManyField(User, blank=True, related_name='vote') featured = models.BooleanField(default=False) date_posted = models.DateTimeField(default=timezone.now) my view: class PostCreateView(LoginRequiredMixin, CreateView): model = Post success_url = '/' fields = ['title', 'content', 'category'] def form_valid(self, form): form.instance.author = self.request.user form.instance.author.points + 15 return super().form_valid(form) When I go to the current user in the admin page the value doesn't change. -
Using 'group()' got "No result backend is configured." error in Django
With the code below, I use Celery 5.2.7 and django-celery-results in Django: # "core/celery.py" import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') # "core/settings.py" INSTALLED_APPS = [ # ... 'django_celery_results' ] CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' # "store/tasks.py" from celery import shared_task @shared_task def add(x, y): return x + y Then, I ran Celery with the command below: celery -A core worker --pool=solo -l info Then, called add.delay(3, 4) in test() as shown below: # "store/views.py" from .tasks import add from django.http import HttpResponse def test(request): add.delay(3, 4) # Here return HttpResponse("Test") Then, I could properly get the result below: Task store.tasks.add[...] succeeded in 0.04s: 7 # Here But, when calling group(add.delay(i, i) for i in range(10))().get() in test() as shown below: # "store/views.py" from celery import group from django.http import HttpResponse def test(request): group(add.delay(i, i) for i in range(10))().get() # Here return HttpResponse("Test") I got the error below: NotImplementedError: No result backend is configured. Please see the documentation for more information. So, I tried si() as shown below: # "store/views.py" from celery import group from django.http import HttpResponse def call_test(request): # ↓ Here group(add.si(i, i) for i … -
Websocket does not receive any message from django channels
I am currently building an application with django channels. I have a websocket connected to a server. Looking at my terminal, it seems like the websocket is successfully connected to the server. HTTP GET / 200 [0.01, 127.0.0.1:62087] HTTP GET /static/video/js/websocket.js 200 [0.00, 127.0.0.1:62087] WebSocket HANDSHAKING /ws/video [127.0.0.1:62089] WebSocket CONNECT /ws/video [127.0.0.1:62089] However, the websocket does not receive the message sent from the server. Here are my codes: consumers.py import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class VideoConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(json.dumps({'message': 'you are connected!'})) websocket.js const address = 'ws://' + window.location.host + '/ws/video' const websocket = new WebSocket(address) const btn = document.getElementById('myButton') websocket.onopen = (event) => { console.log('websocket connected!!!') } websocket.onmessage = (event) => { console.log(event.data) } I would like to receive the message "you are connected!" on my browser's console. I looked into the official django channels document and google searched for a solution but I failed to solve my issue. What am I missing here? -
ValueError at /create_post/
When I click the Create New Post button, I get this error. The service.views.create_post view did not return an HttpResponse object. Instead, it returned None. view.py @login_required @permission_required("service.add_post") def create_post(req): form = PostForm() if req.method == "POST": form = PostForm(req.POST) if form.is_valid(): form.save() title = form.cleaned_data.get("title") if title != "POST": messages.error(req, f"Something went wrong") return redirect('index') id = form.cleaned_data.get("pk") messages.success(req, f"Post {title} was created successfully") return redirect('index') return render(req, "create_post.html", {"form":form}) Nothing because I don't understand the error -
Django Category LIst
I want to show all categories in sidebar can you help me !!! how to list all category pls help my models.py categories = models.ManyToManyField('Category', verbose_name=_('Categories'), blank=True) class Category(models.Model): display = models.CharField(_('Category'), max_length=100) slug = models.SlugField(_('Slug'), unique=True) def __str__(self): return self.display @property def get_absolute_url(self): return reverse_lazy('category_list', args=[self.slug]) class Meta: verbose_name_plural = _('Categories') my views.py class CategoryList(BaseListView): def get_queryset(self): posts = ( Post.objects.filter(is_published=True) .filter(categories__slug=self.kwargs.get("cat")) .order_by("-modified_date") ) term = self.request.GET.get("search") if term: posts = posts.filter(title__icontains=term) return posts def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["list_term"] = Category.objects.get(slug=self.kwargs.get("cat")).display context["list_type"] = "category" return context I've tried but I'm not sure I can do it -
Django annotate with
How can i use average_ndvi and field_count variables into annotate, i need change 0.14 to F"average_ndvi", 5 to F"field_count". commune = ( Commune.objects.annotate( year=SearchVector("field__fieldattribute__date__year"), month=SearchVector(Cast("field__fieldattribute__date__month", CharField())), size=Sum(F("field__fieldattribute__planted_area")), average_ndvi=Avg(F("field__fieldattribute__ndvi")), field_count=Count("field"), standart_deviation=Sum( ((F("field__fieldattribute__ndvi") - 0.14) ** 2) / 5, output_field=FloatField(), ), ) .filter(year=year, month=str(month)) .only("id", "name") ) -
How to order a combined queryset by annotated field?
The weight for our objects is composed of 2 fields. One field is the weight unit (kilogram, tonne and pound) and the other field is the weight (number). I have tried making a queryset which annotates all the weights into one universal unit field. The problem is that once I order_by that annotated (unit) field, it still orders by largest number and not by largest weight. For example 100kg is less than 50t, but the ordering system just sorts by the largest number. This is the code inside the filters.py: ` class AircraftFilter(FilterSet): tail_number = CharFilter(field_name="tail_number", lookup_expr="startswith") by_weight = CharFilter(method="filter_by_weight") class Meta: model = Aircraft fields = ("tail_number", "by_weight") def filter_by_weight(self, qs: QuerySet, value, *args, **kwargs): if value != None: qs = ( qs.filter(max_takeoff_weight_unit=2).annotate( mtw_lb=F("max_takeoff_weight") * 2200 ) | qs.filter(max_takeoff_weight_unit=1).annotate( mtw_lb=F("max_takeoff_weight") * 2.2 ) | qs.filter(max_takeoff_weight_unit=3).annotate( mtw_lb=F("max_takeoff_weight") ) ) qs = qs.order_by("mtw_lb") return qs ` The query: `qs = (Aircraft.objects.all().filter(max_takeoff_weight_unit=2).annotate(mtw_lb=F("max_takeoff_weight")*2200) | Aircraft.objects.all().filter(max_takeoff_weight_unit=1).annotate(mtw_lb=F("max_takeoff_weight") * 2.2) | Aircraft.objects.all().filter(max_takeoff_weight_unit=3).annotate(mtw_lb=F("max_takeoff_weight"))).order_by("mtw_lb")` and the output: `<IsActiveModelQuerySet [ID: 5 | weight: 0.05 - (t) , ID: 4 | weight: 0.20 - (t) , ID: 8 | weight: 2.00 - (t) , ID: 7 | weight: 50.00 - (lbs) , ID: 6 | weight: 100.00 - (kg) ]>` -
i get an error while i use 'is none' in DJANGO [closed]
If there is no row in the Duyuru table registered to the database, I want the h5 tag to be displayed on the screen. But the h5 tag does not appear on the screen. This is my html file: (https://i.stack.imgur.com/K6Pte.png) and this is views: (https://i.stack.imgur.com/V7OWg.png) Can you help me? -
I try to be able to load an image in the django admin, but I can't see it when I click
I don't know how to solve it. It's really frustrating. If you managed to help, I would be very grateful. settings: ``` ``` STATIC_URL = '/static/' MEDIA_URL='Proyectoweb/media/' MEDIA_ROOT=BASE_DIR / 'Proyecto/media' ``` ``` url: ``` ``` from django.urls import path from ProyectoApp import views from django.conf import settings from django.conf.urls.static import static ``` ``` urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` ``` models: ``` from django.db import models # Create your models here. class Servicio(models.Model): titulo=models.CharField(max_length=50) contenido=models.CharField(max_length=50) imagen=models.ImageField(upload_to='servicios') created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='servicio' verbose_name_plural='servicios' def __str__(self): return self.titulo ``` admin: ``` from django.contrib import admin from .models import Servicio # Register your models here. class ServicioAdmin(admin.ModelAdmin): readonly_fields=('created', 'updated') admin.site.register(Servicio, ServicioAdmin) ``` For some reason, this page asks me for more details, when I think I have already given enough. I try to be able to load an image in the django admin, but I can't see it when I click.... -
How can I set a variable width in my CSS or Tailwind class?
I am getting the width from my Django View, but I do not know if I can make it variable in CSS. I’ve been trying to set the Tailwind, but I imagine that it is not the right thing to do: {% for movie in movies %} <div id="bar" class="w-[{movie.score}]" style="transition: 1s"> {{movie.score}} </div> {% endfor %} However, I am also trying to do it directly in CSS, but the style does not accept a variable as: {% for movie in movies %} <div id="bar" style="transition: 1s; width: {{movie.score}}; "> {{movie.score}} </div> {% endfor %} I’ve also tried to change it using JavaScript, but I have to select multiple elements because there will be various bars. So, this just not worked. I receive messages that the movies were declared before if I use let, but using var nothing changes. def get_context_data(self, **kwargs): context = super(MoviesRatePage, self).get_context_data(**kwargs) context['movies'] = movies return context {% block javascript %} <script type="text/javascript"> var movies = "{{movies}}"; for (let i = 0; i < movies.length; i++) { document.querySelectorAll("#bar")[i].style.width = `${movies[i].score}%`; } </script> {% endblock javascript %} Thus, I want to make the bar width the same as the movie’s score.