Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why does Admin panel not show users in django admin site?
i login with supers user account but it shows me nothing . why ? [admin panel shows nothing ] https://i.stack.imgur.com/490OM.png -
why the output of subprocess.Popen is not the same as expected?
I have a Django server which trying to run with subprocess.Popen and store all the logs on a file, this is my code: with open('thefile.log', 'a') as the_file: p1 = subprocess.Popen(['python', os.getcwd() + '\\mySite\\manage.py', 'runserver'], stdout=the_file, stderr=the_file, universal_newlines=True) and this is the result in the thefile.log: Watching for file changes with StatReloader [26/Jul/2019 13:10:05] "GET / HTTP/1.1" 200 16348 [26/Jul/2019 13:10:05] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [26/Jul/2019 13:10:06] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [26/Jul/2019 13:10:06] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184 [26/Jul/2019 13:10:06] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 Not Found: /favicon.ico [26/Jul/2019 13:10:08] "GET /favicon.ico HTTP/1.1" 404 1976 Not Found: /fs [26/Jul/2019 13:10:11] "GET /fs HTTP/1.1" 404 1949 Performing system checks... System check identified no issues (0 silenced). July 26, 2019 - 13:09:44 Django version 2.2.3, using settings 'mySite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. but it should be like this: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 26, 2019 - 13:09:44 Django version 2.2.3, using settings 'mySite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [26/Jul/2019 13:10:05] "GET / HTTP/1.1" 200 16348 [26/Jul/2019 13:10:05] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [26/Jul/2019 13:10:06] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" … -
how to receive modelform_instance.cleaned_data['foreign key field'] in view when form field is ModelMultipleChoiceField?
Here is the situation: I have a model as below: class School(Model): name = CharField(...) Permit model has three objects: School.objects.create(name='school1') # id=1 School.objects.create(name='school2') # id=2 I have another model: Interest(Model): school_interest = ManyToManyField(School, blank=True,) I then build a ModelForm using Interest: class InterestForm(ModelForm): school_interest = ModelMultipleChoiceField(queryset=School.objects.all(), widget=CheckboxSelectMultiple, required=False) class Meta: model = Interest fields = '__all__' I have a view: def interest(request): template_name = 'interest_template.html' context = {} if request.POST: interest_form = InterestForm(request.POST) if interest_form.is_valid(): if interest_form.cleaned_data['school_interest'] is None: return HttpResponse('None') else: return HttpResponse('Not None') else: interest_form = InterestForm() context.update({interest_form': interest_form, }) return render(request, template_name, context) and in interest_template.html I have: <form method="post"> {% csrf_token %} {{ interest_form.as_p }} <button type="submit">Submit</button> </form> I expect to see None when I check no one of the form fields and submit it. I expect to see 'Not None' when I check any or all of the form fields and submit the form. However, I do not see what I expect to happen. -
Getting Undefined when making requests with the built-in interactive API documentation support of Django Rest Framework
I tried to make a simpleGET request but I get Undefined in the pop up. What could be the problem? -
Hi Which is The Best For Professional Website django or flask?
I'm confused which one I want to learn Django or flask for a highly professional website I'm confuse and i want to earn money to for your opinoin which is best for me? -
django how to transfer sum value to another model field each time user input is happened
enter image description herei want to transfer the sum value of stok_masuk as total_masuk,which then it will become the value of another model. The problem is,aggregate sum can only update the value to the same model. Which is why i make onetoonefield for the other model. But the value is not the accumulated total, but still a piece that must be chosen manually by admin, not automatically because this code is not working. def t_masuk(self): jaya = Pergerakanstokgudangatas.objects.aggregate(Sum('stok_masuk')) jaya.save(update_fields=['total_masuk']) return self.t_masuk def t_keluar(self): joyo = Pergerakanstokgudangatas.objects.aggregate(Sum('stok_keluar')) joyo.save(update_fields=['total_keluar']) return self.t_keluar The expected result would be,in picture 45454545, the total value of stok_masuk and stok_keluar will become a value as total_masuk and total_keluar in another fieldenter image description here -
Django queryset how to aggregate (ArrayAgg) over queryset with union?
from django.contrib.postgres.aggregates import ArrayAgg t1= Table1.objects.values('id') t2= Table2.objects.values('id') t3= Table3.objects.values('id') t = t1.union(t2, t3) t.aggregate(id1=ArrayAgg('id')) This raises error {ProgramingError} column "__col1" does not exist Equivalent raw SQL SELECT array_agg(a.id) from ( SELECT id FROM table1 UNION SELECT id FROM table2 UNION SELECT id FROM table3 ) as a -
Why do Django developers use Django builtin admin panel? is it said that must to use instead of a html theme?
I want to develop full functional web application in python django. I want to use bootstrap admin theme to develop admin site. I want to know is it required to use django admin while you are a django developer? or it's just a optional function if some one interested to complete tasks fast? -
Django Admin Inline field No foreign key error
I have two models,linked through Foreign key. What I exactly want is I have created Table hobbies which has some hobbies and user can select hobbies listed in hobbies table inform of checkbox.When editing model 'UserModel', on admin site in field where I have applied FK it shows dropdown to 'Hobbies' Model.On admin site I want hobbies to be displayed in form of checkbox instead of opening a new popup window and selecting hobbies.While searching I found Inline. I have tried to use them but I'm unsuccessful so far. I don't know what I'm doing wrong. models.py from django.db import models from django.contrib.auth.models import User from multiselectfield import MultiSelectField from tagulous import * import tagging class hobbies(models.Model): hobbies_choices = ( ('CRR', 'Cricket'), ('POL', 'Politics'), ('FBL', 'FootBall'), ('TV', 'Television'), ('MOV', 'Movies') ) table_id=models.AutoField(primary_key=True) hobbies = MultiSelectField( choices=hobbies_choices, verbose_name='Hobbies', default=None ) def __str__(self): return str(self.hobbies) class UserModel(models.Model): username=models.ForeignKey( User, related_name='UserModel', on_delete=models.CASCADE, ) name=models.CharField( max_length=50, verbose_name='Full Name', ) gender=models.CharField( choices=( ('M','Male'), ('F','Female'), ), max_length=1, verbose_name='Gender', default='M' ) hobbies=models.ForeignKey(hobbies,on_delete=None,related_name='of_user') admin.py from django.contrib import admin from .models import hobbies,UserModel from django.forms import CheckboxSelectMultiple from .forms import * from django.utils.safestring import mark_safe from django.utils.html import format_html from django.contrib.auth.models import User #from django.contrib.sites.models import Site from django.contrib.auth.models … -
Requested runtime (Python-3.7.3) is not available for this stack (heroku-18)
I'm using django 2.2.3 and I'm getting this error. But, heroku's python-support says that python-3.7.3 should be available in stack heroku-18. runtime.txt contains Python-3.7.3. FULL ERROR Counting objects: 100% (43/43), done. Delta compression using up to 4 threads Compressing objects: 100% (36/36), done. Writing objects: 100% (43/43), 10.70 KiB | 996.00 KiB/s, done. Total 43 (delta 6), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Requested runtime (Python-3.7.3) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed -
How to convert uploaded html file to pdf? (django rest framework)
I have already made html file template in the frontend, and by sending it to the backend I want it to be converted and saved as pdf, I'm newbie in django but I did tried some searching, here's what I found : https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ , If I go with this approach, it will be unnecessary to get multiple data from the user, since the form is very detailed, and frontend is enough to fill. I also did this approach but I don't know what I am missing (https://www.codingforentrepreneurs.com/blog/save-a-auto-generated-pdf-file-django-model) , here is my code so far: (utils.py) from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src): # template = get_template(template_src) # html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(template_src.encode("ISO-8859-1")), result) if not pdf.err: print(pdf) return HttpResponse(result.getvalue(), content_type='application/pdf') return None //============= (models.py) class Questionary(models.Model): date = models.DateField(auto_now_add=True) title = models.CharField(max_length = 100) file = models.FileField(upload_to='Documents/%Y/%m/%d/', blank = False, null = False) def generate_obj_pdf(self): obj = Questionary.objects.get(file=self.id) pdf = render_to_pdf(obj) filename = "YourPDF_Order{}.pdf" %(obj.title) return obj.pdf.save(filename, File(BytesIO(pdf.content))) I expect the html file to be auto converted to pdf, but it still saving it as html. -
Migrate data from django-media-tree to django-filer
We have a DjangoCMS with more than 1000 pages that has been live for many years now and we have been using django-media-tree for a long time, but have now also installed django-filer. I would now like to migrate all of my files from django-media-tree and into django-filer and at the same time, migrate the usage of the files (plugins in articles), so that I eventually can uninstall django-media-tree and make the site look the same for the end user. Has anyone tried to do this and perhaps have some pointers? Maybe someone has written a tool for this already? Regards, Erlend Dalen -
CommandError: No model or app named in elastic search
Here I am creating indices for a django model using django_elasticsearch_dsl but getting error while creating the one. My django app name where the code lies is press_publication django_elasticsearch_dsl = 0.5.1 elasticsearch = 6.6.1 I have tried rebuilding indexes with some already existing indices that working prefectly fine and tried replacing the fields with the new model field and that also working fine. But when creating separate file throwing error. from django_elasticsearch_dsl import DocType, Index, fields from pressads.models import FmPressads posts = Index('fmpressads') @posts.doc_type class FmPadsDocument(DocType): class Meta: model = FmPressads fields = [ 'description_visual', 'cr_qual', 'country', 'agency_cobranch_namelu', 'preprep_cs', 'id_agency_cobranch', 'id_client' ] when running the command python manage.py search_index --rebuild --models=press_publication Actual output is CommandError: No model or app named press_publication Expected output is creating index -
Django - FileField won't upload to database
I'm trying to upload some file with a FileField but when I hit the submit button and run the form.save() I have a new line in my database table but the file I tried to upload is not there. I've been searching for some time to solve my problem but the only thing I've seen is about the enctype="multipart/form-data", but as you can see in the files bellow, I already have it ... views.py class AdminFichiersPhyto(CreateView): template_name = 'phyto/phyto_admin_fichiers.html' model = models.PhytoFile fields = ['general_treatment', 'other'] def form_valid(self, form): print("GONNA SAVE") form.save() if self.request.POST.get('autre'): print("autre") # gonna add some code to read the 'other' file if self.request.POST.get('trtm_gen'): print("traitement généraux") # gonna add some code to read the 'general_treatment' file phyto_admin_fichiers.html {% block forms %} {% if user.is_staff%} <form method="post" action="" enctype="multipart/form-data"> <fieldset> <div style="display: inline-block; margin-left: 22%; text-align: center"><b>Traitements généraux</b>{{ form.general_treatment }}</div> <div style="display: inline-block; text-align: center"><b>Autres traitements</b>{{ form.other }}</div> </fieldset> </form> <p style="margin-top: 2%"> <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Traitements généraux" name="trtm_gen"/> <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Autre" name="autre"/> </p> {% endif %} {% endblock %} forms.py class PhytoFileForm(forms.ModelForm): class Meta: model = models.PhytoFile fields = ['general_treatment', 'other'] def __init__(self, *args, **kwargs): super(PhytoFileForm, self).__init__(*args, **kwargs) models.py class … -
Custom authentication in djangorestframework-jwt
I have two types of user. for one of them which is main user that it's model is available from get_user_model() is ok and the endpoint for that is: Import: from rest_framework_jwt.views import obtain_jwt_token path: path("api/token/", obtain_jwt_token, name="user_jwt") http://127.0.0.1:8000/users/api/token/ Everything is pretty find when I provide my main user credentials for generate token. but for the other type user Teacher it needs some changes in djangorestframework-jwt core codes. I know that it uses username as the default field to login. for main user is Ok, because it takes that this way: username_field = get_user_model().USERNAME_FIELD that in this case is email. I've defined that in model. but for the other type of user it tries to get username this way: def get_username(user): try: username = user.get_username() except AttributeError: username = user.username return username that because the user doesn't have get_username() attribute, because It's a regular model and does not inherit from any model. so I need to edit: username = user.username to username = user.email now when I refer to the custom authentication method it generates the token. but for access/request methods that need Authentication It returns 401 Unauthorized, Invalid signature. What is the problem? How should create a custom authentication … -
Atomic transactions in Django app in a for loop
In my django app I have a celery task which handles user-uploaded XLS file. Its being used to do something like "mass import" of data. In for loop I am processing each row - from each row I want to create one model instance object (so I will have multiple Model.objects.create(...) calls - for one row its possible that I will create multiple objects and its foreign keys). Is is possible in django to have an atomic transaction for whole for-loop? For example, if XLS contains 100 rows - and 90 of them are successful but 91 is not (because data in row is wrong) - is it possible to rollback previous 90 (or more) DB saves? My code looks like: workbook = xlrd.open_workbook(importobject.file.path) worksheet = workbook.sheet_by_index(0) processed_rows = [] omitted_rows = [] print('Mass import rows: ', worksheet.nrows) startrange = 0 if str(worksheet.cell(0, 0).value) == 'header': print('Omit first row as header row') startrange = 1 for rowno in range(startrange, worksheet.nrows): logger.info('Processing row {}:'.format(rowno)) for colno in range(worksheet.ncols): cell = worksheet.cell(rowno, colno) print('Row {}, Col {}:'.format(rowno, colno), str(cell.value)) # process call and row # validate and save object here - if not valid - rollback whole mass import #MyModel.objects.create() -
How to deploy data from Django WebApp to a cloud database which can be accessed by Jupyter notebook such as Kaggle?
I have build a Django WebApp. It has an sql database. I would like to analyze this data and share the analysis using online platform Jupyter notebook such as Kaggle. I have already deployed to Google App Engine as an SQL instance, but I don't know how to view this SQL instance tables in Kaggle. There is an option to view BigQuery databases in Kaggle, but I don't know how to get the data from my SQL instance to BigQuery. -
Using inlineformset_factory with different querysets in CreateView
I am trying to use inlineformset_factory to create instances of the same model. models.py class Skill(models.Model): employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name="employee_skills") technology = models.ForeignKey(Technology, on_delete=models.CASCADE) year = models.CharField('common year using amount ', max_length=4) last_year = models.CharField('Last year of technology using ', max_length=4) level = models.CharField("experience level", max_length=64, choices=LEVELS) class Techgroup(models.Model): """ Group of technology """ name = models.CharField('group_name', max_length=32, unique=True) class Technology(models.Model): """Technologies.""" name = models.CharField('technology name', max_length=32, unique=True) group = models.ForeignKey(Techgroup, on_delete=models.CASCADE, related_name="group") In the Administrator pane I created 2 instances of the Techgroup model: - Framework - Programming language All Skill models belong to one of two groups. On the front I display 2 forms, one containing queryset with instances belonging to the Framework, the other with instances belonging to the Programming language. I divide Querysets using ModelsForm: forms.py class SkillBaseCreateForm(forms.ModelForm): YEAR_CHOICES = [(r, r) for r in range(1, 11)] LAST_YEAR_CHOICES = [(r, r) for r in range(2015, datetime.datetime.now().year + 1)] year = forms.CharField( widget=forms.Select(choices=YEAR_CHOICES), ) last_year = forms.CharField(widget=forms.Select(choices=LAST_YEAR_CHOICES)) class Meta: model = Skill fields = ['technology', 'level', 'last_year', 'year'] class SkillCreatePLanguageForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreatePLanguageForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = Technology.objects.filter(group__name="Programming language") class SkillCreateFrameworkForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreateFrameworkForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = Technology.objects.filter(group__name="Framework") SkillFrameworkFormSet = … -
Problem with custom django admin listview editable field
Django 2.1.2 I've almost successfully added a checkbox to a django admin listview which doesn't link to a field in the underlying model. Instead I want to update fields in the model based on the checkbox value. My code's almost working after reading a post here. My problem is that if I override save() in my form, django breaks somewhere else saying that "'NoneType' object has no attribute 'save'". I have a TrainingSession model with a submitted_date and an accepted_date. The below code shows a checkbox in the listview which defaults to checked if accepted_date is set, and the checkbox is disabled if submitted_date is not set. My plan is then to set the accepted_date to today if you check the checkbox: class TrainingSessionListForm(forms.ModelForm): accept = forms.BooleanField(required=False) class Meta: model = TrainingSession fields = '__all__' def __init__(self, *args, **kwargs): instance = kwargs.get('instance') if instance: initiallyApproved = instance.accepted_date is not None submittedForApproval = instance.submitted_date is not None initial = kwargs.get('initial', {}) initial['accept'] = initiallyApproved self.base_fields['accept'].disabled = not submittedForApproval kwargs['initial'] = initial super(TrainingSessionListForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = kwargs.get('instance') if instance: accepted = self.cleaned_data['accept'] if accepted and instance.accepted_date is None: instance.accepted_date = datetime.date.today() super(TrainingSessionListForm, self).save(*args, **kwargs) class TrainingSessionAdmin(admin.ModelAdmin): list_display … -
How to fix "ModuleNotFoundError: No module named 'DEGNet'"?
I'm trying to "python3 manage.py runserver" on MacOS and get this error. I run the web-application in virtual environment, where Django is installed. The problem appears both on non-virtual environment also. What is DEGNet itself? I can't even find it in directory. Thats what I got after "python3 manage.py runserver" ''' Traceback (most recent call last): File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'DEGNet' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line … -
Import data from sql database into django models
I have SQL database connected with my Django project. I want to import all the data from SQL database into my new created Django models ie I want to import data into new tables created via Django models. -
Accessing Variable from nested loops
I need to access variable from a nested loop in django, but I got empty data instead Here is the piece of code def connections(request): """get service connections from api""" brand_res = requests.get(url+'?method=api.brand_list', auth=HTTPBasicAuth(name, token)) brands = brand_res.json() for key, brand in brands['data'].items(): services = [] service_plans = requests.get( url+'?method=api.service_plan_list&code=SDNCCNNIRTTTT&brand_id='+brand['class_id'], auth=HTTPBasicAuth(name, token)) plans = service_plans.json() if isinstance(plans['data'], dict): """if dict""" for m, plan in plans['data'].items(): """ get all plan_ids""" services_connected = requests.get( url+'?method=client.service_list&plan_id=' + plan['plan_id'], auth=HTTPBasicAuth(name, token)) sho = services_connected.json() services.append(sho) else: """if list""" for plan in plans: print('') print('') print('') return HttpResponse(services) But I have no luck in returning the data to pass in html as json Any ideas? -
Django can't find static folder
I am looking to add a css file to Django but it can't find the static folder. Here is my settings.py file: """ Django settings for opengarden project. Generated by 'django-admin startproject' using Django 2.2.3. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p4(nadg3%7^2raxg3u5rkkk18(1z363dxcyr2cj8znefm+&5$9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'opengarden.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'wx', 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'opengarden.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': … -
how to send payload with identifier using django api rest framework
i'm trying to get a result something like this when someone order more than one product at the same time be able to select different quantities for each product does api can solve this kind of problem ?this the same as subquery in sql how to perform something like this payload = {"identifier":"Order_id", "items":[{"product":"name of item 1","quantity":324},{"item_name":"name of item 2", "quantity":324}]} models.py class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True) quantity = models.IntegerField(default=1) serializer.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = ProductOrder fields = ['product','quantity','ordering'] viewsets.py class CreateOrderSerializer(generics.CreateAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer permission_classes = [] authentication_classes = [] when a customer visit to the restaurant , the cashier be able to fill a receipt,for example (3 pizza with 2 sandwich) then calculate quantities with its prices! -
What does contrib stand for in django? and why?
I am learning Django. I came across the term "contrib" but I don't know what it actually means It obviously seems from the word "contribution" but why is it named like that? Thank you