Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, when a function in views.py returns a JsonResponse, how can it render a web page at the same time?
I am trying to write a webpage in Django that obtains real-time input from the user and gives some responses back to the user. However, when the function in views.py returns a type of JsonResponse, my HTML file in the template cannot be showed properly. How can I fix this issue? My HTML: <!DOCTYPE html> <html> <head> <title>Real-time Input Text</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <input type="text" id="input-box"> <div id="output"></div> <script> $(document).ready(function() { $("#input-box").on("input", function() { var inputText = $(this).val(); // Get the current value of the input box $.ajax({ url: "/update_text/", method: "POST", data: { text: inputText }, success: function(response) { $("#output").text(response); } }); }); }); </script> </body> </html> My function in views: from django.shortcuts import render from django.http import JsonResponse def update_text(request): if request.method == "POST": text = request.POST.get("text", "") return JsonResponse(text, safe=False) else: return JsonResponse({}, status=400) -
How to do custom truncation of date in Django ORM?
I have two sql queries which which does some specific truncation on dates. I have posted the truncation portion below import datetime from datetime import timedelta time_diff_in_minutes = 60 * 24 start_time = datetime.datetime.utcnow() end_time = current_time - timedelta(minutes=time_diff_in_minutes) # 4 days interval (created_at, cost are columns in db) sql = "select date_trunc('month', created_at) + (date_part('day', created_at)::int - 1) / 4 * interval '4 day' AS custom_gran, avg(cost) from some_table where created_at between '{}' and '{}' group by zoom_gran order by zoom_gran;".format(start_time, end_time) # 4 hours interval (created_at, cost are columns in db) sql = "select date_trunc('day', created_at) + date_part('hour', created_at)::int / 4 * interval '4 hour' AS custom_gran, avg(cost) from some_table where created_at between '{}' and '{}' group by zoom_gran order by zoom_gran;".format(start_time, end_time) Now in django models I know basic truncation such as hours, days, months etc. So If I had to write a daily truncation or hourly truncation, this is how I would do it # daily truncation result = SomeTable.objects.filter(created_at__gte=start_time, created_at__lte=end_time) .annotate(daily=Trunc("created_at", "day")).values_list("daily") .annotate(avs=Avg("cost")) # hourly truncation result = SomeTable.objects.filter(created_at__gte=start_time, created_at__lte=end_time) .annotate(hourly=Trunc("created_at", "hour")).values_list("hourly") .annotate(avs=Avg("cost")) I found a Stack overflow question regarding this (Custom TruncFunc in Django ORM) but I didn't quite understand the solution (even the … -
Django ElasticSearch DSL How to sort by another document
In Django, I have 2 models Keyword and KeywordPopularity. class Keyword(models.Model): name = models.CharField(max_length=50) class KeywordPopularity(models.Model): keyword = models.ForeignKey(Keyword, on_delete=models.CASCADE, related_name='popularities') date = models.DateField(auto_now_add=True) popularity = models.IntegerField() I run a script to detect the popularity of each keyword once a month, so a keyword has multiple popularities (with different date of couse). I set up elasticsearch dsl to search keywords by query and it worked fine. @registry.register_document class KeywordDocument(Document): class Index: name = 'keywords' class Django: model = Keyword fields = ['name'] when I search for a query, i used this command and it works: KeywordDocument.search().query('match', name=query)[fromOffset:toOffset] My question is: how to search for a query then sort by popularity in a given date range. What I'm doing right now is to get all keywords that match the query then find each one popularity then sort. But it is very slow: keywords = KeywordDocument.search().extra(size=10000).query('match', name=query).to_queryset() result = [] for keyword in keywords: popularities = keyword.popularities.filter(date__gte=startDate, date__lte=endDate).order_by('date') data = KeywordSerializer(keyword).data data['popularity'] = popularities.last().popularity if popularities.count() > 0 else -1 result.append(data) result = sorted(result, key=lambda keyword: -keyword['popularity']) Could you please help me optimize the above snippet? Thank you very much! -
Docker Compose run, how to map ports defined in docker-compose.yml?
I am trying to run Django server inside a docker container, but the localhost:port is not working. I tried to achieve this by running the following commands: 1. docker compose -p dev run --entrypoint /usr/bin/fish shop-backend 2. docker compose --project-name dev run -p8000:8000 --entrypoint /usr/bin/fish shop-backend 3. docker-compose --project-name dev run --service-ports --entrypoint /usr/bin/fish shop-backend and once I am inside the docker container I start the Django server using this command: python3 src/manage.py runserver but I am not able to reach the localhost:8000. In shortcut my docker-compose.yml look like this: ... services: shop-backend: container_name: ${COMPOSE_PROJECT_NAME}-shop-backend build: context: . dockerfile: Dockerfile.${COMPOSE_PROJECT_NAME} volumes: - ./:/app/ stdin_open: true tty: true ports: - "8000:8000" # HOST:CONTAINER depends_on: - shop-db env_file: .env.${COMPOSE_PROJECT_NAME} ... Can you please provide some examples, of what I need to do to reach localhost:8000, if I want to run Django server from the docker container and get into the docker container I want to use the docker compose run command? -
When I try to use a dynamic URL from my 'articulos application in my template, I encounter a NoReverseMatch error at /
`The dynamic URLs work perfectly in the core app, but when I try to do exactly the same in the articulos app, I get an error, and I don't know what the cause is. This is the part of the template that is causing the error. <a href="{% url 'articulos:create-article' %}" class="btn btn-success mb-3">Crear un nuevo artículo</a> This is the URLs.py of the app: from django.urls import path from .views import * app_name = 'articulos' urlpatterns = [ path('create-article/', CrearArticuloView.as_view(), name='create-article'), path('list-articles/', ListaArticulos.as_view(), name='list-articles'), ] "This is my view:" from django.shortcuts import render from django.views import generic from .models import Articulo from .forms import CrearArticuloForm from django.urls import reverse # Create your views here. class CrearArticuloView(generic.CreateView): model = Articulo template_name = 'blog/create_article.html' form_class = CrearArticuloForm def get_success_url(self): return reverse('articulos:list-articles') def form_valid(self, form): f = form.save(commit=False) f.autor_id = self.request.user.id return super().form_valid(f) class ListaArticulos(generic.ListView): model = Articulo template_name = 'blog/articles.html' context_object_name = 'articulos' paginate_by = 25 And this is the error: NoReverseMatch at / Reverse for 'create-article' not found. 'create-article' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'create-article' not found. 'create-article' is not a … -
Match value with range value in column
I am having table with column registration year with values like '2017-2019' and '2014-2016. If my input value is 2018 then what will be my SQL query to get that record which is in between '2017-2019'. id registration_year 1 2014-2016 2 2017-2019 above is DB table and my input is 2018. Then it should return id 2. What will be my sql query. Thanks in advance -
Google allauth with django
when i do it in the local it work perfectly but when i host it's show this error : NoReverseMatch at /login Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name. Request Method: GET Request URL: Django Version: 4.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name. Note : in the local host it work and doesn't show this type of error i try to edit the domaine in google cloud but the same error -
DataTable -> Python ->Django -> Expanded Row / Colspan problem / Searching, etc. does not work
I have a problem because I am trying to make a datatable with a drop down when I click on a row and everything works. But then I lose the functionality of the datatable and can't search etc. I have already searched half the internet and can't figure it out, maybe there is someone who could help? Script: `$(document).ready(function () { // Ukryj wszystkie rozwinięte wiersze $(".expanded-row").hide(); // Po kliknięciu w wiersz, rozwinięty wiersz staje się widoczny, a reszta zostaje ukryta $(".expandable-row").click(function () { $(this).next(".expanded-row").toggle(); $(".expanded-row").not($(this).next(".expanded-row")).hide(); }); });` Table: ` <table style="width: 100%;" class="table table-hover table-striped table-bordered dataTable dtr-inline" id="clients_list"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> </tr> </thead> <tbody> {% for c in clients_list %} <tr class="expandable-row"> <td><a href="{% url 'client' c.id %}">{{ c }}</a></td> <td>{{ c.email }}</td> <td>{{ c.phone }} <i class="fa fa-fw" aria-hidden="true" title="Copy to use phone"></i> </td> </tr> <tr class="expanded-row"> <td colspan="10"> <div class="row"> <div class="col-md-6"> <div class="widget-chat-wrapper-outer"> <b> <div class="widget-title text-center opacity-10 text-uppercase"> Basic information </div> </b> <div tabindex="-1" class="dropdown-divider"></div> <div class="table-responsive-sm"> <table class="table table-nowrap mb-0 table-borderless" style="table-layout: auto; width: 100%"> <tbody> <tr> <th>Name & lastname:</th> <td>{{ c }} ({{ c.name }})</td> <th>Register date:</th> <td>{{ c.reg_time }}</td> </tr> </tbody> </table> </div> </div> </div> <div class="col-md-6"> <div class="card-body"><h5 … -
How can I change label to span tag using Django filters
I am using django_filters to filter objects. My site displays filter fields with the following code: <div class="inputBoxTEST"> <label for="id_name__icontains">Name contains:</label> <input type="text" name="name__icontains" id="id_name__icontains"> <label for="id_brand__icontains">Brand contains:</label> <input type="text" name="brand__icontains" id="id_brand__icontains"> <label for="id_cloth_type">Type:</label> <select name="cloth_type" class="form-control" id="id_cloth_type"> </div> django_filters generates inputs and labels. I need to change label tag with span tag. How can i do that? My code: views.py class WardrobeView(ListView): model = Clothes template_name = "wardrobe_TEST.html" context_object_name = "clothes" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["filter"] = ProductFilter( self.request.GET, queryset=self.get_queryset() ) return context 'filters.py` import django_filters from django import forms class ProductFilter(django_filters.FilterSet): cloth_type = django_filters.ModelChoiceFilter( queryset=ClothType.objects.all(), label='Type', widget=forms.Select(attrs={'class': 'form-control'}), ) class Meta: model = Clothes fields = { 'name': ['icontains'], 'brand': ['icontains'], } 'wardrobe.html' <div class="filter_form"> <form method="GET"> <div class="inputBoxTEST"> {{ filter.form }} </div> <button type="submit" style="--clr:#1644C9"><span>Submit</span><i></i></button> </form> </div> -
send jwt to Vue front end
I have a Django app and a vue app that work together. The Django part are a few pages including a log in page. Once logged in you are directed to the Vue app where I would like to log the user in automatically because he is already logged in on the Django side. I am sending an encrypted token to the Vue side and I encrypted the token using: encoded_token = jwt.encode({'token': token}, os.environ['SECRET_KEY'], algorithm='HS256') Now I want to use the token on the Vue side to log the user in and get his data. How do I do that because every library I have tried gives me an error: import VueJwtDecode from 'vue-jwt-decode'; Could not find a declaration file for module 'vue-jwt-decode'. '/mnt/500GB/website/frontend/node_modules/vue-jwt-decode/dist/lib/vue-jwt-decode.min.js' implicitly has an 'any' type. this also Could not find a declaration file for module 'jsonwebtoken'. Really new to this so would appreciate some help -
Python Manage.py runserver Failed
I have virtual environment of window 10 of company laptop. I am trying to execute python manage.py or python manage.py runserver Not getting error and it just shows output like this- enter image description here I expect the runserver start in my virtual environment. -
when running server, django always displays error
im only learnin python and django, i tried running server but only it shows error that says Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\theta\AppData\Local\Programs\Python\Python39\lib\site- packages\django\urls\resolvers.py", line 717, in url_patterns iter(patterns) TypeError: 'module' object is not iterable django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'app_advertisements' from ' C:\\Users\\theta\\PycharmProjects\\advertisements\\app_advertisements\\__init__.py' >' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app_advertisements')), ] and an app\urls.py from django.urls import path from .views import index urlpatterns = [ path('user/', index), ] -
I was trying to build an django project, it shows ```got an unexpected keyword argument 'chunked got an unexpected keyword argument 'chunked'```
The project when I previously build on my laptop it works but when I was trying to build this project on my pc it shows docker.errors.DockerException: Error while fetching server API version: HTTPConnection.request() got an unexpected keyword argument 'chunked'. My docker-compose.yml file looks like version: "3.3" services: db: image: postgres:14.0-alpine3.14 restart: always environment: POSTGRES_DB: ${DB_NAME} POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} volumes: - korean_mbc_appointment:/var/lib/postgresql/data web: build: ./ restart: always command: "python manage.py runserver 0.0.0.0:8000" volumes: - ./:/code expose: - 421 # ports: # - "420:8000" depends_on: - db nginx: build: ./nginx restart: always volumes: - ./static:/code/static - ./media:/code/media ports: - "420:80" depends_on: - web volumes: korean_mbc_appointment: The issue when I was trying to build the project looks like sudo docker-compose -f docker-compose.yml up -d --build Traceback (most recent call last): File "/usr/lib/python3/dist-packages/docker/api/client.py", line 214, in _retrieve_server_version return self.version(api_version=False)["ApiVersion"] File "/usr/lib/python3/dist-packages/docker/api/daemon.py", line 181, in version return self._result(self._get(url), json=True) File "/usr/lib/python3/dist-packages/docker/utils/decorators.py", line 46, in inner return f(self, *args, **kwargs) File "/usr/lib/python3/dist-packages/docker/api/client.py", line 237, in _get return self.get(url, **self._set_request_timeout(kwargs)) File "/usr/local/lib/python3.10/dist-packages/requests/sessions.py", line 602, in get return self.request("GET", url, **kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/sessions.py", line 589, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/sessions.py", line 703, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/adapters.py", line 486, in send … -
How to set interaction endpoint on discord
I'm trying to set a interaction endpoint and the verification isn't working. @csrf_exempt def discord_endpoint(request): return JsonResponse({'type':1}) I'm getting: Validation errors: interactions_endpoint_url: The specified interactions endpoint url could not be verified. and as a post response from discord in my django app: b'{"application_id":"...","entitlements":[],"id":"...","token":"...","type":1,"user":{"avatar":"...","avatar_decoration":null,"discriminator":"0","global_name":"...","id":"...","public_flags":0,"username":"nickname"},"version":1}' -
Django How to add new user_id row in django admin, by number or name in another table with same user_id, like works ForeignKey, but without in models
I have Model Users with User_id and Model Subcribes with User_id, but without ForeignKey, How can I add new rows in Subscribes with hints of Users number or name in table Users, like if it would with ForeignKey? Is it possibe, to connect 2 tables like this in django admin? -
Wagtail and Django
I'm experienced with Django and I've just started looking into wagtail integration in order to provide a better UX to the content management. Let's say I have an existing Django app and I would like to keep the same structure but this time the contents can be managed from the wagtail admin panel instead of the Django one. Is there a way to let's say created a parallel Model which mirrors the existing Django Model. So I add contents from wagtail admin and it will add those content to the same DB schema . I know you can created a 1 to 1 relation to the existing django model, that might be one way of approaching it I think. Not sure what the best way to do so ?? Also it seems like you will have to provide an html template for each Model correct ? When does it make sense to use it ? Do you actually save time instead of crating you own UI ? What are the alternatives there ? Thank you in advance -
Djoser reset password flow to javascript frontend (Vue)
I've got most of this reset password flow done using djoser in django. I get the email successfully. The last part where I redirect back to Vue.js frontend after the user follows the link in the email is the only thing I'm missing. For clarity I expect to be redirected to my Vue frontent url with uid and token present. From there I can finish this off. My django files are: backend/settings.py (look at DJOSER setup): """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.2.1. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path from django.urls import reverse # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent BASE_URL = 'http://127.0.0.1:8080' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-1z1=&mfysp%pklgh@x+^_j3+p5)x+zm@va36wc9eq0z=7r3u7z' STRIPE_SECRET_KEY = 'sk_test_51NH4LnIIOIhiNEiGlcpsukLE5pi6Me9zYOhTf1uVP4ux7WgCXyR5QG9b6Yzfgm6qB4Agl8ZcQwZ7RN2rKIex04nk00kF97Aeok' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ 'http://127.0.0.1:8080', ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:8080', ] CSRF_COOKIE_HTTPONLY = False # SESSION_COOKIE_SAMESITE = 'None' # … -
Migrating wagtail snippet model into page model
I'm wanting to convert an existing snippet model into a page model, along with migrating all existing data from the snippet model. Is there a way to do this without having to manually convert the data/ create a script to generate pages from the existing models? I've updated the model, ran the migrations etc. and can create new pages for this type in the wagtail UI, but the existing data hasn't been migrated over and there's no new page models for it. References/links to the old snippet models are still intact, but there's nowhere to view/edit the model as it no longer appears as a snippet and hasn't been migrated over to a page. -
Django Flowbite dropdown doesn't work when I'm looping it in template for loop
Fowbite dropdown works when I write it out of for loop, but when I'm moving it into the for loop it stops working. And reason is not html id. I wrote 3 dropdowns out of for loop with same id and it worked. {% for comment in comments %} <div> <button id="dropdown-comments-{{ comment.id }}" data-dropdown-toggle="comment-options-{{ comment.id }}" class="text-primary-900"> <i class="w-6 h-6 fa-solid fa-ellipsis-vertical hidden sm:block"></i> <i class="w-6 h-6 fa-solid fa-ellipsis sm:hidden"></i> </button> </div> <div id="comment-options-{{ comment.id }}" class="z-10 hidden bg-white divide-y divide-primary-100 rounded-lg shadow w-44 dark:bg-primary-700"> <ul class="py-2 text-sm text-primary-700 dark:text-primary-200" aria-labelledby="comment-options-button"> <li> <a href="" class="block px-4 py-2 hover:bg-primary-100 dark:hover:bg-primary-600 dark:hover:text-white"> <i class="fa-solid fa-pen mr-3"></i> {% trans "Edit" %} </a> </li> <li> <button data-modal-toggle="delete-confirm-{{ comment.id }}" class="block text-start text-red-600 w-full px-4 py-2 hover:bg-primary-100 dark:hover:bg-primary-600 dark:hover:text-white"> <i class="fa-solid fa-trash mr-3"></i> {% trans "Delete" %} </button> </li> </ul> </div> {% endfor %} -
Prevent Prettier from breaking Python code
I am writing some conditions in my django html file and upon every save, vs code Prettier rearranges my code but it's doing it the wrong way hence creating errors. Here's an example of what it is doing. {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="error-message">{{ message }}</div> {% elif message.tags == 'success' %} <div class="success-message">{{ message }}</div> {% else %} <div class="text-center mb-3">{{ message }}</div> {% endif %} {% endfor %} {% endif %} I tried modifying the settings.json with the following "git.confirmSync": false, "editor.formatOnPaste": true, "python.formatting.provider": "autopep8", "explorer.confirmDelete": false, "python.showStartPage": false, "explorer.confirmDragAndDrop": false, "python.linting.pylintArgs": ["--load-plugins=pylint_django"], "[python]": { "editor.defaultFormatter": "ms-python.python" } But it's still doing the same thing -
How to style the CSS bootstrap 'col' elements?
I'm trying to style bootstrap CSS columns col-xl so that I'll be able to have 5 or 6 cards/tiles on my page instead of 4 (page image attached) without touching the other grid layouts. However at this point I've no idea on how to achieve that. Below is my code: {% extends 'base.html' %} {% load static %} {% block content %} <h2>My Meals</h2> <div class='py-4 mt-auto'> <div class='container px-4'> <div class="row meal-tiles"> {% for meal in meals %} <div class="col-sm-12 col-md-12 col-lg-4 col-xl-3 d-flex align-items-stretch meal-tile"> <div class="card mb-3 meal-tile-border"> {% if meal.image %} <img src="{{ meal.image.url }}" alt="{{ meal.name }}" class="img-fluid" style="height: 200px;"> {% else %} <img src="{% static 'images/mealdefault.png' %}" alt="Default Image" class="img-fluid" style="height: 200px;"> {% endif %} <div class="card-body"> <h4 class='card-title'> <strong>{{ meal.name }}</strong></h4> {% with macros=meal.calculate_total_macros %} <p>Kcal in 100g: {{ macros.total_kcal_per_100g }}</p> <p>Carbohydrates in 100g: {{ macros.total_carbohydrates_per_100g }}</p> <p>Fats in 100g: {{ macros.total_fats_per_100g }}</p> <p>Proteins in 100g: {{ macros.total_proteins_per_100g }}</p> <p>Glycemic Load in 100g: {{ macros.total_glycemic_load_per_100g }}</p> <p>Glycemic Index: {{ macros.average_glycemic_index }}</p> {% endwith %} </div> </div> </div> {% empty %} <div class="col-12"> <p>No meals found.</p> </div> {% endfor %} </div> </div> </div> {% endblock %} I've tried styling the css for the .col-xl … -
No 'Access-Control-Allow-Origin' header is present on the requested resource React Django issue
I used django-cors-headers for managing CORS in my Django app. INSTALLED_APPS = [ ..., 'core', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] CORS_ALLOW_HEADERS = ("x-requested-with", "content-type", "accept", "origin", "authorization", "x-csrftoken") And my React look likes the following: React.useEffect(() => { // Make an API call to the backend axios.get('http://127.0.0.1:8000/core') .then((response) => { const namesArray = response.data.map(item => item.title); setNames(namesArray); }) .catch((error) => { console.log(error); }); }; I also include the following in package.json in my react app. "proxy": "http://localhost:8000/core", It's still throwing error Access to XMLHttpRequest at 'http://127.0.0.1:8000/core' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Please help, thank you!! -
my django project was displaying images but doesnt display images anymore after i deployed it to render
my Django project was working fine but after me deploying it using the render server the images do not display anymore like the logo what could be the cause and how can I solve it I tried using AWS S3 buckets but that failed and other than that failed its too complex I guess but is their some sort of easier way of doing this -
Django migrate error on first migration due to forms Meta class using User
I am getting the auth_user does not exist error on manage.py migrate when I try to migrate my app for the first time. This is due to the following part in one of my forms: class MyForm(ModelForm): def __init__(self, *args, **kwargs): ***dothings and super init*** def clean(self): ***dothings**** # This is where it goes wrong: class Meta: owner_choices_base = User.objects.values_list('username', flat=True) owner_choices = [(c, c,) for c in owner_choices_base] owner_choices.insert(0, (None, None,)) model = SomeModel widgets = { 'owner': forms.Select(choices=owner_choices), 'concerned_business_lines': forms.SelectMultiple() } It seems this executes before any of the migrations are done and it will see that User related things actually don't exist yet. It works nicely when I delete the Meta part and after that recreate it. Now I would like to have an app that works without having to comment out code for the first time you create it, but I have no idea how to get around this issue while still being able to populate my "special" owner field with users and I hope someone here will have an idea. For more information on why the Meta class is there: The owner field in the form is just a charfield, but I want to make … -
How can I automatically delete a field value in my Django model?
I want to delete the value of my model in Django which automatically: verify_code = models.IntegerField(blank=True, null=True) verification_timestamp = models.DateTimeField(blank=True, null=True) def save(self, *args, **kwargs): if self.verify_code is not None: self.verification_timestamp = timezone.now() super().save(*args, **kwargs) here I save the time in verification_timestamp if verify_code is not set to None, then I want to delete the value of verify_code after 1 min (for example save the value to None after 1 min), now what should I do?