Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a new user in Django returns: "Object of type Users is not JSON serializable"
I am trying to create a new user in Django and get the error: Object of type Users is not JSON serializable The error seems quite self explainatory - but I just cannot even get a print of the suspected vars to make sure this is what causing all the trouble. I have been working django for a while and noticed that i just do not know to find where is the error exactly (not only in this case). So as a bonus if anyone can walk me through the stages of debugging this - this might save me tons of questions on the future. [13/Feb/2021 20:31:55] "POST /api/register/ HTTP/1.1" 400 62 Internal Server Error: /api/register/ Traceback (most recent call last): File "/Users/mypc/.pyenv/versions/anaconda3-2020.07/envs/SN/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/mypc/.pyenv/versions/anaconda3-2020.07/envs/SN/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mypc/.pyenv/versions/anaconda3-2020.07/envs/SN/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/mypc/.pyenv/versions/anaconda3-2020.07/envs/SN/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Users/mypc/.pyenv/versions/anaconda3-2020.07/envs/SN/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/mypc/.pyenv/versions/anaconda3-2020.07/envs/SN/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/mypc/.pyenv/versions/anaconda3-2020.07/envs/SN/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/mypc/.pyenv/versions/anaconda3-2020.07/envs/SN/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/mypc/.pyenv/versions/anaconda3-2020.07/envs/SN/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in … -
Incorrect type. Expected pk value, received str in DRF.(one to one field)
When I send post request with data in profile model at that time this error show. Error { "user_name": [ "Incorrect type. Expected pk value, received str." ] } I saw this answer but don't know how to implement SlugRelatedField in serializers(OneToOneField) models.py: class CustomUser(AbstractUser): # username_validator = UnicodeUsernameValidator() username = models.CharField( max_length=80, unique=True, ) email = models.EmailField( unique=True, blank=True, ) ..... def __str__(self): return '%s' %(self.username) class Profile(models.Model): user_name = models.OneToOneField(to = CustomUser,on_delete=models.CASCADE) full_name = models.CharField(null=True,max_length=15, blank=True) public_name = models.CharField(null=True,max_length=15, blank=True) .... serializers.py: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['user_name','full_name','public_name'] views.py: class ProfileApiview(CreateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer -
Can you daemonize Celery through your django site?
Reading the daemonization Celery documentation, if you're running Celery on Linux with systemd, you set it up with two files: /etc/systemd/system/celery.service /etc/conf.d/celery I'm using Celery in a Django site with django-celery-beat, and the documentation is a little confusing on this point: Example Django configuration Django users now uses [sic] the exact same template as above, but make sure that the module that defines your Celery app instance also sets a default value for DJANGO_SETTINGS_MODULE as shown in the example Django project in First steps with Django. The docs don't just come out and say, put your daemonization settings in settings.py and it will all work out, bla, bla. From another SO posts this user seems to have run into the same confusion where Django instructions imply you use init.d method. Bonus point if you can answer if it's possible to run Celery and RabbitMQ both configured and with the Django instance (if that makes sense). -
Django on heroku DEBUG settings
I am a bit confused about the settings for django. I have something like this setup in my settings.py file locally: """ Django settings for ebportfolio project. Generated by 'django-admin startproject' using Django 3.1.6. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import environ env = environ.Env( # set casting, default value DEBUG=(bool, False) ) environ.Env.read_env() DEBUG = env('DEBUG') # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = environ.Path(__file__)-1 # BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! ALLOWED_HOSTS = ['127.0.0.1', 'my heroku address'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cloudinary', 'cloudinary_storage', 'django_summernote', 'projects', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ebportfolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['ebportfolio/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ebportfolio.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { # read os.environ['DATABASE_URL'] and … -
Django Nginx Media Folder for User Upload/Download
As part of an app I am working on with Django DRF and Vue, I have a section for uploading and downloading files. Files get uploaded to a media folder and are displayed as a list where users can download them. This all works fine in development running 'python manage.py run server' and 'npm run serve' but I am getting mixed results deploying it on Nginx with Docker. I have tried every configuration possible. Currently, uploading and showing as a list is working without issue. When trying to download the files I am getting a 404 not found error. It is using the correct URL: "[website]/media/[file]". When looking in my Docker folder directory, the file exists at the specified path, so I am not sure what is going on. This is the server configuration I believe may need to be adjusted. server { listen 443 ssl; server_name [website].com www.[website].com; root /dist/; index index.html; ssl_certificate /etc/letsencrypt/live/keeptrackapp.ca/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/keeptrackapp.ca/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # backend urls location ~ ^/(admin|api|accounts|media|registration|auth|api-auth) { proxy_redirect off; proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; } location = /robots.txt { log_not_found off; } location = /sitemap.xml { log_not_found off; } location = /favicon.ico { log_not_found off; } … -
Django Rest Framework - I have working API with curl commands, how can I change it to work with standard http requests in browser?
I think that I might have misunderstood something. I created Django Rest Framework app. I have working api with tokens, query_params etc. Everything is working if I make a curl like that: curl -X "GET" http://localhost:8000/api/results -H "Content-Type: application/json" -H "Authorization: Token eeea084811d9213aa3803946e4464758d66966bc" --data 'make=test' It is actually returning proper records. But often, on other websites I see that they are implementing their api for users in this format: http://www.example.com/?apikey=[yourkey]& I tried to look up converting curl to http but I didn't find anything useful for me and now I am confused. Maybe my api works only with curl currently? Maybe this "http call" needs to be somehow implemented/coded additionally? I suspect that this question is stupid but I don't know yet proper keywords to google it unfortunately. -
Django model autorelation sublevel
I am new to development under the Django framework and I have not found a documentation or tutorial that specifies how to translate to models the data design that I will specify. As an oversimplified example we will devise a production / assembly chain in which a product can depend on / consume X products for its construction. It would be represented by the following structure: Which would translate to the following SQL (on SQL Server): CREATE TABLE [Product] ( [Id] Int PRIMARY KEY IDENTITY(1, 1), [Name] varchar(64) UNIQUE NOT NULL ) CREATE TABLE [ProductRequirement] ( [Id] Int PRIMARY KEY IDENTITY(1, 1), [Product] Int, [ProductRequired] Int, [Quantity] Int NOT NULL, FOREIGN KEY ([Product]) REFERENCES Product([Id]), FOREIGN KEY ([ProductRequired]) REFERENCES Product([Id]), ) But I can't figure out what its representation would be in a Django model, I've tried the following interpretation: class Product(models.Model): name = models.CharField(primary_key=True, max_length=60) class Requirement(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, blank=False, null=False, ) productRequired = models.ForeignKey( Product, on_delete=models.CASCADE, blank=False, null=False, ) Quantity = models.DecimalField(blank=False, max_digits=2, decimal_places=0) But it exhibits the error (when executing 'makemigrations'): Production.Requirement.product: (fields.E304) Reverse accessor for 'Requirement.product' clashes with reverse accessor for 'Requirement.productRequired'. HINT: Add or change a related_name argument to the definition for … -
Django mistake in views or HTML
I have created a quotes model: class Quote(models.Model): book = models.ForeignKey(BookModel, on_delete=models.CASCADE, related_name='quotes') text = models.CharField(max_length=1028) def __str__(self): return self.text Here's my views.py: class Quotes(generic.ListView): model = Quote template_name = 'books/book_quotes.html' context_object_name = 'quote' Here's my URLs.py: path('quotes/', views.Quotes.as_view(), name='book-quotes'), I have also created quotes for books in admin panel. But when I go to quotes/ it shows no quotes despite the fact they actually exist. Here's my quotes HTML template: {% extends 'base.html' %} {% for object in object_list %} {{ object.book.title }} {{ object.text }} {% endfor %} Why doesn't it show objects? Please, help. Thank you -
Django/Flas using Python modules
I'm trying to build a little converter website. pdf to docx, images to pdf, csv to excel etc... I really want to use node as my static files host server. But as I know node doesn't have that cool modules to handle such convertations. I think of using another server of python, e.g flask or django frameworks. Well the reason I want to use python is I believe python has way better modules for such tasks. My question is does Flask/Django support all modules from Python? Or can you suggest me anything better than having two servers running for my converting website? Thanks, have a good day. -
how to show url images objects in forms.py
ican't view image how can show image in template using crispy_forms.layout html this code don't do this img is Empty from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, html, div class ExampleForm(forms.Form): def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( HTML(""" <img src="{{image.value.url}}" class="card-img-top" width="50px" height="100px" alt="..."> """), ) } please how can fixed this. -
Save and Update data from custom html forms in django
I've created a custom HTML form for my model, just like I want to add a post from the front-end. I already created a page with the name add-post.html <form method="POST" action=""> {% csrf_token %} <input name="title" type="text"> <textarea spellcheck="false" name="description"></textarea> <input type="file" name="image" @change="fileName" multiple /> <select required name="priority"> <option value="Low" selected>Low</option> <option value="Medium">Medium</option> <option value="High">High</option> </select> <input type="checkbox" name="on_hold"> <button type="submit">Add ToDo</button> </form> Here's my model.py class Todo(models.Model): title = models.CharField(max_length=100) image = models.ImageField(null=True, blank=True, upload_to='todo/images/') description = RichTextField() Low, Medium, High = 'Low', 'Medium', 'High' priorities = [ (Low, 'Low'), (Medium, 'Medium'), (High, 'High'), ] priority = models.CharField( max_length=50, choices=priorities, default=Low, ) on_hold = models.BooleanField(default=False) No, I want to use the above custom HTML form to post data and save it to this model database. instead of using {% form.as_p %} And I also created a particular page to update this post from the front-end but don't know how to make it work. Can you please guide me on how can I save data from the custom form and also update it from the custom form? Appreciate your response :) -
templates variables in django
I'm trying to use template variable to access templates dictionaries when I do {{ pair_name.8 }} it works but {% with xx=8 %}{{ pair_name.xx }}{% endwith %} doestnt work, please help -
Django Query Database in models.py
A very beginner question I'm sure: I'm trying to make a dynamic table using the values from another table. Is there any way to query the database inside of models.py to build an array? This code works if I manually enter the values but I cannot find a way to query the database. from django.db import models import uuid import datetime # datalogHeaders = ["header1" , "header2"] class keyinfo(models.Model): UUID = models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4, primary_key=True) pointKey = models.CharField(max_length=30, blank=True) pointID = models.CharField(max_length=30, blank=True) pointName = models.CharField(max_length=30, blank=True) address = models.CharField(max_length=30, blank=True) datalogHeaders = keyinfo.objects.get(id=2) class csvhistory(models.Model): UUID = models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4, primary_key=True) csvImportTimestamp = models.DateTimeField(default=datetime.datetime.now()) class datalogs(models.Model): dataImportTimestamp = models.DateTimeField(default=datetime.datetime.now(), primary_key=True) csvUUID = models.CharField(max_length=100, blank=True) pass for dataHeaders in datalogHeaders: datalogs.add_to_class(dataHeaders, models.CharField(max_length=30, blank = True)) -
How can I remove multiple file changes/modifications that were mistakenly added to a commit?
Although I have used Git for some time now, I have been stuck on this particular problem for some time. I am pretty sure this question might be labeled as duplicate, but I have yet to find a post that adequately addresses my problem, though I suspect this is because I am not using the right terminology pertinent to this issue. I have made a new branch on a project that uses a Django framework. I created some files, made some changes, and then staged the changes using the typical git add .. In total, there were 4 files I either created or modified. Everything seemed fine. I then committed and pushed the commit to the remote repo, and made a pull request. I then found out there had been not 4 files changed, but over 1000. The vast majority of these changes revolved around binary files in a data folder having some minor changes (note: I had uploaded some files into this Django site in order to test it with my work). So, I decided to follow the steps outlined here (https://stackoverflow.com/a/927386/6645564), with the minor change of only specifically staging the changes git add filename. However, when I committed … -
How to break down 2 datetime fields into 1 date and 2 times in Django Form?
Okay so I am trying to make booking slots (like events/reservations). #models.py class BookingSlot(models.Model): start_time = models.DateTimeField("Start Time") end_time = models.DateTimeField("End Time") location = models.ForeignKey(Court, on_delete=models.CASCADE) As you can see the model has 2 datetime field. I want to make a form for creating booking slots whereby the form contains just one date and two times (assumption is that it is the same day). I am aware I could change my model but that is gonna create a few problems. #forms.py class BookingSlotForm(ModelForm): class Meta: model = BookingSlot fields = ['start_time', 'end_time', 'location'] I was wondering if there was a way I could edit my forms.py to do this. It seems like this is simple enough to do I am just unsure how to formulate a question for it. #views.py class CreateBookingForm(CreateView): template_name = 'app_book/create_bookings.html' form_class = BookingSlotForm success_message = 'Booking slot created' -
cokkiecutter django-shop i am acceting all the options on defaout , and trying for the runserver , which requires docker and debug yes
I have tried this on: ubuntu 20 on the local system and cloud settings Debian buster (10) on google cloud VM have also tried to answer different configuration but the docker is not starting and getting the same error this is the process I am going through: $-- cookiecutter https://github.com/awesto/cookiecutter-django-shop You've downloaded /home/user/.cookiecutters/cookiecutter-django-shop before. Is it okay to delete and re-download it? [yes]: project_name [My SHOP]: project_slug [my-shop]: app_name [myshop]: appName [MySHOP]: description [Blueprint for an e-commerce site based on django-SHOP]: author_name [John Doe]: email [john@example.com]: virtual_host [www.example.com]: version [1.0.0]: timezone [UTC]: Select dockerize: 1 - n 2 - runserver 3 - uwsgi 4 - nginx Choose from 1, 2, 3, 4 [1]: 2 use_i18n [y]: n languages [de, en]: en use_paypal [y]: n use_stripe [y]: n use_sendcloud [y]: n printable_invoice [y]: n Select delivery_handling: 1 - partial 2 - common 3 - n Choose from 1, 2, 3 [1]: 3 Select products_model: 1 - polymorphic 2 - smartcard 3 - commodity Choose from 1, 2, 3 [1]: 3 use_compressor [n]: y use_elasticsearch [y]: Select stock_management: 1 - simple 2 - inventory 3 - n Choose from 1, 2, 3 [1]: debug [y]: the error I am getting: ''' subprocess.CalledProcessError: … -
Django Edit Form not showing the attachment link
Good Afternoon, I have a query when trying to create an edit template, I'm retrieving data via an api call. When I input the data in the django form.Forms the attachment is showing as blank. This is the Form.py file class PaymentListForm(forms.Form): Title = forms.CharField(max_length=50) Receipt_Amount = forms.DecimalField(max_digits=8, decimal_places=2) Request_Amount = forms.DecimalField(max_digits=8, decimal_places=2) Receipt_Attachment = forms.FileField() def __init__(self, *args, **kwargs): super(PaymentListForm, self).__init__(*args, **kwargs) And this is the views.py file def edit_payments(request, trn_pk): trns = get_transaction_by_id(trn_pk) data = trns['data'] if request.method == 'GET': form = PaymentListForm(initial=data) return render(request, 'paymentlist/createeditpayments.html', {'form': form}) I can confirm that in the data dictionary there is the link for the attachment but somehow in the forms the attachment is getting lost. Any help reg this? Thanks -
How to combine 2 model classes in Django?
I have 2 model classes, from the Django poll app tutorial, which I want to be combined to make it easier to create posts. from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) I could just register Choice in admin.py to be used on the admin page, but then i'd have to create a set of choices for every question, which is not efficient. Instead I want the same Choices every time I post a Question, and I want to be able to add them from the Question model. Copying the contents underneath the Choice class to the Question class doesn't work, even when I use the 'self' argument in the ForeignKey function. I have also tried subclassing and multiple inheritance, but that doesn't work (or my implementation was wrong). -
Django model constraint or business logic
I am building my first django project, it will essentially be an assessment form. Each question will be multiple choice. There is no right or wrong answer the questions but instead a grade of what level they are at. So for each question a user can only select one answer out of the possible three options. I have defined the following models from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: verbose_name_plural = 'Categories' class Question(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) capability = models.TextField() weight = models.FloatField(default=1.0) def __str__(self): return self.capability class Grade(models.Model): name = models.CharField(max_length=100) score = models.PositiveIntegerField() def __str__(self): return self.name class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.PROTECT) grade = models.ForeignKey(Grade, on_delete=models.PROTECT) description = models.TextField() def __str__(self): return f'Q{self.question.id} - {self.description}' class Area(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Assessment(models.Model): created = models.DateTimeField(auto_now_add=True) area = models.ForeignKey(Area, on_delete=models.PROTECT) answers = models.ManyToManyField(Answer) def __str__(self): return f'{self.area} - {self.created}' However an assesment will have multiple answers, however it should only be able to contain one answer per question. Can this type of constraint be designed in the model? or it would be part of the business logic. Esentially the user … -
Django Crispy form based on a ForeignKey
I discovered recently django-crispy-forms. I red many threads on stackoverflow (and elsewhere) but couldn't find one that address my issue. For the sake of simplicity, let consider two models as defined thereafter. One model is a foreign key of the other. My goal is to output a crispy form with all the attributes that can be filled by the user. Namely: foo bar attr1 attr2 [models.py] class ModelA(models.Model): attr1 = models.IntegerField() attr2 = models.CharField(max_length=10) class ModelB(models.Model): foo = models.IntegerField() bar = models.CharField(max_length=50) fk = models.ForeignKey(ModelA, on_delete=models.PROTECT) [views.py] class ModelBForm(forms.ModelForm): class Meta: model = ModelB fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.layout = Layout( Fieldset( Field('foo'), Field('bar'), Field('fk') ) I couldn't find a way to achieve it, even though it looks pretty straightforward on paper. Any help? -
How to Make star Rating using django Database
I have a rating for products stored in django models, now I want the rating to show as a star <script> alert('hello') const Select = (size) => { const children = form.children console.log(children[0]) for (let i=0; i < children.length; i++) { if(i <= size) { children[i].classList.add('checked') } else { children[i].classList.remove('checked') } } } Select(ratings); </script> this is the handler for js <form> <button type="submit" class="fa fa-star fa-1x my-btn " id="first"></button> <button type="submit" class="fa fa-star fa-1x my-btn" id="second"></button> <button type="submit" class="fa fa-star fa-1x my-btn" id="third"></button> <button type="submit" class="fa fa-star fa-1x my-btn" id="fourth"></button> <button type="submit" class="fa fa-star fa-1x my-btn" id="fifth"></button> </form> this is the form, Now i dont know if i have to trigger to make the js work or what esle solution do i have -
Is it possible to upload to a filefield from a formset?
Could you please tell me if it is even possible to upload files from a formset record? I have exhausted everything I have found on the internet. In my template, I have: enctype="multipart/form-data" In my view I have: elif request.method == 'POST': formset = PaymentSheetModelFormset(request.POST, request.FILES) When the page is run, it looks like it will upload, but the file is not actually saved to the database. If I open to the single record form, and upload there, it works perfectly. -
Django blocktranslate not working properly
Hello im working on a django admin with multiple languages. i have my locale directory setup and translation, everything is fine but when i use blocktranslate it doesn't work as i want <li class="breadcrumb-item text-info"> {% blocktranslate with name=opts.verbose_name %} Add {{ name }} {% endblocktranslate %} {% trans 'Add' %} </li> This is my code. The 'Add' inside blocktranslate is not working but trans 'Add' works just fine. I don't know what is the deal here but can u guys help me out. Thanks -
i want to create a urlpattern according to users username
i want to load my profile html with user username on urlpattern my views.py def profile(request): return render(request, 'profile.html') my urls.py from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from accounts import views as user_views from . import views # Template Urls! app_name = 'accounts' urlpatterns = [ path('Skolar/',views.base, name= 'base'), path('Register/',views.register,name='register'), path('login/', views.my_login_view, name='login'), path('logout/',views.user_logout,name='logout'), path('<username>',views.profile, name='profile'), path('EditProfile/',views.update_profile,name='editprofile'), ] -
How to align and center 3 divs without affecting middle div
i am making a game score card, and i want to align 3 divs in same line but the score always stays in the center of the page regardless how long the name of the teams are. i tried many things but nothing got me results i wanted, if you can help please do, thanks in advance. team alpha (logo) 0-0 (logo) team beta very long team name (logo) 0-0 (logo) another team {% for match in matches %} <div class="match"> <div class="home"> {{match.home_name}} <img src="{{match.home_logo}}"> </div> <div class="score"> {{match.home_score}} : {{match.away_score}} </div> <div class="away"> <img src="{{match.away_logo}}"> {{match.away_name}} </div> </div> {% endfor %}