Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Operational Error" when running coverage test
Hi I got a problem when running a coverage test in my django project, an operational error saying that a database already exists, i tried using fake migration python manage.py migrate --fake this is the error message i see File "c:\users\ziad hossain\appdata\local\programs\python\python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 381, in execute return Database.Cursor.execute(self, query) django.db.utils.OperationalError: table "driver_driver_customer" already exists -
How to change django-messages style depending on it's tag?
So I want to have messages pop-up when you add something and when the thing you wanna add is already in the database, the thing is that I can't get the messages style to be different on both occasions I've tried a couple of different things, the main one being the following code here https://imgur.com/a/8oQQ3ME When I do this no style is activated -
How to automate mutations in graphene with apscheduler
I am setting up a schedule template to create an event to notify users to do a stock count periodically. I could do this by calling an instance of the model inside the scheduler but my mutation auto-creates an event that is linked to the schedule. Here's my mutation class: class CreateStockCountTemplate(graphene.Mutation): stock_template = graphene.Field(StockCountTemplateType) success = graphene.String() class Arguments: product_ids = graphene.List(graphene.Int, required=True) event_type = graphene.Int(required=True) assigned_user_ids = graphene.List(graphene.String, required=True) designated_user_ids = graphene.List(graphene.String, required=False) outlet_id = graphene.Int(required=True) scheduled_time = graphene.String(required=True) frequency = graphene.Int(required=False) @login_required @user_permission('Manager', 'Admin') def mutate(self, info, **kwargs): template_instance = StockCountTemplate() template_fields = stock_counts.get_template_fields(**kwargs) schedule = kwargs.get('scheduled_time') with SaveContextManager(template_instance)as stock_tempalate: scheduled_time = make_aware(parser.parse(schedule)) event_type = setattr( stock_tempalate, 'event_type', kwargs['event_type']) description = 'Stock count on auto scheduling' event = Event( start_date=scheduled_time.date(), end_date=scheduled_time.date() + timedelta(days=7), start_time=scheduled_time.time(), end_time=scheduled_time.time(), event_title=f'Stock count', description=f'{description}', event_type=event_type) stock_tempalate = stock_counts.add_fields_to_template( template_instance, **template_fields ) event.save() stock_tempalate.event = event stock_tempalate.save() to_email = stock_tempalate.assigned_users.values_list( 'email', flat=True) email_stock_template = 'email_alerts/stocks/stock_email.html' subject = 'Stock counts alert' context = { 'scheduled_time': datetime.strftime( stock_tempalate.scheduled_time, "%d-%b-%Y"), 'by': str(info.context.user.email), 'template_type': 'Stock counts', 'small_text_detail': 'Hello, you have been assigned to carry' ' out stock counts' } send_mail = SendMail(email_stock_template, context, subject, to_email) send_mail.send() message = SUCCESS_RESPONSES[ "creation_success"].format("Stock count template") return CreateStockCountTemplate( stock_template=stock_tempalate, success=message) And in … -
How to delete certain user image form database in Django?
Hello I need to delete some images of current logged in user from DB from html here is my profile class class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image1 = models.ImageField(default=None, upload_to='images', blank=True) image2 = models.ImageField(default=None, upload_to='images', blank=True) image3 = models.ImageField(default=None, upload_to='images', blank=True) thanks a lot -
How to setup docker-compose, pytest, Selenium Driver and geckodriver/chromedriver correctly
I am testing my django app with pytest. Now I want to use Selenium for system tests. I am also using docker so to execute my tests I do docker-compose -f local.yml run django pytest When I try to use Selenium I get the message that 'geckodriver' executable needs to be in PATH.. I read many questions here on SO and I followed the instructions. Yet, I think my path can't be found because I am executing everything in a docker-container. Or am I mistaken? I added the geckodriver path to my bash-profile by checking my path with: which geckodriver. The result of this is:/usr/local/bin/geckodriver Then I added this to my profile and when I type echo $PATH I can see this: /usr/local/bin/geckodriver/bin:. So I assume all is set correctly. I also tried setting it manually doing: self.selenium = webdriver.Firefox(executable_path=r'/usr/local/bin/geckodriver') Since I still get the error I assume it has sth to do with docker. That's why my specific question is: How can I setup the PATH for geckodriver with pytes, selenium and docker-compose? Any help or hint into the right direction is very much appreciated! Thanks in advance! Here is my docker-compose file as requested: FROM python:3.6-alpine ENV PYTHONUNBUFFERED … -
How to show a list of all of the GitHub user's repositories?
I added django-allauth to the Django project and I can authentication with GitHub on website. Right now I have a different task, I want to show a list of all of the GitHub user's repositories on the web page (it will be only repositories of this user). Do you know how it to do with django-allauth package? Or with another package? Or maybe exist another way? -
www.example.com is insecure but example.com is secure
Currently when i enter the following urls , all are redirected to https://example.com and i want this to happen only. http://example.com example.com https://example.com But when i enter the following urls then they are not getting redirected to https://example.com instead Not secure connection gets open www.example.com http://www.example.com https://www.example.com This is myapp.conf in /etc/nginx/sites-available/ server { root /usr/share/nginx/html; index index.html index.htm; server_name example.com; # managed by Certbot location /static/ { alias /home/datasleek/tracker/staticfiles/; } location /media/ { alias /home/datasleek/tracker/media/; } location / { proxy_pass http://unix:/home/datasleek/trackervenv/tracker/daphne.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/datasleekapp.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/datasleekapp.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80 ; listen [::]:80 ; server_name example.com; return 404; # managed by Certbot } server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80 ; listen [::]:80 ; server_name www.example.com; return 404; … -
Why can't I get the API data using django again?
Alright, I have a web app I'm developing locally, part of the app uses cryptocompare, well contrary to my previous experience on using API in Django(because previously i've been able to get data from cryptocomapare through there API) I couldn't even print the data to the console not to talk of template, I have even checked different other means of doing this in python on youtube and blogs but I don't seem to miss anything too(at least as far as I'm concern, but technically speaking something is wrong). I have done the following creating the app in Django; I have the app in the settings/installed-app I have my api key linked accordingly(at least as far as I can understand) The crypto code is like so for the Django import requests def cryptos(request): api_rqt = requests.get( 'https://min-api.cryptocompare.com/data/v2/news/?lang=EN&api_key={my-app-key) api = json.loads(api_rqt.content) print(api_rqt) context = {'api': api} template = 'home.html' return render(request, template, context) <div> {% for api in api.Data%} <h4><a href="">{{api.title}}</a></h4> <h5>By <a href=""></a> <label>|</label> <i>{{api.published_on}}</i></h5> <p>{{api.body}}</p> <a href="{{api.url}}" target="_blank" class="btn btn-secondary"> Read More ...</a> {% endfor %} </div> I expect the output to show me news summary from cryptocompare but nothing is shown. And my Django server is running very well. -
Add logged user as author of model, but keep ForeignKey
I want when add article, current logged user to be added as author, I'm also using ForegnKey to user and want to keep it, but right now throw error: objects/models.py: from django.db import models from users.models import ProfileUser class Object(models.Model): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) address = models.CharField(max_length=300) content = models.TextField() def __str__(self): return f"{self.title}" objects/forms.py: from django import forms from .models import Object class ObjectForm(forms.ModelForm): class Meta: model = Object fields = [ 'title', 'address', 'content', ] objects/views.py: def add_object(request): form = ObjectForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) obj.author = request.user obj.save() return redirect('home') context = { 'form': form } return render(request, "add_object.html", context) Also I rewrite default django user model: users/models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class ProfileUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.URLField() @receiver(post_save, sender=User) # Still don't know how, but next rows create ProfileUser when User is created def create_user_profile(sender, instance, created, **kwargs): if created: ProfileUser.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profileuser.save() def __str__(self): return f"{self.user}" Error: Cannot assign ">": "Object.author" must be a "ProfileUser" instance. -
How can I get the file information like name and size from request.FILES
i want to get information of uploaded file i know how i can get information form django raw-form request.FILES but it's dosent work with django model-forms moldes.py class ExcelFile(models.Model): name = models.CharField(max_length= 100, null=True, blank=True) file = models.FileField(upload_to='documnets/daily-report/%Y/%m/%d/') forms.py class UploadFileForm(forms.ModelForm): class Meta: model = ExcelFile fields = ('file',) views.py def upload_file(request): template_name = 'upload_file.html' if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): # i want to get file-name, file-size, file-content_type before saving data. form.save() return redirect('index') else: form = UploadFileForm() context = {'form':form} return render(request, template_name, context) -
How can I customize Password Confirm View when received Email Django Rest Auth
I am implementing Password reset by using django Rest Auth, two thing I requires when request hits from reactjs frontend I want the email to be customize I want to use password_reset_email.html template.Firstly I used simple PasswordResetView and I got the email but it sends me to native Rest UI PasswordConfirmView. I want,when User hit request it should use my templates which are, password_reset.html,password_reset_confirm.html,password_reset_done.html... which we make in our templates/appname directory my try: urls.py: urlpatterns=[ url( r'^rest-auth/password/reset/$', PasswordResetView.as_view(), name='password_reset', ), url( r'^rest-auth/password/reset/confirm/' r'(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] authsystem/templates: password_reset_confirm.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% if validlink %} <h3>Change password</h3> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Change password</button> </form> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} </body> </html> I know the above approach is less but I want the direction how can I make it work I don't want to use rest auth built-in UI, when request hits from react side,How can I use templates when the email is sent,when I click on link in email I want to show my template, token … -
Django crispy-forms: 2 column form with a TextArea field
I'm trying to create a good looking 2 column form using crispy-forms Layouts. Its getting messy when 1 of the fields is a TextArea field. (And all works fine when i do not have TextArea fields) This code: ## forms.py class BasicForm(forms.Form): label_1 = forms.CharField(label='label1') label_2 = forms.CharField(label='label2') label_3 = forms.CharField(label='label3',help_text='This is help text', widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'), ), Row( Field('label_2', wrapper_class='col-md-6', css_class='row-fluid'), Field('label_3', wrapper_class='col-md-6') ) ) Yields this format: And this code: self.helper.layout = Layout( Row( Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'), Field('label_3', wrapper_class='col-md-6') ), Row( Field('label_2', wrapper_class='col-md-6', css_class='row-fluid') ) ) Yields this format: I want to separate the 2 columns, each 1 should be stacked to the top, relatively to itself only. -
Could not parse the remainder: '=='True'' from 'upload_file=='True'' [duplicate]
This question already has an answer here: Boolean comparison in django template 2 answers I'm using Django 2.2, how to use logical operation True/False in HTML {% if upload_file == True %} <input type='file' class="form-control" name="images" value="{{ package_add_confirm.images }}"/> <span class="input-group-addon"><b>Upload</b></span> {% endif %} -
Print immediately Task Id of a programmed Task in Celery for Python
When I send a programmed Task from my view in Django, I need to obtain immediately the task.id if I need to revoke in a second moment. For example, my view: @login_required def program_task(request, pk): member = get_object_or_404(Post_Blog, pk=pk) if request.method == "POST": form = PostProgrammaForm(request.POST) if form.is_valid(): action = form.save(commit=False) action.account_id = member.pk action.programmed = 1 year= action.dataprogrammato.year month= action.dataprogrammato.month day= action.dataprogrammato.day hourz = action.oraprogrammato.hour hour= oraz - 2 ##this is for timezone :D minute= action.oraprogrammato.minute quando = datetime(year, month, day, hour, minute) action.save() if action.programmed == True: tasksend.apply_async(args=(action.id), eta=quando) ### here it send task and work, but I need to know here the task.id return redirect('blog_action', pk=member.pk) else: form = PostProgrammaForm(request.POST) return render(request, 'FBIsystem/post_program.html', {'form': form, 'member':member}) now, my celery py is somethig like this: app = Celery() @app.task(bind=True) def tasksend(self, action_id): ###do somethig everything work, I save form and I send task but... if I program a post for tomorrow and i need to revoke task before it run how can i do? Please help Thank you -
How to have new User in admin page after email confirmation?
How to solve the problem whenever someone registers in my site, before email confirmation, it should not be added in admin page. But it is adding before email confirmation. views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your Account.' message = render_to_string('users/active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return render(request, 'users/confirm_email.html') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return render(request, 'users/confirmed_email.html') return HttpResponse('Activation link is invalid!') admin.py class UserAdmin(admin.ModelAdmin): list_filter = ('is_active',) admin.site.unregister(User) admin.site.register(User, UserAdmin) -
establish a connection between django and SQL server using pyodbc
i have a django project that make a connection between django and MS SQL server the problem is that once the system run it display the below error : djago.db.utils.operationalError:('08001','[08001] [microsoft][odbc sql server driver]neither dsn nor server keyword supplied (0) (sqldriverconnect); [08001] [microsoft][odbc sql server driver] Invalid connection string attribute (0)') i know that the code 08001 mean Client unable to establish connection but all the credentials are correct. what am i missing here ? sql server credentials: server name : VSQLSERV authentication: windows authentication views.py from django.shortcuts import render import pyodbc def connect(request): conn = pyodbc.connect( 'Driver={SQL Server};' 'Server=ip address;' 'Database=I-Base_beSQL;' 'Trusted_Connection=yes;' ) cursor = conn.cursor() c = cursor.execute('SELECT "first name" FROM Person WHERE id = 2 ') return render (request,'connect.html',{"c":c}) connect.html {% for row in c %} {{ row }} {% endfor %} -
How to use same same django_filters.CharFilter field for two separate fields
So, basically I have a FilterSet I am using with django-tables2. Now I need to use have a single char field which should search two separate fields from the Model. For example: ip_addr = django_filters.CharFilter(lookup_expr='icontains') virtual_ip = django_filters.CharFilter(lookup_expr='icontains') Above is my current FilterSet. Both these are rendered into two separate fields in the Template. But I want to combine them into a single field in the front end, which looks up either in ip_addr OR in virtual_ip. Can any one point me in right direction. -
Django Admin save inlines save all or nothing
I have a legacy database on which I have developed a Django app purely for admin use with multiple inlines. Now sometimes the database throws an error while saving the inlines by violating a trigger/any other reason. But the parent has already been saved. How do I ensure either all or nothing is saved. -
expected string or bytes-like object error
when I run the migrate command I see that error. I don't know it comes from which my python files. I check my models with a new database but not diff. do you have any idea? Does it come from my models.py? my templates? my views? somewhere? python.exe .\manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, matab, sessions Running migrations: Applying matab.0032_auto_20190825_1010...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\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\operations\fields.py", line 112, in database_forwards field, File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\schema.py", line 433, in add_field definition, params = self.column_sql(model, field, include_default=True) File "C:\Users\Rahkar\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\schema.py", line 161, … -
getting error: get() returned more than one objects ( using get_object_or_404)
I'm getting error get() returned more than one Subtitle_name ..it returned !by executing simple update view using django. views.py from django.http import HttpResponse from django.shortcuts import render,redirect,get_object_or_404 from .models import Subtitle_name def updating_subtitle_name(request): obj=get_object_or_404(Subtitle_name) form=update_Subtitle_name_Form(request.POST or None,instance=obj) if form.is_valid(): form.save() context={ "form":form, "subtitle_name_id":f"Update{obj.subtitle_name_id}" } return render(request,'update_subtitle_name.html',context) forms.py from django import forms from .models import Subtitle_name class update_Subtitle_name_Form(forms.ModelForm): class Meta: model=Subtitle_name fields=['subtitle_name_id','subtitle_name','subtitle_short_code'] def update_subtitle(self,*args,**kwargs): instance=self.instance subtitle_name_id=self.cleaned_data.get('subtitle_name_id') print(subtitle_name_id) qs=Subtitle_name.object.filter(subtitle_name_iexact=subtitle_name_id) if instance is not None: qs=qs.exclude(pk=instance.pk) if qs.exist(): raise forms.ValidationError("This title has already been used Please insert new value") return subtitle_name_id update_subtitle_name.html <form method="POST">{%csrf_token%} {{form.as_p}} <input type="submit" value="Save" /> </form> MultipleObjectsReturned at /update_subtitle_name_create/ get() returned more than one Subtitle_name -- it returned 62! -
How to use NOT IN sql query in django
Im new to Django. Anyone help me to write "Not In" sql query in django. here i used raw() query set without raw() query set how to write this query in django. query = 'SELECT basic_uom FROM uom_master WHERE id="'+ id +'" and basic_uom not in (SELECT next_uom from uom_master WHERE id="'+ id +'") and basic_uom not in(SELECT std_uom FROM std_uom_master WHERE id"'+ id +'")ORDER BY next_uom ASC' data = uom_master.objects.raw(query) -
How to call external API in Django [duplicate]
This question already has an answer here: 400 BAD request HTTP error code meaning? 8 answers I use the external API in my project for sending message And I get the <Response [400]> error def send_sms(request): r = requests.post('https://api.msg91.com/api/v2/sendsms?country=91',json = payload, headers = headers) print(r.text) send_sms = r if r.status_code == 200: return HttpResponse('Its worked') return render(request, 'index.html',{'ph' : send_sms}) -
Generate form classes in Django
I'm building an onboarding / setup flow, and I'd like to define the fields, strings, etc. in a dict and have the form on each page automatically generated. forms.py currently has: class OnboardingEducationForm(forms.Form): school_1 = forms.CharField(label='School Name(s)', max_length=100, required=False) school_2 = forms.CharField(max_length=100, required=False) school_3 = forms.CharField(max_length=100, required=False) How would I generate those classes automatically from a json file that looks like this: setup_content = { "form": { "fields": [ { "name": "school_1", "args": { "label": "School Name(s)", "max_length": "100", "required": "False", }, }, { "name": "school_2", "args": { "max_length": "100", "required": "False", }, }, { "name": "school_3", "args": { "max_length": "100", "required": "False", }, } ] } } Note: This is not for a model form. I'm using modelform_factory for that. -
Handling related models in DRF and getting the right swagger docs for it
So I’m having a bit of trouble with something I was trying to do Basically, I have these models: class Package(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255, null=False, blank=False) contact = models.BooleanField(default=False) downloaded = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) class Item(models.Model): […. all the atributes of the item model….] class PackageItems(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) and now I am trying to make an endpoint that allows my users to add “package” and add a preexisting item in an item model to that newly created package. One package can of course have many items SO I wrote a Package serializer then added a SerializerMethodField that allows one to do a get on any item that a given package contains. The method makes a call to different serializer. Here’s the code for both the serializers: class PackageItemsSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PackageItems fields = ('package', 'item') class PackagesSerializer(serializers.ModelSerializer): """ Creation only requires a title """ package_items = serializers.SerializerMethodField(read_only=True) @swagger_serializer_method(serializer_or_field=packageItemsSerializer) def get_package_items(self, obj): packageItems = PackageItems.objects.all().filter(package=obj.id) return PackageItemsSerializer(packageItems, many=True, context={'request': self.context['request']}).data def create(self, validated_data): package = super(packagesSerializer, self).create(validated_data) return package class Meta: model = packages fields = ('id', 'user', 'title', 'contact', 'downloaded', 'created', 'package_items') read_only_fields = [ 'user', 'contact', … -
What is the value of self._db by default in Django?
Please see the following code: user.save(using=self._db) What is the default value of self._db for Django? Does this value default to what I've specified under default for database in my settings.py? I've found questions on Stack Overflow that say this value will provide a database type to Django, but if I've never set it explicitly, what is it by default?