Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Subtract tags in Django
Im been wondering if it is possible to subtract two tags variable in Django something like this, thanks for the help {% for user_information in values.qs %} <td>{{user_information.amount|floatformat:2|intcomma}} - {{user_information.amount_paid|floatformat:2|intcomma}} </td> {% endfor %} -
How to add a unique code for every classroom in django
So, I am trying to build a simple elearning platform with django. What I want to achieve is that for every classroom that a teahcer creates, a unique 6 digit code is also generated, and when a student enters that code, he is admitted inside the classroom. I have a classroom model like this: class Classroom: name = models.CharField(max_length=20) code = models.IntegerField() def __str__(self): return self.title I really don't think an IntegerField would do the work here. Can anyone help me out? -
How do i filter specific set of data from mongo db using django
I need to fetch states list based on country id. The following code is working states_query = States.objects.all() states_result = StatesSerializer(states_query, many=True) but when i use states_query = States.objects.all().filter(country_id=id) states_result = StatesSerializer(states_query, many=True) it is not fetching the results. I am new to mongo db. Please help me with this. Thanks in advance -
Adding custom javascript audio recording filed to wagtail admin interface
I would like to add custom javascript audio recorder to the admin page in Wagtail. It have been suggested to customize the Time-Date widget which already uses Js. I've modified the original widget to the following code but it seems like it's more complicated than I thought. Demo of the recorder that I want to use is available at Mozilla's MediaRecorder-examples Here is the Js code and html for it. The code so far is: import json from django import forms from django.conf import settings from django.forms import widgets from django.utils.formats import get_format #from wagtail.admin.datetimepicker import to_datetimepicker_format from wagtail.admin.staticfiles import versioned_static # ~ DEFAULT_DATE_FORMAT = '%Y-%m-%d' # ~ DEFAULT_DATETIME_FORMAT = '%Y-%m-%d %H:%M' # ~ DEFAULT_TIME_FORMAT = '%H:%M' class AdminDateInput(widgets.DateInput): template_name = 'wagtailadmin/widgets/date_input.html' def __init__(self, attrs=None, format=None): default_attrs = {'autocomplete': 'off'} fmt = format if attrs: default_attrs.update(attrs) if fmt is None: fmt = getattr(settings, 'WAGTAIL_DATE_FORMAT', DEFAULT_DATE_FORMAT) self.js_format = to_datetimepicker_format(fmt) super().__init__(attrs=default_attrs, format=fmt) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) config = { 'dayOfWeekStart': get_format('FIRST_DAY_OF_WEEK'), 'format': self.js_format, } context['widget']['config_json'] = json.dumps(config) return context @property def media(self): return forms.Media(js=[ #versioned_static('wagtailadmin/js/date-time-chooser.js'), versioned_static("css/custom.js") ]) -
How to create a custom response for permission classes like IsAuthenticated in Django Rest Framework?
How can I create custom response for permission classes The response now is: {"detail": "Authentication credentials were not provided."} The response I want: { "status": 403, "message": "Authentication credentials were not provided", "response": {....} } -
Django rq-scheduler: jobs in scheduler doesnt get executed
In my Heroku application I succesfully implemented background tasks. For this purpose I created a Queue object at the top of my views.py file and called queue.enqueue() in the appropriate view. Now I'm trying to set a repeated job with rq-scheduler's scheduler.schedule() method. I know that it is not best way to do it but I call this method again at the top of my views.py file. Whatever I do, I couldn't get it to work, even if it's a simple HelloWorld function. views.py: from redis import Redis from rq import Queue from worker import conn from rq_scheduler import Scheduler scheduler = Scheduler(queue=q, connection=conn) print("SCHEDULER = ", scheduler) def say_hello(): print(" Hello world!") scheduler.schedule( scheduled_time=datetime.utcnow(), # Time for first execution, in UTC timezone func=say_hello, # Function to be queued interval=60, # Time before the function is called again, in seconds repeat=10, # Repeat this number of times (None means repeat forever) queue_name='default', ) worker.py: import os import redis from rq import Worker, Queue, Connection import django django.setup() listen = ['high', 'default', 'low'] redis_url = os.getenv('REDISTOGO_URL') if not redis_url: print("Set up Redis To Go first. Probably can't get env variable REDISTOGO_URL") raise RuntimeError("Set up Redis To Go first. Probably can't get … -
Django - Javascript error 404 how do i solve this?
I am working with Open Layers API page1:someone puts in list of cities they'd visit page2:the route is displayed using data from GeoJson This works well without Django but with Django i am getting error 404 data .geojson not found project structure maps form admin urls views manage(my python file) models apps maps admin urls settings static main.js styles.css libs(for openlayers) v6.4.3 ol.css ol.css.map ol.js ol.js.map data.GeoJson package.Json templates home.html (form) result.html (output) enter image description here -
AttributeError at /api/module/list/
I want many to many fields to be displayed in module serializer instead of id, these are my serializers class TrainerSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', ] class ModuleSerializer(serializers.ModelSerializer): trainer = serializers.CharField(source='trainer.username') class Meta: model = Module fields = ['id', 'title', 'duration', 'trainer', 'publish_choice'] and this is the error message Got AttributeError when attempting to get a value for field `trainer` on serializer `ModuleSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Module` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'username'. -
JSON fields serializer errors in Django rest framework
when I do input data then I want to check the data key is valid or not by Django rest API JSON serialize field. I have a JSON serializer in serializers.py like as class EmployBasicInfoSerializers(serializers.Serializer): basic_info = serializers.JSONField() designation = serializers.JSONField() academic_info = serializers.JSONField() address = serializers.JSONField() password = serializers.JSONField() and my views function is: def employ_create(request): if request.method == 'POST': json = JSONRenderer().render(request.data) stream = io.BytesIO(json) data = JSONParser().parse(stream) data_serializer = EmployBasicInfoSerializers(data=data) if data_serializer.is_valid(): pass return Response({'data_status':data_serializer.errors}, status=rest_framework.status.HTTP_400_BAD_REQUEST) Then I input JSON data like as: { "basic_info": { "name":"tushar", "gender":"male", "date_of_birth":"2020-08-22", "age":27, "phone_number":8667, "email":"mntushar25@gmail.com" }, "designation":{ "id": 2 }, "academic_info":[ { "degree":"hsc", "last_passing_institution_name":"hgygjhgy", "last_passing_year":"2020-08-22" }, { "degree":"hsc", "last_passing_institution_name":"hgygjhgy", "last_passing_year":"2020-08-22" } ], "address":{ "house_no":8787, "village_name":"kushtia", "post_office":"daulatpur", "thana_name":"daulatpur", "district_name":"kushtia" }, "password":"admin" } But I get errors form data_serializer validation. The errors are: { "data_status": { "name": [ "This field is required." ], "gender": [ "This field is required." ], "date_of_birth": [ "This field is required." ], "phone_number": [ "This field is required." ], "email": [ "This field is required." ] } } I can't understand why these errors occur. pls, help me to solve the errors..... -
Django Angular Lazy Loading and routing not working
I am using Django and angular 10. I am implementing lazy loading on angular side, this works fine when I run angular app independently. However, with Django same router fails to load. To integrate with Django and Angular, I am serving build file found in dist from Django using home url and corresponding html file code is added below Django URL patterns url(r'^home/$', home), url(r'^home/login', home), url(r'^home/moduleone/childurl', home), url(r'^home/moduletwo', home), Angular router const routes: Routes = [ { path: 'login', component: SignInComponent }, { path: 'moduleone', component: HomeComponent, children:[{path:'childurl',component: ChildComponent}]}, //normal router which maps to router home/moduleone/childurl on angular side { path: 'moduletwo', loadChildren: () => import('./moduletwo/moduletwo.module').then(m => m.moduletwo) }, //lazy module ]; So when I access url http://localhost:4200/home/moduleone/childurl --> works fine, because this is not lazy loaded module http://localhost:4200/home/moduletwo ---- does not works fine, because this is lazy module on angular side Home page Html file <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Home pag</title> <base href="/home"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <!--<link rel="stylesheet" href="node_modules/@forevolve/bootstrap-dark/dist/css/bootstrap-dark.css" />--> <link rel="stylesheet" href="static/dist/project/styles.css"></head> <body data-spy="scroll" data-target="#navbar" data-offset="72" class="position-relative"> <app-root></app-root> <script src="static/dist/project/polyfills.js" defer></script> <script src="static/dist/project/scripts.js" defer> </script><script src="static/dist/project/vendor.js" defer></script> <script src="static/dist/project/main.js" defer></script> <script src="static/dist/project/runtime.js" defer></script> <script src="static/dist/project/polyfills.js" defer></script> <script src="static/dist/project/scripts.js" defer></script> … -
CSRF cookie not set Django cross-site iframe in chrome
I'm trying to use an iframe of my django site in a different domain, however whenever I submit a form, It says the CSRF cookies is not set. This occurs in chrome and safari. I am running Django 3.1.0. I've tried adding the following settings in my settings.py: SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True X_FRAME_OPTIONS = 'ALLOWALL' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = None CSRF_COOKIE_HTTPONLY = False CSRF_TRUSTED_ORIGINS = [ 'otherdomain.com', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] Further, I can confirm the csrf token is being set in the form using: {% csrf_token %} Lastly, I've also added the @xframe_options_exempt decorator to the form page. Edit: I am also using the render method to display the form as recommended by the documentation. Edit2: For some more context, this form functions fine when it is used in the host domain (not an iframe) Unfortunately the csrf exempt decorator is not an option for me. I've tried clearing my cookies, though it does not solve my problem. Any help would be greatly appreciated! -
django.db.utils.ProgrammingError: relation "blog_category" does not exist
I started a Django project and I am not sure what I am missing. Prior to this error, I deleted the database, and deleted the migrations as well because I wanted the post to have an UUID. I got this error when I created my docker-compose-prod.yml file and all the django security stuff in the settings.py file(I am assuming all the security code I wrote in the settings.py file work because the warning signs do not show up): django.db.utils.ProgrammingError: relation "blog_category" does not exist As of right now, I am not sure what I am doing wrong? Also, I do not want to delete the migrations or make any changes within the database because I have the "post data" and I remember I ran into this issue a long time ago, but decided to ignore it(Meaning I went with the delete the migrations). More detail version of the error: web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site- packages/django/db/backends/utils.py", line 86, in _execute web_1 | return self.cursor.execute(sql, params) web_1 | psycopg2.errors.UndefinedTable: relation "blog_category" does not exist web_1 | LINE 1: ...log_category"."name", "blog_category"."name" FROM "blog_cate... ... web_1 | File "/code/datablog_project/urls.py", line 30, in … -
Whitenoise doesn't seem to help images to show up in heroku
this is my tree of directory directory1 | |-- manage.py | |-- build/ | | | |--static/ | . | . | |-- static/ . | . |--images/ . . . . The iamges that I want to see are in directory1/static/images/. setting INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', ... ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', .... ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') whitenoise vesrion is 5.2.0. I deployed this app to heroku. everything works fine except images. Do I miss something? Thank you in advance! :) -
Django REST Framework User Registration Privacy Issue: Looking for best practice to not show exception if user with given email exists already
I am suprised I have not found anything on the web regarding the following issue which I thought should be common? I may just have used the wrong search terms so I am happy to receive links with more info. My problem is that when using ACCOUNT_EMAIL_VERIFICATION = 'mandatory' I want to not give a clue to any user except the owner of an email address whether that mail is registered on my website, i. e. not show a "A user is already registered with this e-mail address." if an existing email is entered. My assumption is that that would require for the registration endpoint to return the same response independent of whether the email exists or not. I see several possible approaches, but none seems to be a good one: Use a custom exception handler to remove the exception in question from the error messages sent. That means I have to somehow identify the abovementioned exception among all error messages sent so I can still keep the others in the response. I guess I have to identify the exception message by a string the actual error message (possibly dependent on language settings?). If there are multiple error messages I … -
Connect to Django Admin over SSH using Apache and Port Forwarding
I would like to be able to restrict access to the Django admin for all requests, except for requests that come from inside the server, after connecting via SSH (which I have set as the default on my Ubuntu server) using port forwarding. I am using Ubuntu OS, and Apache server to serve my Django app with a React front-end here. I came across a wonderful description of how to do this with Nginx here. I also saw that it is possible to use <Location> blocks to restrict access to a URI. Can someone please assist here? -
Empty querydict request.data using Django Rest Framework
I am using Django REST Framework, and I use a post request but I have some troubles... I mean when I send this using the parameter Media Type : application/json : { 'name': 'List', 'comment': 'test', 'description': '', 'renders': [ 'application/json', 'text/html' ], 'parses': [ 'application/json', 'application/x-www-form-urlencoded', 'multipart/form-data' ] } It works very well. But when I send that : { 'name': 'List', 'comment': 'test', 'description': '', 'times': [{ 'start': '2020-11-10T14:00:00Z', 'end': '2020-11-10T20:00:00Z', }], 'renders': [ 'application/json', 'text/html' ], 'parses': [ 'application/json', 'application/x-www-form-urlencoded', 'multipart/form-data' ] } I got an empty querydict for the request.data. Could you help me please ? Thank you very much ! -
CSRF cookie not set Django cross-site iframe in chrome
I'm trying to use an iframe of my django site in a different domain, however whenever I submit a form, It says the CSRF cookies is not set. This occurs in chrome and safari. I am running Django 3.1.0. I've tried adding the following settings in my settings.py: SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True X_FRAME_OPTIONS = 'ALLOWALL' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = None CSRF_COOKIE_HTTPONLY = False CSRF_TRUSTED_ORIGINS = [ 'otherdomain.com', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] Further, I can confirm the csrf token is being set in the form using: {% csrf_token %} Lastly, I've also added the @xframe_options_exempt decorator to the form page. Unfortunately the csrf exempt decorator is not an option for me. I've tried clearing my cookies, though it does not solve my problem. Any help would be greatly appreciated! -
Django add User and Listing model to a Watchlist model
I'm trying to add a Listing model for an eCommerce app to a Wishlist model, but I'm not quite sure where I'm going wrong. I referenced this post in order to create a Wishlist model and link it to my User and Listing models via a Foreign key for each. Wishlist post urls.py from django.urls import path from . import views app_name = "auctions" urlpatterns = [ # Listing paths path("", views.index, name="index"), path("login/", views.login_view, name="login"), path("logout/", views.logout_view, name="logout"), path("register/", views.register, name="register"), path("addlisting/", views.add_listing, name="add_listing"), path("viewlisting/<int:listing_id>", views.view_listing, name="view_listing"), # Watchlist paths path("watchlist_add/<int:listing_id>", views.watchlist_add, name="watchlist_add"), ] models.py from django.contrib.auth.models import AbstractUser from django.db import models from datetime import datetime # Categories categories = [ ('misc', 'misc'), ('computers','computers'), ('toys','toys'), ('pets','pets'), ('beauty','beauty'), ('video games','video games'), ('food','food'), ('clothing','clothing'), ] ACTIVE_CHOICES = [ ('Yes', 'Yes'), ('No', 'No'), ] class User(AbstractUser): pass class Listing(models.Model): listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") listing_title = models.CharField(max_length=100) listing_description = models.TextField(max_length=1200) listing_img = models.URLField(null=True, blank=True, max_length=250) created_on = models.DateTimeField(auto_now=True) starting_price = models.DecimalField(decimal_places=2, max_digits=10, default=1.00) # From above categories list category = models.CharField(max_length=30, choices=categories, default='misc') # From active or inactive list active_flag = models.CharField(max_length=10, choices=ACTIVE_CHOICES, default="Yes", verbose_name="active listing") class Meta: ordering = ['-created_on'] def __str__(self): return f"Name: {self.listing_title}, Price: ${self.starting_price}, Posted By: {self.listing_owner}" … -
SynchronousOnlyOperation error when upgrading from python 3.6 to python 3.7 using django channels
I've been attempting to upgrade python from 3.6 to 3.7 for our Django & Django channels application. With that change, Django throws a SynchronousOnlyOperation anytime any HTTP request is made (even if it has nothing to do with websockets). My guess is that somehow the python upgrade has made the Django check more strict. I believe that django channels is serving both the HTTP requests and websocket requests so it expects all code to be async compliant. How do I get Django channels runserver to run the wsgi app synchronously, while the channel consumers asynchronously. # project/asgi.py application = ProtocolTypeRouter({"http": get_asgi_application(), "websocket": routing}) # project/wsgi.py application = get_wsgi_application() Stacktrace: It's clear to me that the auth middleware that is running for a normal wsgi view is not async compliant, how can I get it to run in a sync environment? ERROR Internal Server Error: /a/api Traceback (most recent call last): File "/___/___/.pyenv/versions/pd37/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 233, in _get_session return self._session_cache AttributeError: 'SessionStore' object has no attribute '_session_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/___/___/.pyenv/versions/pd37/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/___/___/___/___/apps/core/middleware.py", line 60, in __call__ request.is_user_verified = request.user.is_verified() File "/___/___/.pyenv/versions/pd37/lib/python3.7/site-packages/django/utils/functional.py", line … -
Django Multiple table to authentication
I'd like to have 3 differents table and use them to authenticate. Here is my "class diagram" (User Class is the default Django Class): Here is my models: class Contact(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) address = models.ForeignKey( Address, on_delete=models.CASCADE, blank=True, null=True ) email = models.CharField(blank=True, null=True, max_length=140) mobile = models.CharField(max_length=12, unique=True) password = models.CharField(max_length=128) optin_email = models.BooleanField(default=False) optin_sms = models.BooleanField(default=False) class ChainStore(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) password = models.CharField(max_length=64) last_login = models.DateTimeField(blank=True, null=True) rules = models.JSONField(default=dict) I've tried to use inheritance with AbstractBaseUser but i had problems like auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'Contact.groups' My Forms: class ContactSignUp(forms.Form): first_name = forms.CharField(max_length=10) last_name = forms.CharField(max_length=10) email = forms.EmailField() mobile = forms.RegexField(max_length=12) password = forms.CharField(max_length=32) password_verification = forms.CharField(max_length=32) class ContactAuth(forms.Form): mobile = forms.CharField(max_length=12) password = forms.CharField(max_length=32) My views: class ContactSignUpView(FormView): form_class = ContactSignUp model = Contact template_name = "sign_up.html" success_url = "/" def form_valid(self, form): """This method is called when valid form data has been POSTed.""" Contact( first_name=form.cleaned_data["first_name"], last_name=form.cleaned_data["last_name"], email=form.cleaned_data["email"], mobile=form.cleaned_data["mobile"], password=form.cleaned_data["password"] ).save() return super().form_valid(form) class ContactAuthView(FormView): form_class = forms.ContactAuth model = Contact template_name = "auth.html" success_url = "/" def form_valid(self, form): """This method is called when valid form data … -
Is there a way to list the column properties of my PostgreSQL tables?
I'm working in a Django project utilizing an old database from the project. The problem is: Migrating with Django don't give me a good fresh database, some fields that should be nullable are not, some are missing, and this breaks the site. The old database is missing some fields too. I need to compare the old database with the new one, but since there are almost 70 tables and lots of columns, I was hoping there is a way to let me visualize this in a easier way... Any ideas? -
How to Convert UTC Time To User's Local Time in Django
I undrestand that this question is repeated, but unfortunately I cannot find any answer. My impression is that Django already takes care of converting server time to local user as long as I have TIME_ZONE = 'UTC' USE_TZ = True in my settings. Even more if the db is postgresql that setting also doesn't matter and every thing will be still converted. however I tried all the followings: {% load tz %} {{ obj.date }} {{ obj.date|localtime }} {{ obj.date | timezone:"Canada/Mountain" }} and only last one works and the rest gives me UTC time. Last one also is not useful as the time would be only correct for users in that zone. I was wondering if I am missing anything here. I have a very simple test model: class TimeObject(models.Model): date = models.DateTimeField(auto_now=True) -
django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases
I'm creating multiple types of users with different permissions and hierarchy by extending AbstractBaseUser in django 3.1. All users are Employee, and there is an exploitation administrator type who is a kind of superuser, a Supervisor who has multiple Drivers under his control and there is a controller who is a independent User. But I get an errors about the models that I used. this is my models definition in models.py: from django.db import models from django.contrib.gis.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.gis.db import models as gis_models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import EmployeeManager class Employee(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=128, blank=False, null=False) last_name = models.CharField(max_length=128, blank=False, null=False) registration_number = models.PositiveSmallIntegerField(unique=True, blank=False, null=False) email = models.EmailField() cni = models.CharField(max_length=18, blank=True) picture = models.ImageField(upload_to='DriversPictures/', max_length=100, blank=True) matricule_cnss = models.PositiveIntegerField(blank=True) driving_licence = models.PositiveIntegerField(blank=True) recruitment_date = models.DateField(auto_now=False, auto_now_add=False, blank=True) phone = PhoneNumberField(blank=True, help_text='numéro de telephone') adress = models.CharField(max_length=128, blank=True) city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL) region_id = models.ForeignKey('Region', blank=True, null=True, on_delete=models.SET_NULL) # user = models.OneToOneField(User, on_delete=models.CASCADE) # roles = models.ManyToManyField('Role') is_exploitation_admin = models.BooleanField(default=False) is_supervisor = models.BooleanField(default=False) is_controlor = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) is_active = models.BooleanField(default=True) vehicle_id = models.ForeignKey('Vehicle', blank=True, null=True, on_delete=models.SET_NULL) USERNAME_FIELD = 'registration_number' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] objects … -
Django REST Framework - Migrate fails when splitting serializers
I'm trying to split the models, serializers and views of my app to get small, readable files. So, I moved from this: app/ recipes/ migrations/ models.py serializers.py views.py To this: app/ recipes/ migrations/ models/ __init__.py tag.py serializers/ __init__.py tag.py views/ __init__.py tag.py Somehow, everything was working fine until I restarted Docker. Then, I realised python manage.py migrate couldn't handle this split, and fails with this error: + python manage.py migrate Traceback (most recent call last): File "manage.py", line 27, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check databases=databases, File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 48, … -
Adjusting images in django
I am working on a django website, the code works pretty well but I'd like to make a few adjustments in order to make the web more professional. There's a section in the web called latest posts. Here's the code: <!-- Latest Posts --> <section class="latest-posts"> <div class="container"> <header> <h2>Latest from the blog</h2> <p class="text-big">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </header> <div class="row"> {% for obj in latest %} <div class="post col-md-4"> <div class="post-thumbnail"><a href="#"><img src="{{ obj.thumbnail.url }}" alt="..." class="img-fluid"></a></div> <div class="post-details"> <div class="post-meta d-flex justify-content-between"> <div class="date">{{ obj.date }}</div> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> </div><a href="#"> <h3 class="h4">{{ obj.title }}</h3></a> <p class="text-muted">{{ obj.overview }}</p> </div> </div> {% endfor %} </div> </div> </section> What you can see in the website is this: As you might have noticed, the images aren't adjusted and therefore, the text doesn't look aligned. Is there any code that can adjust this?