Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it a good practice Django send request to itself
I have a django rest API that serves endpoints. I coded a complex system of permissions from the views, hence the importance of going through the views for my CRUD operations. For a particular need, I must allow an external application to be able to also use a single endpoint to serve all the others. As if this global endpoint were a postal service: we will send information in an envelope: the endpoint to serve, the method, the data ... To avoid writing the same code in several places, I thought from the view of the global endpoint, call the view of one of the endpoints to be served. However, once I get the request in the view, I have to modify it by changing the data, the paths ... to pass it to the other view. But I have to change too much information in the request. So I wonder: can I make an outgoing request to my second endpoint can I use a component as a test Client or Mock do I have to modify the information of the request before calling the second view? What are the best practices? -
I WANT TO GET ALL SESSIONS CRETED BY A USER
MY MODEL I WANT TO GET ALL SESSIONS CRETED BY A USER DO SUGGEST ME WHERE AM I DOING WRONG. class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) date_of_birth=models.DateField(null=True,blank=True) mobile_number=models.CharField(max_length=20,blank=True,null=True) address=models.CharField(max_length=100,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) joining_date=models.DateField(null=True,blank=True) Rating_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) Rating=models.IntegerField(choices=Rating_CHOICES,default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return str(self.user_name) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE) game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) SPORT=( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) Sports_category=models.CharField(max_length=10,choices=SPORT) SESSIONS=( ('General','General'), ('Business','Business'), ) Session_category=models.CharField(max_length=15,choices=SESSIONS) TYPE=( ('Paid','Paid'), ('Free','Free'), ) Session_type=models.CharField(max_length=10,choices=TYPE) Created=models.DateField(null=True,blank=True) Session_Date=models.DateField(null=True,blank=True) Location=models.ForeignKey(MyUser,related_name='street',on_delete=models.CASCADE) Player=models.CharField(max_length=100,blank=False) Start_time=models.TimeField(auto_now=False, auto_now_add=False) End_time=models.TimeField(auto_now=False, auto_now_add=False) Duration=models.CharField(max_length=30,blank=False) status=( ('1','Active'), ('2','UnActive'), ) Status=models.CharField(max_length=20,choices=status) Equipment=models.TextField() Duration=models.CharField(max_length=20,blank=False) Level=models.ForeignKey(IntrestedIn,blank=True,on_delete=models.CASCADE) GENDER=( ('Male','Male'), ('Female','Female'), ('Male and Female','Male and Female'), ('Other','Other'), ) Gender=models.CharField(max_length=20,choices=GENDER ,blank=True) Fee=models.CharField(max_length=50,blank=True,default='0') def __str__(self): return str(self.Host) class Gamification(models.Model): User_Name=models.ForeignKey(MyUser,on_delete=models.CASCADE) Total=models.IntegerField() def __str__(self): return str(self.User_Name) MY VIEWSET I WANT TO GET ALL SESSIONS CRETED BY A USER DO SUGGEST ME WHERE AM I DOING WRONG. class GamificationViewSet(viewsets.ViewSet): def create(self,request): try: User_Name=request.data.get('User_Name') Total=request.data.get('Total') new=Gamification() new.User_Name=MyUser.objects.get(user_name=User_Name) new.Total new.save() return Response({'Data':'Entered'}) except Exception as error: return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) def list(self,request): … -
Reverse for 'create_time_table' with no arguments not found
url.py: url(r'^create-time-table/(?P\w+?)/(?P\w+?)/$', views.create_time_table, name='create_time_table'), menu.html: -
Editing a User photo on Django, need to pass request.POST +request.FILES together
I'm a little stuck here, coding newbie and working on my first Django project from scratch.Looked at a couple answers and tried a couple things out but still not working.I'm trying to allow a user to edit their photo. I figured out how to allow them to upload it in the registration and I know it deals with 'request.FILES', but I can't figure out how to include it with the form value for editing the profile. This is the error I'm getting AttributeError at /update_account/10/ 'Profile' object has no attribute 'get' Request Method: POST Request URL: http://localhost:8000/update_account/10/ Django Version: 3.0 Exception Type: AttributeError Exception Value: 'Profile' object has no attribute 'get' Exception Location: /Users/papichulo/Desktop/DatingApp/11_env/lib/python3.7/site-packages/django/utils/functional.py in inner, line 225 Python Executable: /Users/papichulo/Desktop/DatingApp/11_env/bin/python Python Version: 3.7.3 Python Path: ['/Users/papichulo/Desktop/DatingApp', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/papichulo/Desktop/DatingApp/11_env/lib/python3.7/site-packages'] Server time: Fri, 13 Mar 2020 04:30:40 +0000 here is my update_account view: def update_account(request, profile_id): #Edit an existing profile profile = request.user if request.method != 'POST': #Initial request; prefil form with current entry update_form = ProfileUpdateForm(instance=profile) else: #POST data submitted;process data. update_form = ProfileUpdateForm(profile, request.POST, request.FILES) if update_form.is_valid(): update_form.save() return HttpResponseRedirect(reverse('dating_app:profile', args=[profile.id])) context = {'profile' : profile, 'update_form' : update_form} return render(request, 'dating_app/update.html', context) Here is my form.py, … -
BD scheme for multiple size versions of a single original image
Specification I'm designing BD scheme for user profile photos. Each user profile photo should have three size versions. Sizes are Large Medium Small Problem What are some DB scheme best practice for such a situation? What I came up with Something a came up with was to make one master image table and three tables for each sizes and relate them with foreign keys. Image Master Table Table: User Profile Image - image id - user(fk) Tables for each sizes Large Table: User Profile Image Large - id - user profile image id(fk) - image url(I use S3 for storing images) Medium Table: User Profile Image Medium - id - user profile image id(fk) - image url(I use S3 for storing images) Small Table: User Profile Image Small - id - user profile image id(fk) - image url(I use S3 for storing images) Additional Info I use Django btw but I think my question is almost purely a DB problem. However if there are any libraries making this problem easy I would like to know. -
Where is Flask class in documentation of flask?
Please help me regarding this. When we write : from flask import Flask I tried to find Flask code in documentation of flask but i am not getting it.Where can i find Flask class code? -
What is the DEFAULT maximum length of TextField Django?
i wanna known what is the maximum length of TextField in django models. I just know only they cannot limit maximum length but i wanna know the real maximum length of TextField type. Please help me solve questions. -
Django admin override model field validation
I have a fee DecimalField in my model as follow: class CardTypes(models.Model): class Meta: db_table = "card_types" verbose_name = 'Card Type' verbose_name_plural = 'Card Types' name = models.CharField("Name", max_length=255, null=True, blank=True) fee = models.DecimalField("Fee", max_digits=65, decimal_places=0, default=0) image_url = models.CharField("Image Url", max_length=255, null=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) def card_type_image(self): if self.image_url is not None: return mark_safe('<img src="%s" width="130" height="90" />' % (self.image_url)) else: return "No image yet" card_type_image.short_description = 'image' def fee_convert(self): if self.fee is not None: currency = Currency.objects.get(pk=1) return Decimal(self.fee / pow(10, currency.decimals)) else: return None fee_convert.short_description = 'Fee' I set DecimalField("Fee", max_digits=65, decimal_places=0, default=0) because i want to save it with no decimal place on my DB, but on the admin site i want to interact with it converted method. For excample if fee in database is 0.00005 then in the admin it will only show and save with the value of 5(because currency.decimals = 5) I managed to show the converted value and save with the value of 5 in the admin side like so : class CardTypeAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CardTypeAdminForm, self).__init__(*args, **kwargs) if self.instance.fee is not None: try: self.initial['fee'] = self.instance.fee_convert() except: pass def clean_fee(self): if self.cleaned_data['fee'] is not None: currency = … -
Postgresql with Django
Al correr el comando python manage.py makemigrations me sale el siguiente error y no logro comprender a que se debe. Agradezco su ayuda. Versión de Python es 3.7.4 Versión de Django es 3.0.3 Versión de Psycopg2 es 2.8.4 Los parámetros que tengo en el archivo de configuración son los siguientes DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'articulosclientes', 'USER': 'postgres', 'PASSWORD': 'Felipesanti33', 'HOST':'127.0.0.1', 'DATABASE_PORT':'5432' } Error: C:\Users\Felipe Vargas\Documents\ProyectosDjango\TiendaOnline>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 220, in ensure_connection self.connect() File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\django\db\backends\postgresql\base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\psycopg2\__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Felipe Vargas\Anaconda3\lib\site-packages\django\core\management\base.py", line 369, in execute output … -
react-admin is getting full schema from graphene API
I'm currently following ra-data-graphql-simple documentation https://github.com/marmelab/react-admin/tree/master/packages/ra-data-graphql-simple to connect a RA app to a django-graphene backend. Initial goal is to list all records of a specified model: App.js class App extends Component { constructor() { super(); this.state = { dataProvider: null }; } componentDidMount() { buildGraphQLProvider({ clientOptions: { uri: 'http://mysite:8000/graphql/' }}) .then(dataProvider => this.setState({ dataProvider })); } render() { const { dataProvider } = this.state; if (!dataProvider) { return <div>Loading</div>; } return ( <Admin dataProvider={dataProvider}> <Resource name="model" list={ModelList} /> </Admin> ); } } Modellist JSX: export const ModelList = (props) => { const isSmall = useMediaQuery(theme => theme.breakpoints.down('sm')); return ( <List > {isSmall ? ( <SimpleList primaryText={record => record.id} secondaryText={record => `${record.name} views`} tertiaryText={record => new Date(record.anno).toLocaleDateString()} /> ) : ( <Datagrid> <TextField source="id" /> <TextField source="name" /> <TextField source="anno" /> <EditButton /> </Datagrid> )} </List> ); } RIght now react-admin only shows "Loading..." section of component, and the request made to the API gives complete schema of itself. As I understood, when you state a in RA return jsx, it finds all records of that model in API endpoint, but this one doesnt include any data, but the schema. What I'm missing? -
Changed data after changing name of field in Django models.py
I'm doing and playing around with my own Django project. I tried to change a couple of names of fields in models.py, and tried some ways that I found on google. after some trials, it seemed successful and I played around with my project. But I figured out it's not working out as it had been so I checked my administration page on Django and db browser for sqlite and found that all data of the field I changed in name have been also changed into the name of changed field name that I tried as shown in picture. Does anyone know how to retrieve or bring back my old data? Thanks in advance! picture of changed name of field and its data in models.py -
How to attach a html file within project directory and send it as mail?
I am trying to send the coverage report generated after execution of test cases, which is generated in htmlcov folder, import os from django.conf import settings from utils import email_utils def pytest_sessionfinish(session, exitstatus): to = ['unnim@growthplug.com'] body = 'test' subject = 'coverage test' attachment = "htmlcov/index.html" coverage_html = os.path.join(settings.BASE_DIR + '/' + attachment) email_utils.send_email_with_attachment(to, body, subject, coverage_html, 'application/html', "index.html") while doing so I am getting the following error: ERROR | 2020-03-12 10:07:57,180 | MainThread | email_utils.send_email_with_attachment.69 | a bytes-like object is required, not 'str' Traceback (most recent call last): File "/home/ubuntu/growthplug_django/utils/email_utils.py", line 66, in send_email_with_attachment email.send() File "/usr/local/lib/python3.5/dist-packages/django/core/mail/message.py", line 342, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python3.5/dist-packages/sgbackend/mail.py", line 66, in send_messages mail = self._build_sg_mail(email) File "/usr/local/lib/python3.5/dist-packages/sgbackend/mail.py", line 125, in _build_sg_mail base64_attachment = base64.b64encode(attachment[1]) File "/usr/lib/python3.5/base64.py", line 59, in b64encode encoded = binascii.b2a_base64(s)[:-1] TypeError: a bytes-like object is required, not 'str' I checked if the file exists in the path, using if statement and yes it exists, is this something related to the way I am handling the files here? What should be the right approach? -
django multiple upload not functioning
Good day,, Im having trouble on uploading files.. when upload multiple files(pdf) only 1 file will save.. views.py def attachments(request): to = TravelOrder.objects.order_by('-date_filling').last() if request.method == 'POST': form = AttachmentsForm(request.POST, request.FILES) if form.is_valid(): for f in request.FILES.getlist('attachment'): file_instance = Attachements(travel_order=to, attachment=f) file_instance.save() print('YEY') return redirect('attach') else: form = AttachmentsForm() context = { 'form': form } return render(request, 'employee/attachments.html', context) my models.py class TravelOrder(models.Model): created_by = models.CharField(max_length=255) start_date = models.DateField(auto_now=False) end_date = models.DateField(auto_now=False) wfp = models.CharField(max_length=255, verbose_name='Wfp Where to be charged') purpose_of_travel = models.CharField(max_length=255) region = models.ForeignKey(Region, on_delete=models.CASCADE) venue = models.CharField(max_length=255) date_filling = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=15) def __str__(self): return self.purpose_of_travel class Attachements(models.Model): at_id = models.AutoField(primary_key=True) travel_order = models.ForeignKey(TravelOrder, on_delete=models.CASCADE) attachment = models.FileField(upload_to='attachment/') please help me. thank you in adavance -
Aggregate events with drf
I have the following structure: [ { "event_datetime": "2020-03-12T22:39:55.273267Z", "event_type": "Production", "quantity": 58 }, { "event_datetime": "2020-03-12T22:49:55.273267Z", "event_type": "Production", "quantity": 108 }, { "event_datetime": "2020-03-12T23:39:55.273267Z", "event_type": "Waste", "quantity": 8 }, { "event_datetime": "2020-03-12T23:59:55.273267Z", "event_type": "Production", "quantity": 15 } ] What i wanna do is once i have an event followed by another that has the same type i'd like to output on another endpoint the following structure: [ { "start_datetime": "2020-03-12T22:39:55.273267Z", "end_datetime": "2020-03-12T22:49:55.273267Z", "event_type": "Production", "quantity": 108 }, { "start_datetime": "2020-03-12T23:39:55.273267Z", "end_datetime": "2020-03-12T23:39:55.273267Z" "event_type": "Waste", "quantity": 8 }, { "start_datetime": "2020-03-12T23:59:55.273267Z", "end_datetime": "2020-03-12T23:59:55.273267Z" "event_type": "Production", "quantity": 15 } ] I also want to do that without having to save this structure on db. How could i do this using DRF? -
Can a django template immediately start streaming in chunks to the client without waiting for it to fully render?
I remember working with PHP a long time ago and a webpage would start being streamed to the client directly, then if a php block was found, the stream blocked until the string from the php was returned and then continued sending data to the client. If an exception was found then you could see a chunk of website, and then the exception in the middle of the webpage. I want to be able to send a django template to the client the same way as PHP did. For example: 1. <html> 2. <head> 3. ... 4. </head> 5. <body> 6. hello {{ some_context_variable }} bye 7. </body> 8. </html> If some_context_variable is a long database operation, I want the user to be able to see hello in the browser until some seconds pass and the db operation is solved, then the user would see in the screen something like hello friend bye Can this be done with django views and rendering a django template? If not, could it be done with another template language like jinja2 or another in conjunction with django? Note: I know that django has StreamingHttpResponse, but as I understand it only allows the view to … -
Difference between JSONField and ArrayField
The following case [{type: x, val: y}, {...}, {...}, ...] can be represented by JSONField alone. Also, the following case [1,2,3,4,5] can be represented by JSONField. Then what is the point of using ArrayField? Am I correct to assume JSONField covers all the cases of ArrayField? -
Applying django.db.backends modifications to entire project
So i needed to make implement own CursorWrappedDebug to log error queries too (in file django.db.backends.utils.py). I've done: logger = logging.getLogger('django.db.backends') class CustomCursorDebugWrapper(CursorWrapper): def execute(self, sql, params=None): start = time() try: return super(CustomCursorDebugWrapper, self).execute(sql, params) except Error as e: exception=e finally: stop = time() duration = stop - start sql = self.db.ops.last_executed_query(self.cursor, sql, params) self.db.queries_log.append({ 'sql': sql, 'time': "%.3f" % duration, }) if 'exception' in locals(): logger.error('(%.3f) %s; args=%s' % (duration, sql, params),extra={'duration': duration, 'sql': sql, 'params': params}) raise exception else: logger.debug('(%.3f) %s; args=%s' % (duration, sql, params),extra={'duration': duration, 'sql': sql, 'params': params}) utils.CursorDebugWrapper = CustomCursorDebugWrapper Now I need to apply these changes to the entire project (all modules etc.) not to the current file. Should i make like custom database backend , if so , then how to implement custom database backend. -
How to handle a POST request from a Django form loaded via a custom template tag?
I added a Django form to my Bootstrap nav bar to be included on every page, and it renders as it should with the appropriate values. The form was added using an inclusion_tag. However, I'm now at a loss as to how to handle the request from the form. Upon submission, whichever page the user was on should reload with updated content from the form submission. For more context, see my earlier question: How to place a django form in a nav bar so that it appears on every page? -
Django ORM query to retrieve objects from a table and most recent objects from another foreign-key-related table?
How can I translate the SQL query below to a Django ORM statement so that I get the same fields? SELECT entity_a.id AS entity_a__id, entity_a.created_at AS entity_a__created_at, MAX(entity_b.last_update) AS max__entity_b__last_update, entity_b.id AS entity__b_id, entity_b.datadump AS entity_b__datadump FROM entity_a INNER JOIN entity_b ON entity_a.id = entity_b.entity_a_id WHERE entity_a.created_at < '2020-03-10' GROUP BY entity_a.id; -
filtering a queryset based on the results of anoter one
So I have a model called post and one of its fields is a foreign key to user model, And i have another model called subscriptions which has 2 foreign keys one referring to the user and the other one referrs to another account and i want to filter the post queryset to only show posts from people where there is a subscription object where the user is subscribed to the creator of the post. My models look like this: class post(models.Model): creator = models.ForeignKey(Account,blank=False,null=False,on_delete=models.CASCADE) ... class subscriptions(models.Model): subscriber = models.ForeignKey(Account,blank=False,null=False,on_delete = models.CASCADE, related_name='subscriber') subscribed_to = models.ForeignKey(Account,blank=False,null=False,on_delete = models.CASCADE, related_name='subscribed_to') i tried doing this in the views posts = post.objects.filter(creator__in = request.user.subscribed_to) but it return nothing -
Django session cookie disappears with DEBUG=True and multiple logins
I have a very odd issue I've encountered with either django or django-cas-ng (or possibly caused by other django tools?). When DEBUG = True, and a user logs in twice (e.g. in different browsers), the second browser appears to override the first, and the session cookie disappears. This doesn't appear to happen DEBUG = False, so is there something about DEBUG = True which could cause this, and if so where's the best place to find about the differences DEBUG makes (I had assumed that DEBUG only printed backtraces on error, but it appears it does more than that)? -
Django __in but return the first matching element
I have this model from django.db import models class TranslatedString(models.Model): lang = models.CharField() key = models.CharField() value = models.CharField() I have these instances of this model: a = TranslatedString(lang="en_US", key="my-string", value="hello world") b = TranslatedString(lang="en_AU", key="my-string", value="g'day world") c = TranslatedString(lang="ja_JP", key="my-string", value="こんにちは世界") And I have this list of languages a user wants preferred_langs = ["en_CA", "en_US", "en_AU", "fr_CA"] which is ordered by preference. I would like to return the value that matches the first item in that list. Even though both a and b would match a query like TranslatedString.objects.filter(key="my-string", lang__in=preferred_langs).first() I want it to be ordered by the list, so that I always get a. I can make a query for each element in preferred_langs and return as soon as I find a matching value, but is there a better option? I'd like to do it in one query. -
How to use vue in django?
Maybe this question sounds silly but still my vue code doesn't want to work. I'm totally new in Vue. I just added script in my <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> And thought it would be enough. Then I wrote the simple piece of code: new Vue({ el: ".seats_displayer", data: { display: "redbox" } }) and the caught element: <div class="seats_displayer"> {{display}} </div> console says that "display" has not been defined. When I type VUE in console it shows me the vue's object. What did I do wrong ? -
Django Rest Framework Serializers validate passes for one but fails on another
Here's what I currently have: models.py: class Team(models.Model): label = models.CharField(max_length=128, unique=True) def __str__(self) -> str: return self.label class AppName(models.Model): label = models.CharField(max_length=128, unique=True) def __str__(self) -> str: return self.label serializers.py class TeamSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Team fields = [ 'id', 'label' ] class AppNameSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = AppName fields = [ 'id', 'label' ] This is my function: appname = AppNameSerializer(data={'label': request.POST.get('appname')}) if appname.is_valid(): appname = appname.save() team = TeamSerializer(data={'label': request.POST.get('team')}) if team.is_valid(): team = team.save() where request.POST.get('appname') is 'foo-name' and request.POST.get('team') is 'Chocobo Knights' Why is appname.is_valid() throwing invalid? whereas team.is_valid() passes? They're effectively the same code, I'm so confused. TeamSerializer(data={'label': 'Chocobo Knights'}): id = IntegerField(label='ID', read_only=True) label = CharField(max_length=128, validators=[<UniqueValidator(queryset=Team.objects.all())>]) True AppNameSerializer(data={'label': 'foo-app'}): id = IntegerField(label='ID', read_only=True) label = CharField(max_length=128, validators=[<UniqueValidator(queryset=AppName.objects.all())>]) False -
How to make default values dynamic in django?
How to remove choices and dafault value of year from migration file: migrations.AlterField( model_name='campaign', name='year', field=models.CharField(choices=[['2020', '2020'], ['2021', '2021']], default='2020', max_length=4), ), I want to have it dynamically set in model (and it works, but model seals databes with values above)