Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
react native - django api jwt - HTTP Fetch fails with "TypeError: Network request failed"
im trying to connect my react native app to django. i am using JWT. im trying to send a post method to my api but I get "TypeError: Network request failed" => Resolved every time i press the sign in button. i am using a real android device. im new to react so it is been very hard to solve this problem! can anybody help me pls? i already try all methods above but none seem to work enter image description here enter image description here.stack.imgur.com/70KY9.png -
Django: Field 'id' expected a number but got <Video: Introduction>
i am trying to get the id of a Video, but it keeps showing this error Field 'id' expected a number but got <Video: Introduction>. How do i get to add the number that is expected and not the string. views.py def mark_lesson_done(request, course_slug, video_id): user = request.user profile = Profile.objects.get(user=user) course = Course.objects.get(slug=course_slug) video = Video.objects.get(id=video_id) complete_lesson = False if not profile.completed_lessons.get(id=video).id().exists(): profile.completed_lessons.add(videos) messages(request, f'Lesson Completed!') complete_lesson = True return HttpResponseRedirect(reverse('course:course-content', args=[course_slug])) -
Django - How set headers for external resources?
At my Django application, I want to display an image from an external web server. This web server only returns the image if an Authorization token (JWT) is set in the request header. At my Django template, I do: <img src="{{ blabla.cover_url }}"> Where cover_url is a model function, which looks like this at the moment: def cover_url(self, *args, **kwargs): jwt_payload = jwt_payload_handler(get_request().user) access_token = str("Bearer " + jwt_encode_handler(jwt_payload)) cover_url = "https://cdn.mydomain.com/Images/123456789.jpg" My question now is how I return the cover_url with the Authorization header set? -
Login Failed Error Message Django Based Views
I have a project made in django based view. I need to show an error message when the user enters the wrong password, but in every forum I've seen so far there is a suggestion to use a 'Form'. There is no way to show error message with the project done this way? view.py: def login(request): if request.method == "GET": return render(request, 'users/login.html') else: Email = request.POST.get('Email') Senha = request.POST.get('Senha') user = authenticate(username=Email, password=Senha) if user: loginDjango(request, user) return render(request, 'convite/cadastro_convite.html') else: return redirect('login') html: <div class="col-sm-12 col-md-7 login-dir"> <h2 class="login-titulo">Faça seu login!</h2> <form class="login-form" action="{% url 'login'%}" method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" id="log-email" aria-describedby="emailHelp" name="Email" placeholder="Email"> </div> <div class="form-group"> <input type="password" class="form-control" id="log-senha" name="Senha" placeholder="Senha"> </div> <button href="/Exemplo" type="submit" class="btn btn-primary login-btn_dir"><i class="fa-solid fa-right-to-bracket"></i> Acessar</button> </form> </div> model: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): NomeUsuario = models.TextField(blank=True) Endereco = models.TextField(blank=True) Celular = models.TextField(blank=True) Cidade = models.TextField(blank=True) Estado = models.TextField(blank=True) Cep = models.TextField(blank=True) Bairro = models.TextField(blank=True) -
suggestion AWS vs Heroku
hello I am having an app with django I deployed to heroku, I am using RDS, and now I am thinking which one is better for me heroku or AWS. my questions also, the app is running slow since I am using redis and everything in heroku for free, how can I make my django app fast. -
E1101: Module 'ldap' has no 'OPT_DEBUG_LEVEL' member (no-member)
I have the following code in my settings.py of my Django application: AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 0, ldap.OPT_REFERRALS: 0, } When I run pylint, I get: E1101: Module 'ldap' has no 'OPT_DEBUG_LEVEL' member (no-member) E1101: Module 'ldap' has no 'OPT_REFERRALS' member (no-member) Why is that? I see in multiple places online those those two flags exist. So why? Also tried: > print("OPT_REFERRALS" in dir(ldap)) True So why do I get this warning? -
Password reset using graphene-django?
In our on going project we are migrating all our views from django to react using graphene. Originally, we used the built in django authentication system for user registration, login and password reset. To migrate the login view, we used authenticate and login from django.contrib.auth which worked great. But now we are stuck on the password reset view. We cannot find a way to send the password reset email. Are there any built in functions like the ones mentioned before that we could use? I checked the following project https://github.com/PedroBern/django-graphql-auth, but it seems abandoned, so I would like to avoid it. -
Losing data in db.sqlite3 when deploying django project to heroku
Whenever I make updates to my website I lose all data that has been added to my models. For example my models include users and service_calls and when I push a deploy it overwrites my db.sqlite3 file and I'm back to just my superuser being the only user and 0 service calls in my database. How can I push an update without having my db.sqlite3 file overwritten? Is that possible or do I need to have my local db.sqlite3 file updated before deploying and if so how would I go about that. Thanks in advance -
Django - How to process authorization headers?
At my Django application, I display pictures which are stored on an external web server. To make the picture accessible, the client needs to call the resource with an attached authorization Barer token in the request header, like this: Authorization: Bearer eyJ0eXAiO... To get the actual URL to the picture, I have a function in my models.py which I can simply call at my template.html: def cover_url(self): cover_url = self.libera_backend.endpoint + '/' + self.libera_backend.assets_bucket + '/' + self.cover_path return cover_url As I have to generate a JWT token to make the resource accessible, I have to do something like this: jwt_payload = jwt_payload_handler(user) access_token = str("Bearer " + jwt_encode_handler(jwt_payload)) Where I'm not sure how to implement this. Does it have to be part of a template tag, or is there any way to find out what user calls def cover_url? If so, how can I add the Authorization header here? -
Dynamic SECRET_KEY in Django disadvantages
I just started learning Django and I'm wondering what the drawbacks of using a randomly generated SECRET-KEY would be. So far I've started with using this code... from pathlib import Path import random, string Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(file).resolve().parent.parent Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ Randomized security key size = 100 SECRET_KEY = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase string.punctuation + string.hexdigits + string.digits, k = size)) For now, this seems to work well for a simple blog that I made but I'm wondering what drawbacks this might have in other uses and if there are better ways of making the key secure. Thanks in advance! -
python django whatsapp bot to let others to signup to DBs without using html
Creating a Django project django-admin startproject messages . django-admin startapp whatsapp python manage.py migrate python manage.py runserver Open the settings.py file from the messages directory INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whatsapp.apps.WhatsappConfig', # ← new item ] Open the views.py from the whatsapp subdirectory. from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def message(self): return HttpResponse('Hello!') To make this endpoint accessible through the web application, a URL needs to be assigned to it. Open the urls.py file from the messages directory and add a new entry to the urlpatterns list as shown below: from django.contrib import admin from django.urls import path from whatsapp import views # ← new import urlpatterns = [ path('admin/', admin.site.urls), path('message', views.message), # ← new item ] Receiving WhatsApp messages The next step is to update the logic inside the message() endpoint to extract the information about the incoming message. Replace the contents of the views.py file in the whatsapp subdirectory with the following: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def message(request): user = request.POST.get('From') message = request.POST.get('Body') print(f'{user} says {message}') return HttpResponse('Hello!') Sending a response Update the views.py file in the whatsapp subdirectory one last time with the … -
ERROR "grpc_status": 14. from client when trying to make request to server inside Docker
i use django grpc framework for the server and fastapi for the client. It all work well in local by starting it one by one. But when i try to use Docker somehow (i think) the client can't establish a connection. Here is the code for the client: from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import grpc from blog_proto import post_pb2, post_pb2_grpc channel = grpc.insecure_channel('grpc_service:5000') stub = post_pb2_grpc.PostControllerStub(channel) class Delivery(BaseModel): id: int title: str content: str app = FastAPI() origins = [ "http://localhost", "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.on_event("startup") async def init_grpc(): channel = grpc.insecure_channel('grpc_service:5000') stub = post_pb2_grpc.PostControllerStub(channel) @app.post("/delivery/") async def create_item(delivery: Delivery): return delivery @app.get("/delivery/{id}") async def get_item(id: int): response = stub.Retrieve(post_pb2.PostRetrieveRequest(id=id)) return { "id": response.id, "title": response.title, "content": response.content } code for docker-compose: --- version: '3.9' services: db: image: postgres ports: - "8888:5432" environment: POSTGRES_DB: grpc POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - postgres:/var/lib/postgresql/data pgadmin: image: dpage/pgadmin4:latest environment: PGADMIN_DEFAULT_EMAIL: lawteam@gmail.com PGADMIN_DEFAULT_PASSWORD: lawteam PGADMIN_LISTEN_PORT: 80 ports: - 15432:80 volumes: - pgadmin:/var/lib/pgadmin depends_on: - db grpc_service: container_name: grpc_service build: context: ./tutorial dockerfile: Dockerfile command: > bash -c "python /code/manage.py makemigrations && python /code/manage.py migrate && python /code/manage.py grpcrunserver 0.0.0.0:5000" # volumes: # … -
Django: how to make simple calculation using django python?
i am building a LMS using django and i want students to keep track of thier progress while learning, in that case i want users to mark a lesson as done. Now, the problem is how to calculate the total lesson, despite the number of lessons, them get a result of 100%, even if the lesson count is 4 or even 10, i just want to arrive at 100% when the whole lesson is marked as complete i have tried this views.py def trackProgress(request): progress = 100 - round(((total_unanswered_questions - 1) / total_questions) * 100) where i would display the progress <div role="progressbar" data-aos="slide-right" data-aos-delay="200" data-aos-duration="1000" data-aos-easing="ease-in-out" style="width: 15%" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"> this is the model for the lesssons class Video(models.Model): title = models.CharField(max_length = 100 , null = False) course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="videos") serial_number = models.IntegerField(null=False) hour = models.IntegerField(null=True, help_text="Enter course hours e.g: 3h") minutes = models.IntegerField(null=True, help_text="Enter course minutes e.g: 23m") video_id = models.CharField(max_length = 100 , null = False) is_preview = models.BooleanField(default = False) NOTE: i also have a model Course where the Video Model is a foreignKey to I also have this model that stores the courses a user have … -
How to count download hit in Django admin
I am newbie for Django admin. I have made little site where I am giving option to user to upload some mp3 files.for that I am using Django file upload. I have html page for showing all those files where I have option to download it by clicking on download symbol. I want to count on every download. I have added filed in my table to keep it's record. My html file where I want to count hit. <th scope="row" style="vertical-align: middle;"> <a href="{{radio_file.audio_file.url}}" download > <i class="fas fa-download mr-2 text-danger"></i></a>&nbsp; </th> <td>{{ radio_file.download_count }} </td> models.py class RadioFile(models.Model): audio_file = models.FileField( upload_to='radio/', validators=[validate_file_extension], max_length=255, help_text="Only wav,mp1,mp2,mp3,m4p,.m5p,wma and voc files are allowed.", ) category = models.ForeignKey( Category, related_name='radio_files', on_delete=models.SET_NULL, null=True, ) trending = models.BooleanField( default=False, help_text="Tick if you want to show it on Home Page",verbose_name="Feature" ) download_count = models.PositiveIntegerField(default=0, blank=False,null=False) uploaded_by = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='radio_files', on_delete=models.CASCADE, ) uploaded_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Django base template didn't work when delete one 'include'
When i delete one of includes (Marked in code) my application didn't work properly. I have side bar and when i delete my nav bar, side bar stops scrolling. I have this code (base template) why this happens? When i don't touch 'include' all is good and working but when i delete som of includes imidiatelly something brokes :( <!DOCTYPE html> <html lang="en"> <head> <title> <!-- title bla bla bla --> </title> <!-- meta and links bla bla bla --> </head> <body class=""> <!-- [ Pre-loader ] start --> <div class="loader-bg"> <div class="loader-track"> <div class="loader-fill"></div> </div> </div> <!-- [ Pre-loader ] End --> {% include 'includes/sidebar.html' %} {% include 'includes/navigation.html' %} <!-- DELETE THIS LINE --> {% include 'includes/header-user-list.html' %} {% include 'includes/header-chat.html' %} {% block content %}{% endblock content %} {% include 'includes/scripts.html' %} <!-- Specific Page JS goes HERE --> {% block javascripts %}{% endblock javascripts %} <script src="{{ ASSETS_ROOT }}/js/menu-setting.js"></script> </body> </html> -
AJAX only picks first element id in a DJANGO loop
AJAX only picks first element id in a DJANGO loop. Wherever I click the "edit" button it brings the first post content. I've just similar metholodogy in other functions (for example a like button) but in this one I don't really see what it only picks the top element of the loop in every template. Please help. This is what I came up with so far: //Edit $('.editfunction').click(function(){ event.preventDefault() var post_pk; var content = $('.textarea_edit').val(); post_pk = $(this).data("post_pk"); $.ajax({ type: "POST", url: `/post/${post_pk}/edit`, data: { csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, post_id: post_pk, textarea: content }, success: function(data) { $('.modal-edit').modal('hide') var content = $('.textarea_edit').val() $(`.post-object-content${post_pk}`).html(content) } }) }) -
When is necessary to create a new app (with startapp) in Django?
Ive found this question, but the answer was from 2008, and I couldnt find any current answer, so I wanted to know if there is a good place to find current information about it, or if you have any advice about it I would be very grateful. -
Why IntegrityError, UNIQUE constraint failed when updating django model?
I'm using Django 4.0.5 and I'm trying to save a youtube video model and then download its thumbnail. When I update the model with the thumbnail it gives me IntegrityError but I can't understand why. models.py class YoutubeVideo(models.Model): title = models.CharField(max_length=255) description = models.TextField() json_info = models.TextField(default='{}') slug = models.SlugField() thumbnail_url = models.CharField(max_length=255) video_url = models.CharField(max_length=255) thumbnail = models.ImageField(upload_to=get_path_yt, null=True, blank=True) video = models.FileField(upload_to=get_path_yt, null=True, blank=True) added_at = models.DateTimeField(auto_now=True) added_from = models.ForeignKey(User, on_delete=models.CASCADE) def download_thumbnail(self) -> None: request = requests.get(self.thumbnail_url, stream=True) if request.status_code != 200: raise ValueError('Invalid thumbnail url') img_temp = NamedTemporaryFile() img_temp.write(request.content) img_temp.flush() file_name = self.thumbnail_url.split('/')[-1] self.thumbnail.save(file_name, File(img_temp.file)) img_temp.close() @staticmethod def create_from_url(url: str, request: Any) -> Any: youtube_video = YoutubeVideo(**get_video_info(url)) youtube_video.added_from = request.user youtube_video.save() youtube_video.download_thumbnail() return youtube_video Error UNIQUE constraint failed: youtube_archive_youtubevideo.id If I save the model only once after downloading the thumbnail it works but I need to do it at two different times. -
SUBMIT button for Django Modal Forms not working, no url to direct to
So, I am trying to add data into a db with the usage of a modal, for this, I am using django-bootstrap-modal-forms. I followed the steps on the manual, step by step and I finally made it work. Well, everything except the buttons on the modal. First, to dismiss data, it had to be data-ds-dismiss instead of the data-dismiss appearing on the code, but that's fine. The only thing that I cannot get to work is the CREATE button, to add data to the database. Here is my code (which is pretty much what appears on the site previously mentioned): #contform.html <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Create new contract</h5> <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field }} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Create</button> </div> </form> What appears on my console is django.core.exceptions.ImproperlyConfigured: No url to direct to and yes, it makes sense bc Im not adding any … -
Django CRUD functionality after changed model
I was building the CRUD-functionality with create_project_old, update_project, update_project. Then I slightly switched my models.py and create_project_new view but I unfortenatly do not really know how I have to change my update_project and delete_project views now. I have also posted my new models.py and forms.py. Thanks! views.py def create_project_new(request): form = ProjectForm() form2 = ProjectImageForm() if request.method == 'POST': form = ProjectForm(request.POST) form2 = ProjectImageForm(request.POST, request.FILES) images = request.FILES.getlist('image') if form.is_valid() and form2.is_valid(): title = form.cleaned_data['title'] describ = form.cleaned_data['describtion'] price = form.cleaned_data['price'] project_instance = Project.objects.create( title=title, describtion=describ, price=price) print(project_instance) for i in images: ProjectImage.objects.create(project=project_instance, image=i) return redirect('projects') context = {'form': form, 'form2': form2} return render(request, 'projects/project_form.html', context) def create_project_old(request): profile = request.user.profile form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST, request.FILES) if form.is_valid(): project = form.save(commit=False) project.owner = profile project.save() return redirect('account') context = {'form':form} return render(request, 'projects/project_form.html', context) @login_required(login_url='login') def update_project(request, pk): profile = request.user.profile project = profile.project_set.get(id=pk) form = ProjectForm(instance=project) if request.method == 'POST': form = ProjectForm(request.POST, request.FILES, instance=project) if form.is_valid(): form.save() return redirect('projects') context = {'form':form} return render(request, 'projects/project_form.html', context) @login_required(login_url='login') def deleteProject(request, pk): profile = request.user.profile project = profile.project_set.get(id=pk) if request.method == "POST": project.delete() return redirect('account') context = {'object':project} return render(request, 'delete_template.html', context) models.py … -
Avoid duplication in Django for loop with a many to many relationship
My goal is to list the tag_titles for each note created. I am having issues because the tag_title and note are linked through a Many to Many relationship. How I would normally do this is: {% for note_tag in note_tags %} {% if note_tag.note == note %} {{note_tag.tag_title}} {% endif %} {% endfor %} However, because tag_title has a many to many relationship with NoteModel, note_tag.note gives out notes.NoteModel.None My models.py are as follows: class NoteModel(models.Model): note = models.CharField( max_length = 5000, ) note_title = models.CharField( max_length = 500, blank = False, null = True, ) project = models.ForeignKey( IndividualProject, on_delete=models.CASCADE, related_name = "note_projects", blank = False, null = True, ) tag = models.ManyToManyField( 'NoteTagModel', related_name="tags", blank= False, through = "TaggedModel" ) def __str__(self): return f"{self.note_title}" class NoteTagModel(models.Model): note = models.ManyToManyField( 'NoteModel', related_name="tag_notes", blank= False, through = "TaggedModel" ) tag_title = models.CharField( max_length = 200, default = "General", ) def __str__(self): return f"{self.tag_title}" class TaggedModel(models.Model): note = models.ForeignKey(NoteModel, on_delete = models.CASCADE) tag = models.ForeignKey(NoteTagModel, on_delete = models.CASCADE) def __str__(self): return f"{self.note} | {self.tag}" class TagCommentaryModel(models.Model): tag_title = models.ForeignKey( NoteTagModel, on_delete=models.CASCADE, related_name="tag", blank = False, null = True, ) tag_commentary = models.CharField( max_length = 5000 ) def __str__(self): return f"Tag: {self.tag_title} … -
Querying a Django model and comparing its fields for similarities or near duplicates
I have a model that records changes to other models in my database. I would like to query for changes that only add a newline character -- \n. My changes model looks like this: class Change(models.Model): object_type = models.ForeignKey( ContentType, related_name="object_change_set", on_delete=models.CASCADE, ) object_id = models.CharField(max_length=255, db_index=True) object = GenericForeignKey("object_type", "object_id") old_fields = models.JSONField(encoder=JSONEncoder, null=True, blank=True) new_fields = models.JSONField(encoder=JSONEncoder, null=True, blank=True) Essentially, I want to find instances of Change where the difference between a value for a key in old_fields and new_fields is \n. Here's what new_fields look like: { "body": "Had a great time on Wednesday.", "created": "2022-06-15T19:49:06.784Z", } And similarly, old_fields: { "body": "Had a great time on Wednesday.\n", "created": "2022-06-15T19:49:06.784Z", } Note that new_fields and old_fields are both JSONFields. Ultimately, I want to remove the Change instances that only add \n to the body. I realize that I could do this by iterating over the queryset and looking for these discrepancies, but I'm wondering if there's a more elegant solution. -
While, not looping in Python
I'm trying to make a rock paper scissors game with rounds. I'm using a while loop but it doesn't go back to the beginning. I've tried declaring the variables inside of the while, outside, and many other things, but it just doesn't work. I'll leave the code here. Thanks for the help! import random computer_win = 0 user_win = 0 jugadas = 0 def play(computer_win, user_win, jugadas): while (jugadas < 3): user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: ") computer = random.choice(['r','p','s']) if user == computer: jugadas = jugadas + 1 return( f'It\'s a tie. Round {jugadas}/3') if is_win(user, computer): user_win +=1 jugadas = jugadas + 1 return( f'You won! Round {jugadas}/3') else: computer_win +=1 jugadas = jugadas + 1 return( f'You lost! Round {jugadas}/3') if computer_win >2 or user_win>2: if computer_win > user_win: "The computer won" elif user_win > computer_win: return "You won!" else: return "It's a tie ...." def is_win(player, opponent): if(player == 'r' and opponent == 's') or (player =='s' and opponent =='p') \ or (player =='p' and opponent == 'r'): return True print(play(computer_win, user_win, jugadas)) -
TypeError: get() takes 1 positional argument but 2 were given
I am building and Inventory Web App and I am facing this error. I am trying to get Username from token to show a custom hello message and show that the user is logged in as someone. Here is my Views.py that gets Token from localStorage as logged in user: class UserDetails(APIView): def post(self, request): serializer = UserAccountTokenSendSerializer(data=request.data) global token if serializer.is_valid(): token = serializer.validated_data['token'] return Response(serializer.data) def get(self): user_id = Token.objects.get(key=token).user_id details = User.objects.get(id=user_id) serializer = UserDetails(details, many=False) return Response(serializer.data) class UserDetails(serializers.ModelSerializer): class Meta: model = User fields = ( 'username', ) Here is my Urls.py: urlpatterns = [ path('get-user-token/', views.UserDetails.as_view()), path('get-user-details/', views.UserDetails.as_view()), ] And this is the error that I get: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) TypeError: get() takes 1 positional argument but 2 were given [15/Jun/2022 19:34:59] "GET /api/v1/get-user-details/ HTTP/1.1" 500 82239 -
Is there a way to set a Django model IntegerField default to the ID of the newly created record?
Lets say we have the following model: class MyModel(models.Model): some_int = models.IntegerField() I would like the value of MyModel.some_int to default to the value of MyModel.id. For example, immediately after creating a new record in an empty version of MyModel, I could call MyModel.objects.get(id=1) and receive an object with id=1 and some_int=1. Is there a way to do this? Edit: My current workaround is to set the default to 0, then go back and populate the value with the id of the created record, but that is messy. For context: On an existing model similar to MyModel, I am being asked to add a new column that will render using the MyModel index obsolete as the reference point for the records in that model. Instead, I am adding a new, secondary column, that should store the values of the old IDs for previous records, and new values for future records. To do that though, I need to populate the column first.