Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Init not prefilling the form
I have a model form and I want to initialize my form with two prefilled fields, I have override the init method but is not working, this is something that I have tried: forms.py class AgregarPagoTransaccionExistente(forms.ModelForm): def __init__(self, *args, **kwargs): self.carro = kwargs.pop('carro') self.semana = kwargs.pop('semana') super(AgregarPagoTransaccionExistente, self).__init__(*args, **kwargs) class Meta: model = Pagos fields = ('carro', 'pago', 'fecha', 'semana', 'renta') widgets = {'fecha': forms.DateInput(attrs={'type': 'date'}), 'semana': forms.DateInput(attrs={'type': 'week'}) } views.py class AgregarPagoSemana(CreateView): template_name = "AC/add_paymentexistingweek.html" model = Pagos form_class = AgregarPagoTransaccionExistente def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'semana': self.kwargs['semana'], 'carro': self.kwargs['carro'], }) return context def get_form_kwargs(self): kwargs = super(AgregarPagoSemana, self).get_form_kwargs() kwargs['carro'] = self.kwargs.get('carro') kwargs['semana'] = self.kwargs.get('semana') return kwargs this is how I'm passing the parameters in the template <a href={% url 'pago_existente' carro=request.resolver_match.kwargs.carro semana=request.resolver_match.kwargs.semana %}><button type="button" class="btn btn-primary" > this is the UI of the form with the blank fields: I'm not getting any errors, the form is being display but now with the data prefilled according to the parameters that I'm passing wich are 'Carro' and 'Semana'. -
How to link html files together using Django?
i am using django 3.0 with python 3.8. i am new to coding. below is my project hierarchy.i want to connect my "home" page to next html "teoco" page by clicking on continue button for which i have below html code myproject.urls- from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('training_review.urls')), path('teoco', include('training_review.urls')), path('admin/', admin.site.urls), ] home.urls- from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home'), path('teoco',views.teoco, name='teoco') ] home.views- def home(request): return render(request, 'home.html') def teoco(request): return render(request, 'teoco.html') -
'User' object is not iterable , on save function called
in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME Internal Server Error: /factarti/upload/file Traceback (most recent call last): File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/brter/PycharmProjects/brter/brter_2_7/factartis/views.py", line 352, in upload factarti, admin = savefactarti(request.POST, factarti_object_type, factarti_form, request.user)# here is error File "/home/brter/PycharmProjects/brter/brter_2_7/factartis/views.py", line 515, in savefactarti specific_form.save() File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/forms/models.py", line 458, in save self.instance.save() File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/db/models/base.py", line 790, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/signals.py", line 52, in handle_save index.update_object(instance, using=using) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/indexes.py", line 284, in update_object backend.update(self, [instance]) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/backends/solr_backend.py", line 60, in update docs.append(index.full_prepare(obj)) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/indexes.py", line 208, in full_prepare self.prepared_data = self.prepare(obj) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/indexes.py", line … -
django aws elastic beansstalk error ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
I know this error have come to many people and i have tried different solutions and none of them worked. I am using aws eb cli. i am using following command eb deploy to deploy my application to server. Following are the configuration for my django. under .ebextensions directory, i have following 2 files: 1: 01_packages.config packages: yum: git: [] python27-devel: [] mysql: [] mysql-devel: [] and another file is 2: 02_django.conf option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "settings.development" "PYTHONPATH": "/opt/python/current/app/src:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: src/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" following is my requirements.txt file after pip freeze in my local virtual environment. requirements.txt asn1crypto==0.24.0 awsebcli==3.17.1 backports.ssl-match-hostname==3.5.0.1 botocore==1.14.17 cement==2.8.2 cent==2.1.0 centrifuge==0.8.4 certifi==2017.11.5 cffi==1.11.2 chardet==3.0.4 colorama==0.3.9 cryptography==2.1.4 Django==1.8.18 django-colorfield==0.1.14 django-countries==5.0 django-debug-toolbar==1.9.1 django-environ==0.4.4 django-multiselectfield==0.1.8 django-simple-history==1.9.1 django-sslserver==0.20 docutils==0.15.2 enum34==1.1.6 future==0.16.0 google-api-python-client==1.6.4 hiredis==0.2.0 html5lib==1.0b8 httplib2==0.10.3 icalendar==4.0.0 idna==2.6 ipaddress==1.0.18 jmespath==0.9.4 jsonschema==2.4.0 mysqlclient==1.4.6 oauth2client==2.0.0 oauthclient==1.0.3 olefile==0.44 pathspec==0.5.9 paypalrestsdk==1.13.1 pdfcrowd==4.0.1 phonenumbers==8.8.6 Pillow==4.3.0 pyasn1==0.3.7 pyasn1-modules==0.1.5 pycparser==2.18 PyJWT==1.5.3 pyOpenSSL==17.5.0 PyPDF2==1.26.0 pypiwin32==219 pytesseract==0.1.7 python-dateutil==2.6.1 pytz==2017.3 PyYAML==5.2 reportlab==3.4.0 requests==2.18.4 rsa==3.4.2 semantic-version==2.5.0 six==1.11.0 sockjs-tornado==1.0.1 sqlparse==0.2.4 termcolor==1.1.0 toredis-fork==0.1.4 tornado==4.2.1 toro==0.8 twilio==6.9.1 uritemplate==3.0.0 urllib3==1.22 wcwidth==0.1.8 webencodings==0.5.1 xhtml2pdf==0.2.2 i kept this in my root directory. when i run eb deploy it deploys successfully. but when i run the browser to my url. I get this Internal Server … -
How to properly write complex boolean expressions in Python [closed]
if not request.user.is_staff and obj.is_internal or not request.user.is_kyc_complete: return None I tried: if not (request.user.is_staff and obj.is_internal) or not request.user.is_kyc_complete: return None But my tests keep failing -
Difference between models and Model in django
What exactly is the difference between models and Model.while writing a model in django. from django.db import models class Teacher(models.Model): -
Select a valid choice. <choice> is not one of the available choices
I am passing choices from the view into my form. When I submit the form , the error returned from form.errors is: Select a valid choice. 1-20-2020 - 1-27-2020 is not one of the available choices. views.py : lstchoices = [] for week in weeks: lstchoices.append((week,week)) form.fields['camp_dates'].choices = lstchoices def register(request): form = RegistrationForm() print (request.POST) if request.method == 'POST': # create a form instance and populate it with data from the request: form = RegistrationForm(request.POST) # check whether it's valid: if (form.is_valid()): return render(request,'camp_registration.html') else: print (form.errors) forms.py class RegistrationForm(forms.Form): camp_dates = forms.MultipleChoiceField( widget = forms.CheckboxSelectMultiple, ) -
Populate database with foreign key relationship in Django (Wagtail)
once a day I need to remove all data from 2 tables and upload new data. All goes well with "product" table, but I'm not able to populate "pricelist" table because there is foreign key relationship on the table. model.py: class product(models.Model): EAN = models.CharField(primary_key=True, unique=True, max_length=13) Name = models.CharField(max_length=50) class vendor(models.Model): vendor = models.CharField(primary_key=True, unique=True, max_length=7) Name = models.CharField(max_length=50) class pricelist(models.Model): EAN = models.ForeignKey(product, on_delete=models.CASCADE) vendor = models.ForeignKey(vendor, on_delete=models.CASCADE) Qty = models.CharField(max_length=15) app.py ... def app ... product_list = product_list[["EAN", "Name"]] session.execute("use intranet; SET FOREIGN_KEY_CHECKS = 0; DELETE FROM product_list; DELETE FROM pricelist; SET FOREIGN_KEY_CHECKS = 1;") session.flush() session.commit() product_list.to_sql("product_list", con=engine, if_exists='append', chunksize=1000, index=False) df = df[["EAN", "vendor", "Qty"]] # everything works until here: df.to_sql("pricelist", con=engine, if_exists='append', chunksize=1000, index=False) Error I get: (1452, 'Cannot add or update a child row: a foreign key constraint fails If I replace if_exists='append' with if_exists='replace' then data is uploaded but table settings (including all relations) are wiped out. Any help would be really appreciated! -
Pull Variable From HTML And Pass to Django Form
In my url i have my classroom id : example here : http://127.0.0.1:8000/points/k8_points_classroom/1? I need to pull the 1 out of this and send it to my forms view to achieve this query. How do i go about doing that ? Thank you class K8Points_ClassroomForm(forms.ModelForm): class Meta: model = K8Points fields = ('student_name', 'behavior','academic', 'time_frame','date','day','week_of','class_name') labels = {'class_name':_('Class Name'),'student_name':_('Student Name'),'time_frame':_('Time Frame') } def __init__(self, *args, **kwargs,): super(K8Points_ClassroomForm,self).__init__(*args,**kwargs) self.fields['date'].disabled = True self.fields['day'].disabled = True self.fields['week_of'].disabled = True classid = getstudents = Student.objects.filter(class_name = classid).order_by('student_name') self.fields['student_name'].queryset= getstudents.all().order_by('student_name') self.fields['class_name'].widget.attrs['readonly'] = True The query filters the students that are present in the class to the dropdown menu. -
Does a Django form invalidates if additional input fields are injected and posted from html?
I am using two different forms for same model, one of which is supposed to not include a particular field in it. Say, I have a model called payments (which has a field 'lead' and some other fields). I make two forms out of it - PaymentAddWithLeadField and PaymentAddWithoutLeadField. The latter form excludes the field lead in it. Now, if someone manually injects the field lead in html form and posts it, will form.is_valid() stand invalidated? I just want to make sure that no one can save the value for the field 'lead' from PaymentAddWithoutLeadField (that excludes the field) form posting as I dont want it to happen. -
Specify where django should look for template
I have a loca django project. In this project I stored a templates/ directory at the same level as apps/the inner project folder. This folder only held base.html (as I didn't think it made sense to store it in an app if all pages would extend it). To use this template I simply said {% extends 'base.html' %} and it would work. Now, I have set up a server and am working on moving my project over. However, now when I go to my domain(have debug=True for now) I see: TemplateDoesNotExist at / Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /home/justin/project/account/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/justin/project/job/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/justin/project/env/lib/python3.6/site-packages/crispy_forms/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/justin/project/env/lib/python3.6/site-packages/django/contrib/admin/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/justin/project/env/lib/python3.6/site-packages/django/contrib/auth/templates/base.html (Source does not exist) Is there a way to tell Django it can find base.html at /home/justin/project/templates/base.html? -
django.db.utils.IntegrityError: NOT NULL constraint failed: users_profile.user_id
I am currently working on a project that would take in a users information and store it. My problem is I keep running into this NOT NULL constraint failed with the user id error. I believe this comes from having a null user when the form is trying to save, but don't know what I could do to fix it. I tried using this line: form.user = Profile.objects.get(user=self.request.user) but it didn't work and gave me this error: NameError at /users/pii/ name 'self' is not defined Any help or advice that would point me in the right direction would be greatly appreciated! models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') gender = models.CharField(max_length = 1, choices = GENS, default = '') birthday = models.DateField(default = '1900-01-01') address = AddressField(on_delete=False, blank=True, null=True) race = models.CharField(max_length = 2, choices = RACES, default = 'x') ethnicity = models.CharField(max_length = 1, choices = ETHNICITIES, default = 'x') income = models.CharField(max_length = 1, choices = INCBRACKET, default = 'x') education = models.CharField(max_length = 2, choices = EDUCATION, default = 'x') employment = models.CharField(max_length = 1, choices = EMPLOYMENT, default = 'x') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kawrgs): super().save(*args, **kawrgs) img … -
WSGI problem on Eleastic Beanstalk with Django
Some days ago I have deployed a Django on AWS elastic beanstalk(EB) and it worked fine. Today, after a new deploy, where I did minor changes in view.py, the Django APP on EB has a very big problem and it becomes not accessible anymore. Looking at the log file in AWS EB I read this errors: Script timed out before returning headers: wsgi.py End of script output before headers: wsgi.py, referer ... Do you have any ideas how to solve this issues? I would like to thank you in advance, -
Image not being uploaded .I want to upload the image and save it into the database i've given the media root and media url
applyonline.html(I have given file fields for adhaarcopy and idcopy) <body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-if="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="custom-file"> <input type="file" class="custom-file-input" id="customFile" name="adhaaarcopy"> <label class="custom-file-label" for="customFile">Choose file</label> </div> </div> <!--logic for no--> <div ng-if="showHideTest=='false'"> <div class="form-group"> <div class="form-group"> <label for="adhaar_eid">Aadhaar Enrollment ID(EID):</label> <input name="adhaar_eid" id="identityno" class="form-control" required> </div> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Identity Card)* </label> <input name="beneficiary_id_name" class="form-control" id="formGroupNameInput" placeholder="Enter your name" required> </div> <div class="form-group"> <label for="idno">Identity Number(Enclose Copy of Identity Card)*:</label> <input name="idno" id="identityno" class="form-control" required> </div> <div class="custom-file"> <input type="file" class="custom-file-input" name="idcopy" id="customFile"> <label class="custom-file-label" for="customFile">Choose file</label> </div> </div> </div> <button type="submit" class="btn btn-primary" style="margin-bottom:10px ">Submit</button> </form> </div> {% endblock %} </body> this is my views.py i've used POST.get @login_required def personal_detail(request): … -
Export HTML table to excel without page refresh using python
I have a web page in which user can generate a table with no of rows and no of columns input. Now I want to export this HTML table to an excel file using python. After some googling, I came to know about the to_excel snippet as shown below. import pandas as pd # The webpage URL whose table we want to extract url = "https://www.geeksforgeeks.org/extended-operators-in-relational-algebra/" # Assign the table data to a Pandas dataframe table = pd.read_html(url)[0] # Store the dataframe in Excel file table.to_excel("data.xlsx") As you can observe from the above code that the program navigates to the specified url, but in my web page, if the url is hit, all the data is gone (after page refresh) because I am generating number of rows and columns on the go without page refresh. Can someone suggest alternate approach for excel export of HTML table using python? -
Why si widthratio (multiplication) not working in my template?
I'm using Django 2.0 and Python 3.7. I've read I can do multiplication in templates by using widthratio -- multiplication in django template without using manually created template tag . However, in a template of mine, I'm trying this to no avail. I'm trying {% if widthratio articlestat.score 1 TRENDING_PCT_FLOOR >= articlestat.weighted_score %}style="font-weight:bold;"{% endif %} When my template is executed with this code, it gives the error ... Unused 'articlestat.score' at end of if expression. I want my if expression to say if the multiple of "articlestat.score" and "TRENDING_PCT_FLOOR" is greater than "articlestat.weighted_score," print this out, but I can't seem to figure out how to do that. -
Using prefetch_related on category, subcategory and features
I'm trying to loop over my FeatureCatergories, FeatureSubcategories and Features. I'm able to loop over my feature categories just fine. Now I want to loop over my feature subcategories and finally features. I'm not sure what to call in my template for subcategories.. Should it be {{featuresubcategory.title}}? What about features? views.py def features_view(request): context = { "feature_categories": FeatureCategory.objects.prefetch_related('featuresubcategory_set').all(), } return render(request=request, template_name="main/features.html", context=context) template.html {% for category in feature_categories %} {{category.title}} {% for subcategory in featuresubcategory %} {{ subcategory.title }} {% endfor %} {% endfor %} models.py class FeatureCategory(models.Model): title = models.CharField(max_length=50) featured_image = models.ImageField(blank=True, upload_to="features/") category_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Feature Categories" def __str__(self): return self.title class FeatureSubcategory(models.Model): title = models.CharField(max_length=50) category = models.ForeignKey('FeatureCategory', on_delete=models.CASCADE) category_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Feature Subcategories" def __str__(self): return self.title class Feature(models.Model): title = models.CharField(max_length=150) category = models.ManyToManyField(FeatureSubcategory) description = models.TextField() featured_image = models.ImageField(upload_to=image_dir) class Meta: verbose_name_plural = "Features" def __str__(self): return self.title -
Django EmailMultiAlternatives - When attach a file: Body becomes blank in email
I use EmailMultiAlternatives to send mail in my django application. Please find below code for reference: email = EmailMultiAlternatives( subject=subject, body=body_text, from_email=from_email, to=to_email, reply_to=reply_to_email, cc=cc_email, bcc=bcc_email ) email.attach_alternative(body_html, 'text/html') # attachments for attachment in attachments: email.attach(attachment.name, attachment.document.read()) email.send() Now problem is whenever there is any attachment, email body gets blank. Is there any conflict between attach_alternative and attach. Let me know if any doubt/confusion! Thanks -
Backward lookup in Django
Following are my model classes. class Categories(models.Model): name= models.CharField(max_length=255, unique=True) class Values(models.Model): category = models.ForeignKey(Categories) language = models.CharField(max_length=7) category_name = models.CharField(max_length=50) Lets say I have already got list of Values. Now I want to get name of the Category to which this Value object is related to. How can I do that ? Will appreciate your help. -
How do I create a field in my serializer to avoid a "TypeError: cannot unpack non-iterable Address object" error?
I'm using Django 2.0, Python 3.7 and the django-address module -- https://github.com/furious-luke/django-address . In short, the Address object depends on Locality objects (cities) and I have created my own model that depends on the Address object ... class Coop(models.Model): name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() Then I have created the below serializers to handle processing JSON being uploaded to create my model and its address object ... class AddressTypeField(serializers.PrimaryKeyRelatedField): queryset = Address.objects def to_internal_value(self, data): if type(data) == dict: locality = data['locality'] locality, created = Locality.objects.get_or_create(**locality) data['locality'] = locality address, created = Address.objects.create(**data) # Replace the dict with the ID of the newly obtained object data = address.pk return super().to_internal_value(data) ... class CoopSerializer(serializers.ModelSerializer): type = CoopTypeField() address = AddressTypeField() class Meta: model = Coop fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site'] def to_representation(self, instance): rep = super().to_representation(instance) rep['type'] = CoopTypeSerializer(instance.type).data rep['address'] = AddressSerializer(instance.address).data return rep def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Coop.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Coop` instance, given the validated data. … -
Django: OR with multiple statements
I want to fetch an object, sometimes with one condition and some other time adding (OR) another condition. With Laravel (PHP), this is easy to do: $q = MyModel::where('col1', $val1); if ($userWantsToAddAnotherOrCondition) { $q = $q->orWhere('col2', $val2); } At the end I have a query either with condition 'col1' = $va1 or 'col1' = $va1 OR 'col2' = $val2. In Django (python), I only know this way: q = MyModel.objects.filter(Q(col1=val1) | Q(col2=val2)) How can I add the second condition (col2=val2) with another statement ? -
Confirm user owns a social account without switching to a different logged user (django social auth)
I'm using Django social auth to log users in using Facebook, Twitter, etc as described, for example here. Scenario: A user is logged onto my platform using my native login system. I want them to validate that they own a particular Twitter account without redirecting them to a view where request.user is a new UserSocialAuth associated with their Twitter account. I want to show the user the Twitter login page but, after they provided their credentials, keep them logged in as they were rather than log them in as a different user. -
haystack and solr takes 1 positional argument but 2 were give
update_index.Command().handle( app_label, using=None, remove=indexJob.remove ) I am migrating from django 1.8 to django 2.2 and python 2.7 to python 3. I am having that error there, how can i fix it? -
Setting default value of field in model to another model instance
Model class SlackPermission(models.Model): STATUS_CHOICES = [ ('A', 'ACTIVE'), ('P', 'PASSIVE') ] account_type = models.CharField(max_length=100) status = models.CharField(max_length=1, choices=STATUS_CHOICES) class GithubPermission(models.Model): STATUS_CHOICES = [ ('A', 'ACTIVE'), ('P', 'PASSIVE') ] ACCOUNT_TYPE_CHOICES = [ ('A', 'ADMIN'), ('B', 'BASIC') ] field1 = models.CharField(max_length=100) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE_CHOICES) status = models.CharField(max_length=1, choices=STATUS_CHOICES) class Employee(models.Model): full_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) slack_permission = models.OneToOneField(SlackPermission, on_delete=models.CASCADE, related_name='Slack',default=SlackPermission.objects.get(pk=1)) github_permission = models.OneToOneField(GithubPermission, on_delete=models.CASCADE, related_name='Github',default=GithubPermission.objects.get(pk=1)) Error: ValueError: Cannot serialize: <GithubPermission: GithubPermission object (1)> There are some values Django cannot serialize into migration files. I am creating API just to create Employee. Where there is not option of giving slackpermissions and githubpermissions. How do I give default value in there? -
Why with SlugField model cannot be updated and without slugfield it can be updated?
In general, the data didn't change, I decided to remove the slug in the model and it all worked. Before that, when I changed something through the admin panel, and generally through any means nothing changed, but for some reason when I removed the slug field, any field changes. Why did it happen? Models (BEFORE REMOVING) from .for_slug import slugify as my_slugify class Quiz(models.Model): """Quiz model""" slug = models.SlugField('Url-адрес', max_length=50, blank=True) ..... def save(self, *args, **kwargs): """Use the custom slugfiy (for_slug.py)""" if not self.slug: slug = my_slugify(self.title) exists = Quiz.objects.filter(slug=slug).exists() if exists: slug += f'-{str(int(time()))}' self.slug = slug super().save(*args, **kwargs) for_slug.py from django.template.defaultfilters import slugify as django_slugify alphabet = { 'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo', 'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'j', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u', 'ф': 'f', 'х': 'kh', 'ц': 'ts', 'ч': 'ch', 'ш': 'sh', 'щ': 'shch', 'ы': 'i', 'э': 'e', 'ю': 'yu', 'я': 'ya' } def slugify(s): return django_slugify(''.join(alphabet.get(w, w) for w in s.lower())) If it matters I use PostgreSQL. Why it happens?