Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
@property doesn't store value in DB
My model is like this: class Cart(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(null=False,blank=False) total = models.FloatField(null=False,blank=False) @property def total(self): return self.quantity * self.product.price The total appears in my admin dashboard but when I inspect the db from the shell I don't get the total value, I get the other values: <QuerySet [{'id': 42, 'product_id': 11, 'quantity': 2}]> Expected output: <QuerySet [{'id': 42, 'product_id': 11, 'quantity': 2, 'total': 29.00}]> -
django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded:
this is the Databases code in 'settings.py': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'proj_15db', 'USER': 'root', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '3306', } } After typing "manage.py makemigrations" successfully i then type "manage.py migrate" the following error occured : all the essential code has been done successfully but when i try to migrate this following happens Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\db\backends\mysql\base.py", line 234, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\MySQLdb\connections.py", line 179, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Django_Class\proj_15\manage.py", line 22, in <module> main() File "D:\Django_Class\proj_15\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, … -
how can i contact us page to django
Save all the contact us inputs on the database, and create a view to handle all the records. Tasks include Search and sort: based on the user entries like the services, or the email, phone number, names etc. Delete: records with irrelevant information to be removed/fake/false records to be removed Insert:: new records to be inserted when a new entry is submitted how to perform these tasks -
One Django view, multiple urls and apps
I have a small newsletter signup form at the footer of every page. The footer is part of base.html. I use Ajax to submit the form. Right now Ajax code calls a view defined in app1 and the corresponding URL is defined in the urls.py of the same app. Here's the AJAX code (this code is saved in a separate js file and included in the base.html): $('#newsletterForm').submit(function(e){ e.preventDefault() $('#loader').css("display", "block") $.ajax({ type : "POST", url : "/subscribe/", data : { subscriber_email : $('#e-mail').val(), csrfmiddlewaretoken : csrftoken, datatype : "json", }, success: function(){ $('#loader').css("display", "none"), $('#subscribed').css("display", "block"), $('#subscribed').delay(3000).fadeOut("slow") }, failure: function(){ alert('An error has occurred. Please try again.') }, }); }); The view (defined in app1): def subscribe(request): if request.is_ajax(): subscriber = Subscriber(email=request.POST.get('subscriber_email')) subscriber.save() return JsonResponse({}, status=200) else: return redirect('homepage:index') The URL (defined in app1): path('subscribe/', views.subscribe, name='subscribe'), Now, the problem is when I'm in app2, Django looks for /subscribe/ in that app which doesn't exist. So is there any way to solve this issue or I have to include /subscribe/ in urls.py and views.py of every app? -
django css has an issue with -ms-filter
enter image description here hey, so I have been making this Django app and when I run this, I can see errors with the ms-filter used with the message in the pic. please help me correct it. -
FOREIGN KEY constraint failed - can't remove from admin - Django
I want to remove data from admin but I am getting error Traceback (most recent call last): File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 1735, in changelist_view response = self.response_action(request, queryset=cl.get_queryset(request)) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 1402, in response_action response = func(self, request, queryset) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\actions.py", line 39, in delete_selected modeladmin.log_deletion(request, obj, obj_display) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 843, in log_deletion return LogEntry.objects.log_action( File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\models.py", line 29, in log_action return self.model.objects.create( File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 447, in create obj.save(force_insert=True, using=self.db) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 790, in save_base updated = self._save_table( File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 933, in _do_insert return manager._insert( … -
Add Product by Category in Django
I am trying to insert my product by category in django. I have two model Product and Category. I want to add Product in Product table.when I add product category comes in select box and select category. Category id in category value. which is insert in product table. Category is ForeignKey. But show this error: Cannot assign "<QuerySet [<Category: Mixeur>, <Category: Hachoir>, <Category: Batteur>]>": "Product.category" must be a "Category" instance. model.py: from django.db import models from django.forms import ModelForm class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): label = models.CharField(max_length=50) description = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() def __str__(self): return self.label view.py : def add_product(request): print(request.POST) p_category = Category.objects.all() if request.method == 'POST': label = request.POST['label'] description = request.POST['description'] quantity = request.POST['quantity'] category = request.POST['category'] data = Product( label=label, description=description, quantity=quantity, category=p_category ) data.save() return HttpResponseRedirect('/products/') else: form = AddProduct() return render(request, 'product/add_product.html', {'form': form, 'p_category':p_category}) add_product.html <form action="/add-product/" method="post"> {% csrf_token %} <label for="label">Label: </label> <input id="label" type="text" name="label" value=""> <label for="description">Description: </label> <input id="description" type="text" name="description" value=""> <label for="quantity">Quantity: </label> <input id="quantity" type="text" name="quantity" value=""> <select class="form-control mb-4" name="category"> <option selected disabled>Select Category</option> {% for cat in p_category %} <option value="{{cat.id}}">{{cat.name}}</option> … -
Query Optimization and profiling for celery tasks
Django-debug-toolbar and Django-silk are two famous tools for profiling HTTP requests. Is it possible to analyze a celery task or any other function inside the code? for instance, I have a celery task like this: def main_task(): while _condition: logic() sleep(_t) return True I need some information like duplicate and similar queries in logic() for every loop. -
How can I Access _id field on djongo model it returns None
This code creates a User document class UserManager(BaseUserManager): def create_user(self, name, email, password, mobile_number, alias=None): user = self.model(email=self.normalize_email(email)) user.name = name user.mobile_number = mobile_number user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_staff() user.is_superuser = True user.save() return user This is the User Model it uses the djongo models classes class User(AbstractBaseUser): _id: ObjectIdField(primary_key=True) email = EmailField(null=False, unique=True) name = CharField(max_length=30) mobile_number = CharField(max_length=10, unique=True) is_active = BooleanField(default=True) is_staff = BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" class Meta: db_table = "login" user = User() user.email = 'test@mail.com user.name = 'name' user_mobile_number = '7894561236' user.save() print(user._id) ->None accessing user id this way returns None user.name = 'newname' user.save() #this creates a new instance of document -
django apiview form not showing up
models.py from django.db import models from datetime import datetime class Song(models.Model): title = models.CharField(max_length=64) audio_file = models.FileField() genre = models.CharField(max_length=64) created_at = models.DateTimeField(default=datetime.utcnow) serializers.py from rest_framework import serializers from . import models class SongSerializer(serializers.ModelSerializer): class Meta: model = models.Song fields = '__all__' views.py from . import models, serializers from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.views import APIView class SongView(APIView): def get(self, request, format=None): serializer = serializers.SongSerializer(models.Song.objects.all(), many=True) return Response(serializer.data) class PostSong(APIView): # The issue <---------------- def post(self, request, format=None): song = request.data.get('song') serializer = serializers.SongSerializer(data=song) if song.is_valid(): serializer.save() return Response({'OK':'Song Uploaded'}, status=status.HTTP_200_OK) return Response({'Bad Request': 'Invalid Data'}, status=status.HTTP_400_BAD_REQUEST) urls.py from django.urls import path from . import views urlpatterns = [ path('songs/', views.SongView.as_view(), name='songs'), path('add-song/', views.PostSong.as_view(), name='add-song') ] The SongView works perfectly fine and PostSong works too but the form is not showing up, I can only post data via json so I am not able to upload the audio file, how can I fix this? -
Django ORM and Azure SQL
Student programmer here! so go easy... My team and I are building a web app with Django that centres around creating a structured database, inserting data that has been extracted from PDF's, and enabling users to view records in the database. Its for an archeology department for their paper based archive that needs to be digitized. First time Django and Azure user, so I don't fully understand how/if they fit together. I've begun coding the models.py file to create the models. Do we also need to set up Azure SQL to store the db? Or is it completely managed by Django, seeing as it has its on backend interface? Basically, is ORM just used to initialise the database and for accessing the objects, but something still needs to be set up on Azure specifically for the database? Thanks in advance -
Connecting MongoDB database with django by djongo
My app was using PostgreSQL then I tried to connect with MongoDB Database but the collections didn't appear in it after migration?! DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'NoSQL_Blog', } } -
Cloudflare GraphQL API With Python Authentication Error
I am trying to build a website statistics app with Cloudflare APIs and Python Django. def website_metrics(request): cf_graphql = CloudFlare.CloudFlare( email=settings.CLOUDFLARE_EMAIL, token=settings.CLOUDFLARE_API_TOKEN ) query = """ { viewer { zones(filter: {zoneTag: "zone_id_placeholder"}) { firewallEventsAdaptive(limit: 10000, filter: {date: "2021-07-22"}) { action clientCountryName clientAsn clientASNDescription clientIP clientRequestScheme clientRequestHTTPHost datetime userAgent } httpRequests1dGroups(limit: 10000, filter:{date: "2021-07-22"}) { sum { threats } dimensions { date } } } } } """ try: r = cf_graphql.graphql.post(data={'query':query}) except CloudFlare.exceptions.CloudFlareAPIError as e: exit('/graphql.post %d %s - api call failed' % (e, e)) return HttpResponse(template.render(context, request)) The code I've got above is mostly taken from the example_graphql.py script from the python-cloudflare package repository, here. This code is returning an authentication error: SystemExit: /graphql.post 10000 Authentication error - api call failed. I can confirm that the Zone ID, Cloudflare Email address and API keys are correct. Running the same GraphQL query in GraphiQL succeeds and returns the actual metrics. What am I doing wrong here? -
Is it a good to make an industrial project in IoT using Django on the server side
I'm attempting to make an industrial project in IoT which contains thousands of devices and I'm thinking of using Django on the server side of it. Does anyone think it's a good idea? (1)I am looking at (IOT and DJANGO) and also (IOT and node.js). (2)For me I may used DJANGO, because I use python a lot. But looking at node.js plugins, its hard to not select this package. -
how to serialize properly in perticular format
Please help me improve my code.. im newly placed and learning things i want to display separately product field in my code just like category and sub-category in my code but i don't know how to. Also please point out if there anything that i can improve in my code Here is my output: [ { "Category": { "c_id": 1, "parent_id": 15 }, "Sub_category": { "sc_id": 1, "is_active2": 1 }, "p_id": 2, "group_id": "", "product_name": "Fruit", "is_prescription_needed": 1, }] Whereas my expected format is: [ { "Category": { "c_id": 1, "parent_id": 15 }, "Sub_category": { "sc_id": 1, "is_active2": 1 }, "Product": { # How do i separate this "Product" key and value "p_id": 2, "group_id": "", "product_name": "Fruit", "is_prescription_needed": 1 }] here is my code: Serialziers.py class ProductCategorySerializer(serializers.ModelSerializer): c_id = serializers.SerializerMethodField() category_image = serializers.SerializerMethodField() class Meta: fields = ["c_id","parent_id","category","category_image","is_active"] model = Category def get_c_id(self,obj): return obj.id def get_category_image(self,obj): return obj.image class ProductSubCategorySerializer(serializers.ModelSerializer): sc_id = serializers.SerializerMethodField() is_active2 = serializers.SerializerMethodField() class Meta: fields = ["sc_id","sub_category","is_active2"] model = ProductSubCategory def get_sc_id(self,obj): return obj.id def get_is_active2(self,obj): return obj.is_active class ProductSerializer(serializers.ModelSerializer): Category = ProductCategorySerializer(source='category', read_only=True) Sub_category = ProductSubCategorySerializer(source='sub_category', read_only=True) product_image = serializers.SerializerMethodField() p_id = serializers.SerializerMethodField() class Meta: fields = ["Category","Sub_category", "p_id", "group_id", "product_name", "is_prescription_needed", "product_description", … -
Django Send Selenium Exception Message in Template
Hello All I am pretty new to Django Web Framework. I tried creating bot to fill form and the website sometimes changed I want to handle NoSuchElementException and send my custom Error message in django template I dont know how to do it def upload(request): if request.method == "POST": uploaded_file = request.FILES['csv_document'] fs = FileSystemStorage() read = csv.reader(codecs.iterdecode(uploaded_file, 'utf-8')) for row in read: try: time.sleep(3) select = Select(driver.find_element_by_xpath("//select[@formcontrolname='clientDealerType']")) select.select_by_visible_text(row[0]) except NoSuchElementException as e: print('Could not locate element with visible text {}'.format(e)) return render(request, 'upload_csv.html') I want to send exception message in template. I don't have much thing in my template here is my template <!DOCTYPE html> {#{ % load#} <html lang="en"> <head> <meta charset="UTF-8"> <form></form> <title>Title</title> </head> <body> <h1>upload</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="csv_document" /> <button type="submit">Upload a file</button> </form> </body> </html> Any hint will be helpful. Thank you. -
Django Rest Framework - Is it possible to edit the required POST request JSON structure and still use the ViewSet w/ Mixins?
First off, please excuse my mediocrity as I have very recently started working with Django and DRF and I'm still getting the hang of it. I have created a REST API and I've got 2 models, Chat and Conversation. class Conversation(models.Model): def __str__(self): return str(self.id) class Chat(models.Model): payload = models.TextField() userId = models.CharField(null=True, max_length=10) utc_time = models.DateTimeField(default=now) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='chats', null=True) def __str__(self): return self.payload My goal is to be able to create a new chat inside a conversation using a POST request at myapi/chat/, like so: { "conversationId": 1, "chat": { "payload": "Payload test", "userId": 3 } } So if you POST this JSON, a new chat with the corresponding payload would be created inside the existing conversation with the id = 1, and the id of the newly created chat would be returned as a response. My issue is, despite looking inside the DRF documentation, I am still very confused about how to choose what fields should be passed inside the JSON in order to respect the JSON structure above. I am currently using the following GenericViewSet with the following Mixin(s?) for the Conversation and Chat, as I have found it much easier and cleaner to … -
How can I make a field in Django models that concatenates a specific string to each record's id?
I have made a field facility_id in Django models that should concatenate a specific string "ACCTS-" on the left with each record's id on the right, My model class is below: class Facility(models.Model): ... id = models.BigAutoField(primary_key=True) facility_id = models.CharField(max_length=50, default=print(f'{"ACCTS-"}{id}'), editable=False) ... I want to the facility_id field to be storing special and readable human friendly facility_id's of the form: ACCTS-1, ACCTS-2, ACCTS-3, ... corresponding to each individual id. The migrations didn't throw any errors, however When I try to create the records for this table in the Django Admin, am getting an IntegrityError of: IntegrityError at /admin/ACCTS_CLYCAS/facility/add/ NOT NULL constraint failed: ACCTS_CLYCAS_facility.facility_id How do I fix this problem, or what could be the easiest way to implement my problem. -
append data in list in django template
I want to create a list and append data within for loop in django template. How can i do this I try this but not working @register.simple_tag def appendDataInList(list_data, add_data): print(list_data, add_data) if list_data is not None: return list_data.append(add_data) return list_data In my view i have set a list like this return render(request, self.template_name, {'list_data' : [] } ) And in template {% for value in data %} {% appendDataInList list_data value.order_id as list_data %} {% endfor %} When i want to print this list out of loop {{ list_data }} #it give me only one result in list why? -
Django Form request.POST.get() returns none value
Here is my Django if request.method == 'GET': term = request.POST.get('term') grade = request.POST.get('grade') year = request.POST.get('year') Here is my HTML code <form method="GET"> <label><b>Term</b></label> <input type="text" name='term' id='term' placeholder="Ex:Term3"> <label><b>Grade</b></label> <input type="text" name='grade' id='grade' placeholder="Ex:Grade 11A"> <label><b>Year</b></label> <input type="number" name='year' id="year" placeholder="Ex:2021"> <button type="submit" class="btn btn-primary"><a href="{% url 'prediction'%} ">Search</a></button> </form> but term year and grade always show empty Any one cam help me -
Django UpdateView AttributeError 'UserPostUpdateView' object has no attribute 'publish'
I get the error when I try to save the form after editing. If I override get_context_date(currently commented out), I get the error when loading the form. I've looked at the documentation and previous questions with this problem. Those who ran into this had overridden post() which I have not. So I have no idea why this is happening and how to solve it. Would appreciate any help. Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create/my_collideas/2021/7/28/title-2-by-user2/edit/ Django Version: 3.2.4 Python Version: 3.8.2 Installed Applications: ['home', 'search', 'userauth', 'blog', 'menus', 'contact', 'create', 'wagtail.contrib.forms', 'wagtail.contrib.modeladmin', 'wagtail.contrib.redirects', 'wagtail.contrib.table_block', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'allauth', 'allauth.account', 'allauth.socialaccount', 'ckeditor', 'widget_tweaks', 'dbbackup', 'django_extensions', 'captcha', 'wagtailcaptcha', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'debug_toolbar'] Installed Middleware: ['debug_toolbar.middleware.DebugToolbarMiddleware', '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', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 194, in post return super().post(request, *args, **kwargs) File … -
How to allow sqlite3 databate take duplicate values in different rows providing the primary keys are different?
I'm trying to import a .csv file into my Django db.sqlite3 and I followed exactly as the the instructions from a Youtube video. However, there are a couple of rows in my .csv file that have the same latitude and longtitude values and sqlite3 fails to import some rows as the latitute and longtitude already appear in the table. sqlite> .import venues.csv myapi_venue venues.csv:17: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:44: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:49: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:60: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:66: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:73: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:80: INSERT failed: UNIQUE constraint failed: myapi_venue.name I tried to force the model to have unique as False, but it doesn't help. class venue(models.Model): name = models.CharField(_("name"), primary_key=True, max_length=300) address = models.CharField(_("address"), max_length=300, unique=False) categories = models.CharField(_("category"), null=True, max_length=300, unique=False) latitude = models.FloatField(_("latitude"), max_length=150, unique=False) longitude = models.FloatField(_("longitude"), max_length=150, unique=False) When I try migrate the changes, it shows this: $ python manage.py makemigrations No changes detected How do I import all the rows into the database? -
Cannot resolve keyword '_cart_id' into field. Choices are: cart_id, cartitem, date_added, id
views.py def allProdCat(request, c_slug=None): c_page = None products_list = None if c_slug != None: c_page = get_object_or_404(Category, slug=c_slug) products_list = Product.objects.all().filter(category=c_page, available=True) else: products_list = Product.objects.all().filter(available=True) paginator = Paginator(products_list, 6) try: page = int(request.GET.get('page', '1')) except: page = 1 try: products = paginator.page(page) except (EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request, "category.html", {'category': c_page, 'products': products}) category.html {% extends 'base.html' %} {% load static %} {% block metadescription %} {% if category %} {{category.description|truncatewords:155 }} {% else %} Welcome to ABC store where you can buy different items... {% endif %} {% endblock %} {% block title %} {% if category %} {{category.name }} - ABC Store {% else %} See our New Collections -ABC Store {% endif %} {% endblock %} {% block content %} {% if category %} {% endif %} {% if category %} {{category.name}} {{category.description}} {% else%} Our products Collections What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has? {% endif %} {% for products in … -
Sum values from child models using nested Subquery and annotaions in Django Viewset
I'm trying to calculate the total price of a Recipe. To optimize DB queries I'm trying to use Django's ORM capabilities to perform the fewest requests. My models.py is like this: class BaseRecipe(models.Model): title = models.CharField(_('Base recipe title'), max_length=255, user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='user_base_recipes') class Meta: ordering = ['title'] def __str__(self): return self.title class IngredientBaseRecipe(models.Model): base_recipe = models.ForeignKey(BaseRecipe, on_delete=models.CASCADE, related_name='ingredients') name = models.CharField(_('Name'), max_length=255) products = models.ManyToManyField(Product) quantity = models.FloatField(_('Quantity'), default=0.0) class Meta: ordering = ['-id'] def __str__(self): return self.name class Product(models.Model): name = models.CharField(_('Name'), max_length=255, help_text=_('Product name')) price = models.FloatField(_('Sale price'), default=0) class Meta: ordering = ['name', ] indexes = [models.Index(fields=['name',]), ] Then in my Viewset I'm trying to get the BaseRecipes queryset with an annotated field that shows the sum of the ingredients prices. I get to the point to obtain the ingredients price, but I'm stucked trying to sum them in the BaseRecipe query set: min_price = ( Product.objects.filter(name=OuterRef('name')) .annotate(min_price=Min('price')) .values('min_price') ) ingredients_price = ( IngredientBaseRecipe.objects .filter(base_recipe=OuterRef('id')) .annotate(price=Subquery(min_price)) .order_by() .annotate(total=Sum(F('price') * F('quantity'))) .values('total') ) queryset = BaseRecipe.objects.filter(user=self.request.user) \ .annotate(cost=Sum(ingredients_price)) return queryset Thanks a lot for your help! -
How does Django map the urls when there is ambiguity
I have the url patterns in my project urls.py url(r'^', include('app.urls')), url(r'^api/app/', include('app.url.router_urls')), and in the app.urls i have something like url(r'^api/app/user$', views.user_validator), and in the app.url.router_urls i have something like url('^v1/', include('app.url.app_v1.urls')) I have a question around these. so when the request is BASE_URL/api/app/{user} which url will be mapped to this? and how about BASE_URL/api/app/v1/ which url will be mapped. this will map first with ^ right and will use the app.urls for both? thanks