Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve values from the related table created by Django itself?
Recently I am developing a project where I have to create a table that contains 2 many to many fields and 1 foreign key. Through this table Django implicitly creates a related table (for mapping). Now my question is I need to fetch the values from the mapping table. This particular table has no existence in models.py but this is there in the database.How shall I query this one in views.py and what shall I import to make this table visible in views.py. p.s. I am a noob in Django. Any help would really be appreciable. -
Django Oauth Toolkit as SSO server
I want to know can we use Django oauth Toolkit (DOT) as SSO server? I am using Django Rest Framework in backend. Steps I need to achieve : On clicking the Login Button in the client server, it redirects to the server asking to authorise. If already logged in it will return the auth code. If not logged in open the log in prompt. On successful login step 2 will followed. Thanks. -
How to display python output to the page in django
Hey I am making a website with django, I already have the design of the website all that i need is to display a timer, history, different graphs, and other python backend code. I am confident i can write it in python I am just confused on how i can display the output from python to the page. Please help! -
How to genrate fingerprint using NAB Transact in django?
I am using NAB Transact with Python/Django. I found 2 documentation for Nab: Document 1 - https://sourdough.com/sites/default/files/PDF/DirectPostIntegrationGuide.pdf Document 2 - https://www.nab.com.au/content/dam/nabrwd/documents/forms/payment-andmerchants/nab-ecommerce-merchant-application-form.pdf I tried to generate a Fingerprint but couldn't get any response. <form action="https://transact.nab.com.au/test/directpost/genfingerprint" method="post" target="_blank"> <input type="hidden" name="EPS_MERCHANT" value="XYZ0010"> <input type="hidden" name=”EPS_PASSWORD” value=”txnpassword”> <input type="hidden" name="EPS_REFERENCEID" value="Test Reference"> <input type="hidden" name="EPS_AMOUNT" value="100.00"> <input type="hidden" name="EPS_TIMESTAMP" value="20140224221931"> <input type="hidden" name="EPS_RESULTURL" value="https://www.resulturl.com"> <input type="submit" value="OK"> </form> -
How to Upload Image in React js and Django?
I am trying to upload an image using react js on django backend but wheni try to upload pic and check it console.log() image FILE exist there and once i submit the form image file object shsows {} empty i don't why all the time when i submitted for its shows uploaded but all the time image shows null, Here is my code so far what i did. here is also a link of code sandbox link . https://codesandbox.io/s/thirsty-varahamihira-fnusu?file=/src/App.js:0-1494. Thanks. import React, { Component } from "react"; import "./styles.css"; class App extends Component { constructor(props) { super(props); this.state = { image: null }; } handleInputChange = async (event) => { await this.setState({ [event.target.name]: event.target.files[0] // image: event.target.files[0] }); }; handleSubmit = (e) => { e.preventDefault(); const formdata = new FormData(); formdata("image", this.state.image); fetch(`https://inback.herokuapp.com/api/1/blog/image/list/`, { method: "POST", headers: { "Content-Type": "multipart/form-data", Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw" }, body: formdata }) .then((response) => { if (response.ok) { alert("Success"); } else { alert("error"); } }) .catch((err) => { console.log(err); }); }; render() { return ( <div id="other" className=""> <p className="mod" style={{ marginTop: "10px" }}> Uplaod </p> <hr></hr> <form onSubmit={this.handleSubmit}> <input type="file" name="image" onChange={this.handleInputChange} /> <button>Submit</button> </form> </div> ); } } export default App; -
Cannot send mail when close terminal AWS
I deployed a Django app on AWS and when I connect to AWS Linux terminal, it worked. But when close the terminal, the web server cannot send mail anymore. I use EmailMessage in Django. I run server with nginx and gunicorn. -
Django Hosting that has unlimited hosting apps for my Projects
Is there any website which gives unlimited apps to create for django hosting... Means I can upload as many django website as I want for my projects because heroku only gives 5 apps at max -
Django forms not adding textbox & not sending what user looked up
So the django file is not showing the form and at first, I got angry at that so I just used HTML code to create a form but I realized that when I submit it on the form it does not send it to where I want it to send. I was just wondering if you could help. I think the problem with the file is between the relationship between util.py file and the index.html file but I can't see it for some reason. Thank you!! util.py file class Form(forms.Form): searched = forms.CharField(max_length=128, help_text="Please enter the category name.") def get_name(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): searched = form.cleaned_data['searched'] return searched else: form = Form return render(request, "wiki/index.html", { "form" : form }) wiki.urls.py - main urls file from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include("encyclopedia.urls")), path('wiki/', include("encyclopedia.wurls")) ] encyclopedia.urls file from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] views.py file from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "lookUp": util.get_name(request) }) def title(request, name): return render(request, "encyclopedia/titlePage.html", { "entries": util.list_entries(), "name": name, "entry": … -
add a field to a Django model
I am working on this project: https://github.com/mirumee/saleor I want to add a "user_id" column to the product table. So, I added the following code to line 248 https://github.com/mirumee/saleor/blob/master/saleor/product/models.py#L248 account_user = models.ForeignKey( Account_User, related_name="products", on_delete=models.CASCADE, ) However, Django says "NameError: name 'Account_User' is not defined". How could I solve this problem? Thanks -
Deploying a python app to heroku, struggling with gunicorn configuration
I've inherited a python django app and am trying to breathe new life in it. It's currently using python 2.7 and many old packages that I will eventually need to upgrade. But the first thing before upgrading is I want to have it running successfully on heroku. So far I have it running fine locally, but I'm running into issues with heroku and gunicorn. Here is the error I'm getting: 2020-09-10T03:48:27.212247+00:00 heroku[web.1]: Starting process with command `gunicorn spotlit_due_diligence.spotlit_due_diligence.wsgi:application` 2020-09-10T03:48:29.477479+00:00 heroku[web.1]: State changed from starting to up 2020-09-10T03:48:29.206728+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [4] [INFO] Starting gunicorn 19.10.0 2020-09-10T03:48:29.207159+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [4] [INFO] Listening at: http://0.0.0.0:45741 (4) 2020-09-10T03:48:29.207253+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [4] [INFO] Using worker: sync 2020-09-10T03:48:29.211268+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [11] [INFO] Booting worker with pid: 11 2020-09-10T03:48:29.250434+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [13] [INFO] Booting worker with pid: 13 2020-09-10T03:48:29.000000+00:00 app[api]: Build succeeded 2020-09-10T03:48:30.075238+00:00 app[web.1]: [2020-09-10 03:48:30 +0000] [11] [ERROR] Exception in worker process 2020-09-10T03:48:30.075250+00:00 app[web.1]: Traceback (most recent call last): 2020-09-10T03:48:30.075251+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 586, in spawn_worker 2020-09-10T03:48:30.075251+00:00 app[web.1]: worker.init_process() 2020-09-10T03:48:30.075251+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 135, in init_process 2020-09-10T03:48:30.075252+00:00 app[web.1]: self.load_wsgi() 2020-09-10T03:48:30.075252+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-09-10T03:48:30.075252+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-09-10T03:48:30.075253+00:00 app[web.1]: … -
Testing Graphene returns error JSONDecodeError: Expecting value: line 2 column 1 (char 1)
I am new to Unit Test on Graphene and DJango. I am trying to test my graphql query by graphene https://docs.graphene-python.org/projects/django/en/latest/testing/ But I have no idear why I am getting this error. Please help me. import json from graphene_django.utils.testing import GraphQLTestCase # Create your tests here. class CryptoBankQueryTestCase(GraphQLTestCase): def test_cryptobank_query(self): response = self.query( ''' query cryptoBank($id: Int!){ cryptoBank(cryptoBankId: $id) { id, name, phoneNumber, address } } ''', op_name="cryptoBank", variables={"cryptoBankId": 1} ) content = json.loads(response.content) # This validates the status code and if you get errors self.assertResponseNoErrors(response) # Add some more asserts if you like Error: ERROR: test_cryptobank_query (cryptobank.tests.test_cryptobank_query.CryptoBankQueryTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/cafafanscoders/Desktop/python/CryptoBankGraphQL/src/cryptobank/tests/test_cryptobank_query.py", line 22, in test_cryptobank_query content = json.loads(response.content) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1) -
Django Oscar Dashboard link not accessible
I have developed oscar /django applications before but I am completely stumped by this issue: I can see the dashboard url in the supported urls list but I am not able to access it. 404 Page I have forked a few apps from oscar like voucher, shipping, checkout, reviews and customized them in various ways(None of these are dashboard related) . This is my INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar.config.Shop', 'oscar.apps.analytics.apps.AnalyticsConfig', 'iirns.checkout.apps.CheckoutConfig', 'oscar.apps.address.apps.AddressConfig', 'iirns.shipping.apps.ShippingConfig', 'oscar.apps.catalogue.apps.CatalogueConfig', 'iirns.catalogue.reviews.apps.CatalogueReviewsConfig', 'oscar.apps.communication.apps.CommunicationConfig', 'oscar.apps.partner.apps.PartnerConfig', 'oscar.apps.basket.apps.BasketConfig', 'iirns.payment.apps.PaymentConfig', 'oscar.apps.offer.apps.OfferConfig', 'oscar.apps.order.apps.OrderConfig', 'oscar.apps.customer.apps.CustomerConfig', 'oscar.apps.search.apps.SearchConfig', 'iirns.voucher.apps.VoucherConfig', 'oscar.apps.wishlists.apps.WishlistsConfig', 'oscar.apps.dashboard.apps.DashboardConfig', 'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig', 'oscar.apps.dashboard.users.apps.UsersDashboardConfig', 'oscar.apps.dashboard.orders.apps.OrdersDashboardConfig', 'oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig', 'oscar.apps.dashboard.offers.apps.OffersDashboardConfig', 'oscar.apps.dashboard.partners.apps.PartnersDashboardConfig', 'oscar.apps.dashboard.pages.apps.PagesDashboardConfig', 'oscar.apps.dashboard.ranges.apps.RangesDashboardConfig', 'oscar.apps.dashboard.reviews.apps.ReviewsDashboardConfig', 'oscar.apps.dashboard.vouchers.apps.VouchersDashboardConfig', 'oscar.apps.dashboard.communications.apps.CommunicationsDashboardConfig', 'oscar.apps.dashboard.shipping.apps.ShippingDashboardConfig', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', 'mailer', 'extra', ] and this is my root url file: from django.conf.urls import url from django.contrib import admin from django.apps import apps from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('extra.urls')), path('', include(apps.get_app_config('oscar').urls[0])), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to create a separeate log file for each user logged in using Django?
Am new to DJango, how to create a new logger or log file on each user logon? how to access this logger to log user specific actions? And also, Need to close the logger on the user logout. Please share any ideas or examples if any? -
django-pytest with user-agent cant find request.user-agent
thanks for your time. i've got a app thats getting tested with pytest-django. although i've been facing some issues for the request function o views.py. at my views i've got some statements based on the request.user_agent(app installed django-user-agents) to select if will be displayed a mobile or desktop template. And those are getting me errors on pytest-django. views.py: def curriculo_view(request): context = {} if request.user_agent.is_mobile: return render(request, 'amp/Curriculo-mobile.html', context) elif request.user_agent.is_pc: return render (request, 'admin/Curriculo.html', context) else: return render (request, 'admin/Curriculo.html', context) test_views.py: def test_curriculo_view(self): path = reverse('curriculo') request = RequestFactory().get(path) response = views.curriculo_view(request) assert response.status_code == 200 error: def curriculo_view(request): context = {} > if request.user_agent.is_mobile: E AttributeError: 'WSGIRequest' object has no attribute 'user_agent' accounts\views.py:98: AttributeError i've tried to set like when i want to set a user (ex:request.user = User.objects.get()), tried to set to the key of request.META['USER_AGENT'] and none is getting me trough this. -
Cannot assign "'value'": "model.attr" must be a "model" instance
I am new en django, I have the next models in models.py class Persona(models.Model): cedula_p= models.CharField(primary_key=True, max_length=10) Nombre_p= models.CharField(User, max_length=100) fecha_nacimiento_p= models.DateField() #11111, User1, 01/01/1991 #22222, User2, 02/02/1992 #Others 13998 items def __str__(self): return "{0},{1}".format(self.cedula_p, self.Nombre_p) class Producto(models.Model): Nombre_prod = models.CharField(max_length=100) precio = models.PositiveIntegerField() def __str__(self): return "{0}".format(self.Nombre_prod) class compra(models.Model): cedula_prod= models.ForeignKey(Persona, max_length=10, on_delete=models.CASCADE) producto = models.ForeignKey(Producto, on_delete=models.CASCADE) The forms.py is: class formulario_compra(forms.ModelForm): cedula_prod = forms.CharField() #I have 14.000 elements, for that reason i don't use select o choicefield class Meta: model = compra fields = '__all__' #input test cedula_prod: 11111 or 22222 and the views.py class crear_persona(CreateView): model = Persona form_class = formulario_persona template_name = 'web1.html' success_url = reverse_lazy('EjemploVista1') class crear_compra(CreateView): model = compra form_class = formulario_compra template_name = 'Web2.html' success_url = reverse_lazy('EjemploVista2') in the forms, in formulario_compra i don't use the default form for cedula_prod because would be a list with some values (14000), so, I use a charField. I need to verify that the input exists in the model Persona.cedula_p. At the moment to try to save appear: Cannot assign "11111": "compra.cedula_prod" must be a "Persona" instance. I try different things, but I can't solve this situation. -
How to check email is already in database or not in django?
I want to add a functionality in registration form that if email is already in database than display massage ie this email is already register. i am trying this with the following code but this is not working accounts/forms.py from django.contrib.auth import get_user_model from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): # email = forms.EmailField() class Meta: fields = ["username","email","password1","password2"] model = get_user_model() def clean_email(self): email = self.cleaned_data.get('email') if email in User.objects.all(): raise forms.ValidationError("Only .edu email addresses allowed") return email def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' # self.fields['email'].label = 'Email Address' -
How to get ManytoManyField's data from another model in Django?
I am here asking for guides on how to get ManyToManyField's data from another model. Let's say I have 3 models, Student, Course, and Attendance. Course model has a many to many relationship with Student. In CourseForm I set the widget of student to CheckBoxSelectMultiple so that user can check which student can get into that course in form. In another model called Attendance I also have a field which also has many to many relationship with Student. Now in my AttendanceForm on student field I want to display only the students who were selected when the Course was created. I think maybe we can do the queryset inside the AttendanceForm because right now the default queryset for student inside AttendanceForm is Student.objects.all() but I don't know how to do the queryset to get only the students who were selected when the Course was created. Can anyone help me please? models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) class Course(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) random_code = ShortUUIDField(default=code, editable=False) class Attendance(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) course = models.ForeignKey(Course, on_delete=models.CASCADE) forms.py class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['student', 'random_code', ..] widgets = {'student': … -
Integrating Google Calendar into existing Django app
I'm currently trying to integrate Google calendar to a Django project I'm working on for my job (not a programming job originally but is going in that direction thanks to corona). I started learning programming very recently and we haven't had a very structured course for learning, so I'm pretty close to a beginner. I found plenty of resources on how to get started using the Google Calendar API but nothing on how to actually use it in the Django app, so I'm pretty much just winging it. For now I just need to have the site add an event to our calendar when a booking is made, I have a file with some copy-pasted code (the only changes I made were to get the event date and time from a booking in the database instead of inputting it manually), which will add the event when I run the file on its own. I've run into some problems trying to integrate it with the existing files. Below is that code (again, I'm still struggling to learn things so be kind) from __future__ import print_function from datetime import datetime, timedelta import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import … -
Django-rules setup issue: has_perm always False for custom user model
I am new to Django. I have been trying to set up django-rules with a custom user model but keep getting a 404 when trying to access the page. Here is how the setup looks: Custom user model class User(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name = _('user') verbose_name_plural = _('users') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email settings.py AUTHENTICATION_BACKENDS = ( 'rules.permissions.ObjectPermissionBackend', 'django.contrib.auth.backends.ModelBackend', ) installed apps INSTALLED_APPS = [ # ... 'rules.apps.AutodiscoverRulesConfig', ] rules.py @rules.predicate def is_organisation_member(user, organisation): """Check if user is an active organisation member""" m = get_if_exists( OrganisationMember, user=user, organisation=organisation, organisation__state=Organisation.LifecycleState.ACTIVE ) if not m: return False if not m.is_active: return False return True rules.add_perm('organisations.member', (is_authenticated & is_active & is_organisation_member)) views.py def get_organisation_by_slug(request, *args, **kwargs): return get_object_or_404(Organisation, workspace_name=kwargs['workspace']) @permission_required('organisations.member', fn=get_organisation_by_slug) def OrganisationView(request, workspace): # ... According to the debug, is_organisation_member returns True, but the user still gets a 404 error when trying to view the page (without django-rules permission_required decorator the page works). Any ideas why am I getting a 404 response? -
Django query: Item in model who is not in other model
Noob Django ORM question here: I have a model similar to this: class Company(models.Model): id = models.PositiveIntegerField(null=False, blank=False, primary_key=True) name = models.CharField(max_length=255, null=True, blank=True, default="") class Audited(models.Model): company = models.ForeignKey( Company, null=False, blank=False, on_delete=models.CASCADE, related_name="logs" ) city = models.CharField(null=False, blank=False, max_length=255) I have been scratching my head with this problem and I can not figure out how to solve it. Given a city, I need the company that do not have been audited on that city, so basically the Company who does not have a record on Audited with that city. So for example, if the city is New York, and there is no record in Audited with a company like Oracle and city as New York, I receive Oracle. It is very confusing to me because the ORM appears to have been designed for positive relations, like "the item from table A who has a record on Table B", and this is precisely the opposite. Any clue of how can I do this? -
Dynamic JsonForm with ImageField
I am creating a dynamic form (using JSON format) in Django, the form needs to save multiple images using Django Storage and save the reference to the file in the JSON field. This is what I have right now, it works but is really ugly, Django already do this, I can't figure out how to re-use same functionality. Class SomeModel(models.ModelForm): results = JSONField() class DynamicJsonForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # ... Add dynamic fields to the form self.extra = [] # Save the reference for the fields class Meta: model = SomeModel exclude = ("results",) def save(self, commit=True): results = {} for extra in self.extra: value = self.cleaned_data.get(extra) question = some_query.question if "photo" in extra and value: # value = photo filename, ext = value.name.split(".") filename = "media/the/path/to/photos/{}_{}.{}".format(filename, uuid4().hex, ext) uploaded_file = SimpleUploadedFile(filename, value.read(), value.content_type) image = Image.open(uploaded_file) if image.mode in ("RGBA", "P"): image = image.convert("RGB") image.save(fp=filename) results[question][extra] = filename else: results[question][extra] = value self.instance.results = results return super().save(commit) This actually works, it saves the data to the JSONField (results) and saves the image to local file system storage. How can this be improved to use Django Storage and make it simple? Using Django Model.save() seems a lot … -
Requested runtime (python 3.8) is not available for this stack (heroku-18)
I'm trying to deploy an app with Heroku, but it's not working... I have looked at a bunch of other posts on here with the same error, but I'm not finding what's wrong. I have Python 3.8.5 installed on my machine which is supported by Heroku-18, but for whatever reason when I do "git push heroku master" it sees python 3.8: -----> Python app detected ! Requested runtime (python 3.8) is not available for this stack (heroku-18). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. I have the runtime.txt file with python-3.8.5: python-3.8.5 I also checked the version on my PC specifically, and tried reinstalling to no success, either: $ python -V Python 3.8.5 And, again, it's supported as of July, 21st, 2020: https://devcenter.heroku.com/changelog-items/1833 I guess the question would be, how do I get Heroku to recognize that I have the correct version installed? I'm sure it's something small I'm overlooking, but I can't figure it out. -
Get / extract the date format currently used, from Django
Is there a function that gets / extracts the string literal "dd/mm/yyyy" or "mm/dd/yyyy" based on Django's localisation / internationalisation settings i.e. the default format that it is using, when displaying dates coming from a "models.DateField", in its template engine? -
Django can't create a new column
I've created a django project recently and it always starts to show problems. I've made some models let's say this is models.py: from django.db import models class MainModel(models.Model): text = models.CharField(max_length=1000, blank=False, null=False) other_text = models.CharField(max_length=1000, blank=False, null=False) def __str__(self): return f"Main obj: {self.id}" The first step before I write any code, is run python manage.py migrate so I can run the initial migrations. After that I write the model shown above and then execute python manage.py makemigrations and then python manage.py migrate. This worked and everything was fine. I tried to add a new column, let's say an integer field: models.py: from django.db import models class MainModel(models.Model): text = models.CharField(max_length=1000, blank=False, null=False) other_text = models.CharField(max_length=1000, blank=False, null=False) number = models.IntegerField(default=1) def __str__(self): return f"Main obj: {self.id}" Great! I run python manage.py makemigrations and everything breaks. I get 200 lines of errors and the output is django.db.utils.OperationalError: no such column: app_mainmodel.number This is fun and all but I couldn't find an answer to why was this happening. I tried changing folders. I created a new file in the same path. So the first project was located in C:/Users/user/Desktop/Site for example and the second one was in C:/Users/user/Desktop/Site2. I created the … -
Extract id field as key django rest framework serializer
Say I have a Blog model which has the following fields: id content title If I am to create a model serializer, It would serialize to this: [ {id: 1, content: "content1", title: "title1"}, {id: 2, content: "content2", title: "title2"}, ] But I want it to serialize to this: { '1': {content: "content1", title: "title1"}, '2': {content: "content2", title: "title2"}, } This way, I could access elements faster on the front end given their id instead of having to search for the id manually. How can I do that ?