Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter show default last 30 days
Right now I have a filter that allows me to show objects from a specific date range. It's gotten to the point though where it does not make sense to show the full date range. One always ends up filtering for at least the month or last month. How can this month be set up by default? If you manually pick the dates for, let's say, this month the loaded URL looks as such: http://127.0.0.1:8000/stats/?type=&asset=&symbol=&broker=&date_range_min=2020-10-01&date_range_max= Ideally in the end there could be a quick-select button for [this month | last month | this year] filters.py class StatsFilter(django_filters.FilterSet): associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios) date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry', widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = Trade fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] def get_filterset_kwargs(self, filterset_class): kwargs = super(StatsFilter, self).get_filterset_kwargs(filterset_class) if kwargs['data'] is None: # I've tried just setting a default to a simpler field but have yet to get any results # kwargs['queryset'] = kwargs['queryset'].filter(type='Long') # Is this where I could fitler for the date_range? # kwargs['queryset'] = kwargs['queryset'].filter(date_range= ???) return kwargs -
How to choose a csv file from a number of csv files available in django
I am pretty new to django and python. I have a number of different csv files with same format in my app in django project. I want to choose a particular file using the hyperlink of the project(website). How can I do that? Are there some other methods? -
what is the mean to getting invalid parameter to prefetch_related()
I am getting below error AttributeError: Cannot find 'detail_set' on Article object, 'detail_set' is an invalid parameter to prefetch_related() I want to know that from where this problem is comming. for exapmle:- Is the issue in serializers or in view file? -
Check if row exist in postgresql if not create and insert it
i would like to know if there is a way to check if a row exists in the db, I'm working with an api and I'll be adding a script who will run every 24 hours to collect data from a page wich has data from many companies but if I run the script today and tomorrow for example there's a chance of gather almost the same data with new ones so i need to get rid of those, is a good idea to use COUNT or should i use if statements? I'm adding this json data to my db: { OrgName: name, Direction: Street 123 City: cityname Lat: 13.123123 Lon: 12.123123 Code: XC23-123D } As mentioned before, the data can be repeated in all the keys but not in the code, will code=unique solve the problem? -
ValueError: source code string cannot contain null bytes in django while running python manage.py migrate after inspectdb
I connected my Django with mysql database and ran a sql script to make a database and ran migrations on my django project and I had no errors but to to use the database I had to use python manage.py inspectdb >appname/models.py , after doing this I cleaned my models as it was mentioned in the steps but when I ran python manage.py migrate it gave me this error: MYSQL script create database if not exists payroll_db; use payroll_db; create table m_state(state_code varchar(2) primary key, state_name varchar(30)); create table m_address(address_id integer primary key,building_details varchar(30) NOT NULL, road varchar(20) NOT NULL,landmark varchar(30) NOT NULL, city varchar(30) NOT NULL,state varchar(2) NOT NULL references m_state(state_code),country varchar(30) default 'India'); create table m_company(company_id integer primary key, company_name varchar(50) NOT NULL, building_details varchar(30) NOT NULL, Area Varchar(30), Landmark Varchar(30), City varchar(30), state varchar(2) NOT NULL references m_state(state_code),country varchar(30) default 'India'); create table m_department(company_id integer NOT NULL references m_company(company_id),department_id integer primary key,department_name varchar(30) NOT NULL); create table m_grade(grade_id integer primary key, grade_name varchar(20) NOT NULL); create table m_employee(employee_id integer primary key,employee_name varchar(30) NOT NULL,department_id integer references m_department(department_id),company_id integer NOT NULL references m_company(company_id), building_details varchar(30) NOT NULL, Area Varchar(30), Landmark Varchar(30), City varchar(30), state varchar(2) NOT NULL references … -
python manage.py makemigrations
Hey guys new to coding here. Just started a django python tutorial and when i type into the command: python manage.py makemigrations, it says ModuleNotFoundError: No module named 'products'. I created a model in the models.py 'products' and saved it in the settings.py under the INSTALLED_APPS array. Can anyone help? Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'poducts' -
Django - Will adding or removing an index from a table every create an issue with the database and migrations?
I want to understand if adding or removing indexes from models creates issues with migrations Please indicate if any step(s) cause issues with migrations A) On Day One I create the following model class Person(models.Model): person_name = models.CharField(max_length=50) create_date = models.DateTimeField() country = models.ForeignKey(Country, on_delete=models.CASCADE) run migrate and makemigrations commands B) 20,000 records of data are added for the Person model C) I add an index to the person_name field class Person(models.Model): person_name = models.CharField(max_length=50, db_index=True) create_date = models.DateTimeField() country = models.ForeignKey(Country, on_delete=models.CASCADE) run migrate and makemigrations commands D) I remove the index from the person_name field class Person(models.Model): person_name = models.CharField(max_length=50) create_date = models.DateTimeField() country = models.ForeignKey(Country, on_delete=models.CASCADE) run migrate and makemigrations commands -
How can I put JSON from my Javascript code to my Django server?
I want to put JSON from my Javascript code to my Django server. I made test folder and it has test.js and test.html. I wrote test.js var info = [ { "name": "key", "pass": "123", }, ]; console.log(info); const csrftoken = Cookies.get("csrftoken"); var xhr = new XMLHttpRequest(); var userjson = JSON.stringify(info); xhr.open("POST", "http://127.0.0.1:8000/app/index/"); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.send(userjson); and I wrote test.html <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script type="text/javascript" src="test.js"></script> </head> <body> <p>TEST</p> </body> </html> I wrote views.py of app like @csrf_exempt def index(request, data, status=None): json_str = json.dumps(data, ensure_ascii=False, indent=2) print(json_str) return render(request, 'app/top.html') I wrote urls.py of app like urlpatterns = [ path('index/', views.index, name='index'), ] My settings.py is INSTALLED_APPS = [ ・・・ 'corsheaders', ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:8000', 'http://127.0.0.1:8000', ) I run this Django server and accessed http://127.0.0.1:8000/app/index/.I checked index method was called.However when I load test.html, console.log(info) was read but "Access to XMLHttpRequest Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https. " error happened. Also "POST file://Users/test/127.0.0.1:8000/app/index/ net::ERR_FAILED" error happened.Furthermore in Django server,TypeError: index() missing 1 required positional argument: 'data' error happened. I already installed CORS Unblock(https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino) in Google … -
Auth0 LOGIN URL 404 Not found
Reposting from https://community.auth0.com/t/login-url-404-not-found/52181 Ive setup an auth0 app. I am trying to setup an auth webapp flow and code authorization flow as well; I am following this article: https://auth0.com/docs/quickstart/webapp/django to implement Auth0 web app flow. To implement backend code authorization flow im following: https://auth0.com/docs/quickstart/backend/django Implementations are in this file: apps/auth_zero/auth0backend.py to write both the standard web app flow and the code authorization flow. which subroutes /login/auth0 as auth0/login/auth0; check the main app urls. But I get 404 not found when i Press Login: Ive setup an auth0 app. I am trying to setup an auth webapp flow and code authorization flow as well; I am following this article: https://auth0.com/docs/quickstart/webapp/django to implement Auth0 web app flow. To implement backend code authorization flow im following: https://auth0.com/docs/quickstart/backend/django Implementations are in this file: apps/auth_zero/auth0backend.py to write both the standard web app flow and the code authorization flow. which subroutes /login/auth0 as auth0/login/auth0; check the main app urls. But I get 404 not found when i Press Login: I suspect something must be wrong in my settings; The repo for ref is: https://github.com/Xcov19/covidX/tree/1777fe574c640c31db587e361c32758bc0c175d2/covidX this is my middleware: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", # Map username from the Access Token payload to # … -
How do i solve this error : django.db.utils.IntegrityError: NOT NULL constraint failed
I'm writing unit tests for my wishlist button/view and I'm trying to check if my book ISBN and the userID is added to the wishlist after I press the button. I've tried it but it keeps giving me the error stated in the title. Here's my code: #tests.py class wishlist_view_test(TestCase): @classmethod def setUpTestData(cls): books.objects.create(ISBN = "976354890", bookName = "testingbook1", bookVersion = "1",bookAuthor = "Carlie Presley", bookPublisher = "TeamBananaMonkey1") retailer.objects.create(retailer= "Amazon", sellerID = 1) retailer_book.objects.create(condition = "new", reviews = "4.5", ID= 1, bookType = "hardcover", ISBN_id= "976354890", sellerID_id = 1, price = 177.98) def test_wishlist_button(self): user = User.objects.create_user(username='user1', password='djangolife') self.client.login(username='user1', password='djangolife') response1 = self.client.post(reverse('TextSearch:wishlist',args=("976354890",))) self.assertEqual(str(wishlist.objects.filter(userid_id= user.id),'<QuerySet [..........]>') #html code <form action="{% url 'TextSearch:wishlist' book.pk %}" method="post"> {% csrf_token %} <input type="hidden" value="{{book.pk}}" name="isbn"> <input type="submit" value="Add to wishlist★"> #views.py class wishlistView(TemplateView): template_name = 'TextSearch/wishlist.html' model = wishlist def post(self, request, pk): isbn = self.request.POST.get('isbn') current_user = request.user book = wishlist(userid_id = current_user.id, ISBN_id = isbn) book.save() return render(request, 'TextSearch/wishlist.html') #models.py class wishlist (models.Model): userid = models.ForeignKey(User, on_delete= models.CASCADE) ISBN = models.ForeignKey(books, on_delete = models.CASCADE) I'm using Django's built-in user model. -
Streamfields wagtail streamform can I add WagtailFormBlock to a different block?
I wanted to include a form in another block class HomeBannerBlock(blocks.StructBlock): background_image = CorrectImageBlock( label = 'Background Image' ) header = HeaderBlock( label="Banner Header", max_length=120, ) text = blocks.CharBlock( label = 'Banner Text', max_length=240, ) form = WagtailFormBlock() class Meta: #noqa template = 'streamfields/home_banner.html' icon = 'square' I was hoping it would pass a {{ form }} that I could loop through in the home_banner.html template. {{ form }} = nothing {{ value.form }} = StructValue([('form', <Form: Provider Sign Up Form>), ('form_action', ''), ('form_reference', '65fa1d39-c603-4537-8c16-245055b3516e')]) {{ value.form.form }} = <Form: Provider Sign Up Form> these will not print a form. If I loop through {{ value.form.form.fields }} it will output the label and value of the field label and help text it a definition table but it will not print the input. Is it possible to use Streamforms like this? -
I am trying to store my media files in google drive. The application is not showing any error other than images are not showing on my web page
This is my setting.py: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'jobs', 'gdstorage', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'static') GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE = os.path.join(BASE_DIR,'Api_key.json') GOOGLE_DRIVE_STORAGE_MEDIA_ROOT = '/media/' GOOGLE_DRIVE_STORAGE_SERVICE_EMAIL = 'myaccount.iam.gserviceaccount.com' GOOGLE_DRIVE_STORAGE_KEY = '555e8bc_My_Storage_Key_aa4375f' This is my models.py: from gdstorage.storage import GoogleDriveStorage # Define Google Drive Storage gd_storage = GoogleDriveStorage() ... image = models.ImageField(upload_to='images', storage=gd_storage) I am trying to show my media files on my home page but the images are not loading. Thanks in advance. -
charfield and foreignkey without null=True in Django
I have a django project with multiple apps. There are some models in two apps. What I would like to know is how can I makemigrations and migrate without having to pass null=True and default=some_value for some models only in my local environment. This is required because in production these fields should not be null and some value will be passed based on the client requirements. So whenever I create a new model in the said apps I am getting errors while makemigrations for these fields to provide some default value. I am using postgresql. So if I provide some default values in my local database in postgresql will django ignore these errors or is there some way to do this so that I do not have to pass the null value everytime I migrate in my local environment? At present I am passing null values before I migrate in my local environement and delete them before pushing the code to github. -
Dynamic exec Django
Good day people! I have 3 forms that perform 3 different operations. The task is to make a single class to handle forms dynamic. I was briefly explained that I need 2 tables. It will take the number of variables from the first table, and the names of variables from the second table. Next, it collects data in an array and passes it as an input parameter to the operation being performed. models.py from django.db import models from SqlApp import greats class DForm(models.Model): create_choices = ( ('LOAN', 'Создать кредитный договор'), ('ACC', 'Создать банковский счет'), ('DEPO', 'Создать депозитный договор') ) choose_procedure = models.CharField(max_length=4, verbose_name='Выберите процедуру', choices=create_choices) def __str__(self): return self.choose_procedure class Acc(models.Model): oper_date = models.CharField(max_length=10, verbose_name='Операционная дата') instance = models.CharField(max_length=10, verbose_name='Инстанция') iin = models.CharField(max_length=12, verbose_name='ИИН клиента') dcl_code = models.CharField(max_length=10, verbose_name='Шаблон продукта') val = models.CharField(max_length=10, verbose_name='Валюта') specfl = models.CharField(max_length=10, verbose_name='Признак спец.счета') def save(self, *args, **kwargs): greats.createAcc(self.oper_date, self.instance, self.iin, self.dcl_code, self.val, self.specfl) class Loan(models.Model): oper_date = models.CharField(max_length=10, verbose_name='Операционная дата') instance = models.CharField(max_length=10, verbose_name='Инстанция') iin = models.CharField(max_length=12, verbose_name='ИИН клиента') dcl_code = models.CharField(max_length=10, verbose_name='Шаблон продукта') pcn = models.CharField(max_length=10, verbose_name='Процентная ставка') pday = models.CharField(max_length=10, verbose_name='День месяца погашения') def save(self, *args, **kwargs): greats.createLoan(self.oper_date, self.instance, self.iin, self.dcl_code, self.pcn, self.pday) class Depo(models.Model): oper_date = models.CharField(max_length=10, verbose_name='Операционная дата') instance = … -
Why is this django test is failing?
Whenever I run my test.py I get: (blog-1rz6wx-6) λ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). .F.. ====================================================================== FAIL: test_post_detail_view (blog.tests.BlogTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\ **** \Desktop\blog\blog\tests.py", line 40, in test_post_detail_view self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 4 tests in 0.776s FAILED (failures=1) Destroying test database for alias 'default'... My test.py code: def test_post_detail_view(self): response = self.client.get('/post/1/') no_response = self.client.get('/post/100000') self.assertEqual(response.status_code, 200) self.assertEqual(no_response.status_code, 404) self.assertContains(response, 'A good title') self.assertTemplateUsed(response, 'post_detail.html') urls.py that is in the same folder as settings.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), ] And the urls.py that is located in the same folder as views.py: from django.urls import path from .views import BlogListView, BlogDetailView urlpatterns = [ path('post/<int:pk>', BlogDetailView.as_view(), name = 'post_detail'), path('',BlogListView.as_view(),name = 'home') ] I have no Idea, and when I changed the response to response = self.client.get(''), it does come up with code 200, but the TemplateUsed obviously becomes 'home.html. Thanks beforehand. -
Which frameworks to generate CRUDs on mobile?
I'm building a web app to manage inventory. The simplified model looks like: Client(clientId, name, address, email, etc) Auditor(auditorId, email, etc) Product(productId, name, description, unit, cost, etc) InventoryDataEntry(entryId, productId, nbUnits, inputDate) A Client needs to input entry in his inventory daily: "as of today, I have 10 kg of apples" An Auditor need to verify the inventory stock monthly: "as of today, clientId 123ABC has 10 kg of apples" I need a role-based system: a client can only input data in his own inventory while an auditor can input data for any client. I will need to display graphs to show the evolution of stocks over time. I'm thinking of using Django for the back-end and services. I like the django-admin interface. HOWEVER, I need to make the web app usable thru mobile and I'm very rubbish at front-end dev. I looked at solutions such as react-native which looks great. I'm wondering if there were any solutions that could provide a django-admin like interface (generating all the CRUDs + permissioning) for a mobile web app. -
django modelformset_factory not validating because * id * Select a valid choice, That choice is not one of the available choices
MY view receives a model modelformset_factory from the template, but it doesn't pass validation, claiming that * id * Select a valid choice. That choice is not one of the available choices. Here is a simplified version of my view: def menuuser(request): user_role = DesignationForm() #formset = modelformset_factory(SbTitle, fields=('title', 'permission'), max_num=0) sbtitle_form = SbTitleForm(queryset=SbTitle.objects.all()) sbitleelement_form = SbTitleElementForm(queryset=SbTitleElement.objects.all()) if request.method == 'POST': user_role_id = request.POST['designation_selection'] sbtitle_form = SbTitleForm(request.POST, queryset=SbTitle.objects.all()) sbitleelement_form = SbTitleElementForm(request.POST, queryset=SbTitleElement.objects.all()) if sbtitle_form.is_valid() and SbTitleElementForm.is_valid(): bla...... context = { 'user_role':user_role, 'sbtitle_form':sbtitle_form, 'sbitleelement_form':sbitleelement_form, } return render(request, 'admins/user_role/user_permission.html', context) And here is my template: {% extends 'base/base.html' %} {% load static %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} {{ sbtitle_form.management_form }} {{ sbitleelement_form.management_form }} <div id="DataTables_Table_2_wrapper" class="dataTables_wrapper no-footer"> <div class="datatable-header"> <div class="form-group row"> <label class="col-md-4 col-form-label"><span><h5>Select User Role For Menu Permission:</h5></span></label> <div class="col-md-5">{{ user_role.designation_selection }}</div> </div> </div> <div class="datatable-scroll"> <table class="table table-bordered table-hover datatable-highlight dataTable no-footer" id="DataTables_Table_2" role="grid" aria-describedby="DataTables_Table_2_info"> <thead> <tr role="row" class="bg-teal-400"> <th class="sorting text-center h5" tabindex="0" aria-controls="DataTables_Table_2" rowspan="1" colspan="1" aria-label="Job Title: activate to sort column ascending">Sidebar Title</th> <th class="sorting text-center h5" tabindex="0" aria-controls="DataTables_Table_2" rowspan="1" colspan="1" aria-label="DOB: activate to sort column ascending">Sidebar Title Element</th> </tr> </thead> <tbody> {% for field in sbtitle_form %} … -
How do I connect a model instance to a user in django?
Im looking to make it so the logged in user that creates a profile is linked to their guestprofile model when they create their profile. When I create the guest profile while logged in, it successfully creates the guest profile, but in the guest profile admin screen there is no user connected to the guest profile model created. Instead there is a dropdown menu listing all users, which makes the connection process manual. Thanks. views.py class AddProfileView(CreateView): model = GuestProfile form_class = AddProfileForm template_name = 'profilemanip/addprofile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user Forms.py class AddProfileForm(forms.ModelForm): name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) location = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) summary = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class': 'form-control'})) profile_pic = forms.ImageField() class Meta: model = GuestProfile fields = ('name', 'location', 'summary', 'profile_pic') Models.py class GuestProfile(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) location = models.CharField(max_length=100) summary = models.TextField(max_length=350) profile_pic = models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return str(self.user) -
Run functions inside model.py - Django
I want to execute the function named Average_Health() inside models.py to insert it's i.e. Average_Health()returned value. I don't want to execute the function inside views.py because there's such a condition that several views.py will this same task. It's just a sample code to understand: class myModal(models.Model): name = models.CharField(max_length=150, null=True) earning = models.IntegerField(max_length=150, default=1600) def Average_Health(): return (earning-2500) health = models.IntegerField(max_length=1000, default=Average_Health()) -
Django renders an "in exception" page instead of a page that can help debugging
I don't know why but recently whenever I get an error I don't see any helping messages in the terminal and all what I see in my browser is an empty page with "in exception" text And now my only way of debugging is to through multiple print statements and see where my code crashed. Does anyone know why Django suddenly became very useless?! The page I get when an error occures look like this I spend literally 2 hours trying to find out why my page wasn't rendering to find out that I forgot to place ".html" extension at the end of rendering! Why Did Django Suddenly Became Useless?! -
Nested Json is not being serialized while using Multipart Parser
I will try to give a small example and tell where it's not working. The models are as follows, class Address(models.Model): name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) class Meta: managed = True db_table = 'Address' class Product(models.Model): title = models.CharField(db_column='title', max_length=200, blank=False, null=False) imageUrl = models.ImageField(db_column='image_url', blank=True, null=True, upload_to='deals/%Y/%m/') addresses = models.ManyToManyField(Address, related_name='product_addresses') class Meta: managed = True db_table = 'Product' The serializers class AddressSerializer(BaseSerializer): id = serializers.IntegerField(required=False) name = serializers.CharField(required=False) class Meta: model = Address fields = ['id', 'name'] class ProductSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) title = serializers.CharField(required=False) addresses = AddressSerializer(many=True, required=False) def create(self, validated_data): locationData = get_popped(validated_data, 'addresses') instance = Product.objects.create(**validated_data) self.createLocation(locationData, instance) return instance def createLocation(self, locationData, instance): location_ids = [] if locationData is not None: for item in locationData: if 'id' in item: location_ids.append(item.get('id')) addresses = Address.objects.filter(id__in=location_ids) for loc in addresses: instance.addresses.add(loc) instance.save() def update(self, instance, validated_data): print(validated_data) addressData = get_popped(validated_data, 'addresses') if addressData is not None: instance.addresses.clear() self.createLocation(addressData, instance) super(self.__class__, self).update(instance, validated_data) return instance class Meta: model = Product fields = ['id', 'addresses', 'title', 'imageUrl'] My views, class ProductViewSet(viewsets.ModelViewSet): pagination_class = CustomPagination serializer_class = ProductSerializer parser_classes = (MultipartJsonParser, parsers.JSONParser) queryset = Product.objects.all() class AddressViewSet(viewsets.ModelViewSet): pagination_class = CustomPagination serializer_class = AddressSerializer queryset = Address.objects.all() And the … -
How to Create a Dependent dropdown in django without form or ajax
I want to create a dependent dropdown in django restframework without using forms and ajax. -
Django DRF AttributeError: Got AttributeError when attempting to get a value for field `added_email` on serializer `UserMailListSerializer`
ps. I'm sorry that the sentences are weird because I'm not familiar with English. An error occurs when you add an email to your mailing list. error message AttributeError: Got AttributeError when attempting to get a value for field `added_email` on serializer `UserMailListSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'added_email'. After AttributeError, the database contains the values you want to save correctly, and after refresh, check the mailing list with Get to get the values. Errors seem to occur only when added to the list. Model.py class UserAccountManager(BaseUserManager): """ model manager """ def create_user(self, email, name, password=None): """ create user """ if not email: raise ValueError("valid email") user = self.model(email=self.normalize_email(email), name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password=None): """ create admin """ user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): """ user account model """ email = models.EmailField(unique=True, verbose_name='email') name = models.CharField(max_length=20, verbose_name='username') created_at = models.DateTimeField(auto_now_add=True, verbose_name='subscription_date') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] class Meta: db_table = 'accounts' def … -
How do I make all posts that share a category appear on a page in Django
How do I make the page list all posts that that share the same category id. I have the category titles as a separate "foreign key" model. My goal is to be able to type in my url so that I have the category id at the end and it shows me all the posts that have the specific category id. """models.py""" class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() def __str__(self): return self.name def get_absolute_url(self): return reverse('post-category', kwargs={'pk': self.pk}) class HelpPage(models.Model): title = models.CharField(max_length=100) content = models.TextField(default="test") date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) product = models.CharField(max_length=100) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) """views.py""" class CategoryDetailView(DetailView): model = Category context_object_name = 'category' template_name = 'blog/categories.html' """urls.py""" from .views import ( CategoryDetailView,) urlpatterns = [ path('category/<int:pk>', CategoryDetailView.as_view(), name='post-category'),] """categories.html""" {% extends "blog/base.html" %} {% block content %} Category name: {{ category.name }} {% for post in category.post_set.all %} post: {{ post.title }} {% endfor %} {% endblock content %} categories.html -
How to sort cart items in order
I am building a Django e-commerce website and as I was working on my cart functionality I noticed that every time I try to change the quantity of a specific item in the cart, all the items in the cart are re-sorted in a different order. I was wondering if there's any way I can sort the items in the backend before they are displayed. ** I am getting this error only when the user is "Authenticated" ** Guest checkout is working correctly This is my cart Views.py def cart(request): # Authenticated Checkout if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) cartItems = order.get_cart_items items = order.orderitem_set.all() if cartItems == 0: context = {"items": items, "order": order, "cartItems": cartItems} return render(request, "cart_empty.html", context) #Guest Checkout else: data = cartData(request) cartItems = data["cartItems"] order = data["order"] items = data["items"] if cartItems == 0: context = {"items": items, "order": order, "cartItems": cartItems} return render(request, "cart_empty.html", context) context = {"items":items, "order": order, "cartItems":cartItems} return render(request, "cart.html", context) def update_cart(request): data = json.loads(request.body) productId = data["productId"] action = data["action"] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == "add": orderItem.quantity = (orderItem.quantity …