Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Duplicate key value violates unique constraint Dajngo python
My goal. If the id matches, you need to update the creation time column in the model. I can't figure out how I can solve this problem. It doesn't seem complicated, but I'm stuck. if a:=Defect.objects.get(id_leather=id_file_name) == True: a.update(created=datetime.datetime.now()) else: Defect.objects.create(id_leather=id_file_name, path=path_file_save) Models.py class Defect(models.Model): created = models.DateTimeField(auto_now_add=True) Error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "files_defect_id_leather_key" DETAIL: Key (id_leather)=(9998) already exists. -
Get distinct titles from product list with min and max price of that product title in django
I have list of products with same title but of different price. This is my Product model: class Product(BaseModel): title = models.ForeignKey( ProductTitle, on_delete=models.CASCADE, related_name="product_title", null=True, blank=True, ) quantity = models.PositiveIntegerField(default=1) price = models.FloatField(validators=[MinValueValidator(0.00)]) unit = models.CharField( max_length=20, blank=True, null=True, help_text="Standard measurement units.eg: kg, meter,etc..", ) description = models.TextField( blank=True, null=True, help_text="Short Info about Product" ) slug = models.SlugField(null=False, unique=True) Say, I have 10 products of same title but with different price, and same goes for other products as well. Now i want to get single(distinct) product of particular title with Min and Max price for that product and so on. So, i should get say Orange with min and max price, apple with min and max price and so on. I have tried some ways but its not working. Like in this query its giving me: product_qs = ( Product.objects.filter(is_deleted=False) .order_by("title__title") .distinct("title__title") ) p_list = product_qs.values_list("title", flat=True) product_list = product_qs.filter(title__in=p_list).annotate( max_price=Max("price"), min_price=Min("price") ) NotImplementedError at /api/product/unique_product/ annotate() + distinct(fields) is not implemented. Can somebody help me with this -
How to make certain field not visible in an api output using python and django?
i have parent (AccessInternalSerializer) and child serializer (AccessSerializer) classes like below, class AccessInternalSerializer(AccessBaseSerializer): private_key = serializers.FileField( allow_null= True, required=False) ca_cert=serializers.FileField( allow=True, required=False) def to_representation(self, obj): data = super().to_representation(obj) data['private_key'] = obj.private_key data['ca_cert'] = obj.ca_cert return data class Meta(AccessBaseSerializer.Meta): model=Access extra_kwargs = { 'auth_failure': { read-only: True } } class AccessSerializer(AccessInternalSerializer): private_key = serializers.FileField( write_only=True, allow_null=True, required=False) ca_cert=serializers.FileField( write_only=True, allow_null=True, required=False) class Meta(AccessInternalSerializer.Meta): extra_kwargs={ **AccessInternalsSerializer.Meta.extra_kwargs, 'private_key': { 'write_only':True, } 'ca_cert': { 'write_only': True, } } Now with above code for some reason private_key and ca_cert are shown in the output of api using AccessSerializer. with AccessInternalSerializer to_representation i make the private_key and ca_cert fields visible in api output that uses AccessInternalSerializer. however it behaves the same using AccessSerializer. i expect the api output to not return private_key and ca_cert fields using AccessSerializer. I am not sure where i am going wrong. i am new to python and django programming. i am stuck with this from long time. could someone help me with this. thanks. -
How to Fix django migrate issue?
I am try to run my django project before run I did makemigrations all my apps and then I run command migrate but I am getting this error I am not able to understand what exactly this error. Please help. -
Using CDN fro django-jet theme's Static Files
Can i move every Static file related to Django-jet (like static/admin/css/autocomplete.css) theme to CDN ? Is it required to keep the referenced libraries within code base ? -
Free SMTP for Django Projects
What is the best Free SMTP Service for website? Also what are the Django settings for the same. Currently, I am developing a Django project based on amounts due to pay in the organization. The person whose amount are due should get a proper email notification regarding the remaining amount to be paid. So I want to use a free SMTP service for the base usage. -
Sum multiple annotates in django orm
Here's my model: class Product: name = models.CharField(max_length=80) price = models.FloatField() category = models.CharField(max_length=40) class ProductInventory: inventory = models.IntegerField() product = models.OneToOneField(Product, on_delete=models.RESTRICT) and here's raw sql of what I want to achieve but how do I write this in django ORM? SELECT product.category, SUM(price) * SUM(product_inventory.inventory) FROM product LEFT JOIN product_inventory ON product.id=product_inventory.product_id group by product.category; Thank you. -
django.db.utils.ProgrammingError: table does not exist after migrating to Postgres from SQLite
After changing my settings and migrating to Postgres I am getting this error while performing migrations, I previously deleted all my migration folders because I had a similar issue with database inconsistency, now I don't have any migrations in my app-level directories, I do have DB backup but, how do I get past this, any help is appreciated, thanks in advance Db Settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'mypass', 'HOST': 'localhost', 'PORT': '5432', } } Trace Traceback (most recent call last): File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 22, in <module> main() File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\executor.py", line 230, in apply_migration migration_recorded = True File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\backends\base\schema.py", line 118, in __exit__ self.execute(sql) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\backends\base\schema.py", line 145, in execute … -
django.db.utils.IntegrityError: (1364, "Field 'name' doesn't have a default value")
I'm Facing This Error Whenever I am trying to execute the python manage.py migrate command then, Please Help Us. -
Set attribute based on another attribute
How to set hostel choices based on gender? Global variables BOYS_HOSTEL_CHOICES = (...) GIRLS_HOSTEL_CHOICES = (...) class Student(models.Model): MALE = 'M' FEMALE = 'F' #... GENDER_CHOICES = ( (MALE, 'Male'), (FEMALE, 'Female') ) gender = models.CharField( max_length = 10, choices = GENDER_CHOICES, verbose_name="gender", ) hostel = models.CharField( max_length=40, choices = BOYS_HOSTEL_CHOICES if gender == 'M' # <--- else GIRLS_HOSTEL_CHOICES, default = 'some hostel' ) -
drf spectacular not showing query params in swagger ui
I have generic ListAPIView with following list request function. Here category is a query parameter. I am trying to achieve such that the swagger ui also shows the query parameter in the swagger ui doc. How to achieve this? I have the following code. @extend_schema( parameters=[ OpenApiParameter(name='category',location=OpenApiParameter.QUERY, description='Category Id', required=False, type=int), ], ) def list(self, request, *args, **kwargs): category_id = request.query_params.get('category') .... return Response(data) -
How can I find out which mange.py is running?
On a Ubuntu machine, there is a Django process $ ps aux | grep 8010 xxx 5790 0.0 0.0 75228 12 ? S 2019 0:00 python manage.py runserver 0.0.0.0:8010 How can I find out the absolute path to this manage.py? -
Custom Authentication returning NULL everytime in django
I am beginner in django and I want to build authentication using custom user model. I have asked question Here. I have been advised to inherit the User Model. I created custom user model. As all the password are stored using bcrypt function so I created my own custom authentication. Now every time I login, I am getting None even if my password is correct. I want to know what I am missing? models.py class AdminUserManager(BaseUserManager): def create_user(self, username, password): if username is None or password is None: raise ValueError("Username and Password is Required") else: user = self.model( username = username, password = str(bcrypt.hashpw(password.encode('utf8'),bcrypt.gensalt()),'utf-8') ) user.save(using=self.db) return user class AdminUsers(AbstractBaseUser): username=models.CharField(max_length=50,unique=True) firstname=models.CharField(max_length=50) department=models.CharField(max_length=50) mail=models.CharField(max_length=50) id=models.IntegerField(primary_key=True) password=models.CharField(max_length=200) # some more field USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['mail'] objects = AdminUserManager() class Meta: db_table="admin_users" def __str__(self): return self.username backend.py from .models import AdminUsers import bcrypt class CustomAuthentication(object): def authenticate(self,username,password): if username is not None and password is not None: user = AdminUsers.objects.get(username=username) hashed_password = user.password is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8')) if is_check == True: return user else: return None else: return None def get_user(self,id): user = AdminUsers.objects.get(id=id) if user is not None: return user else: return None views.py def login(request): if request.method == 'POST': … -
Is Django is necessary for data science and machine learning
In my experience, Django has been a really great choice for data science projects. This is a common scenario I've found in freelancing, and in having conversations with other developers; typically in companies that are working with data, whether it's a service they provide to their clients or it's for internal tools. Traditionally the company starts by using Microsoft Excel. Over time those companies want their data to be more flexible and want to start doing things that are more demanding than what traditional spreadsheets can provide. They'll then start looking at custom solutions to improve their processes. Data science machine learning + django What do you think Django can improve our data science projects. is Django necessary for a good data scientist or machine learning engineer? -
Can't set a password for costume user model in the admin page
I'm working on an app where I have Users with multiple role, Customers, and Employees, where employees also are in different roles: Drivers and administration. I used AbstractBaseUser model to set a customized user model as this: class UserAccountManager(BaseUserManager): def create_superuser(self, email, first_name, last_name, password, **other_fields): other_fields.setdefault("is_staff", True) other_fields.setdefault("is_superuser", True) other_fields.setdefault("is_active", True) other_fields.setdefault("is_driver", True) other_fields.setdefault("is_customer", True) other_fields.setdefault("is_responsable", True) if other_fields.get("is_staff") is not True: raise ValueError(_("Supperuser must be assigned to is_staff.")) if other_fields.get("is_superuser") is not True: raise ValueError(_("Superuser must be assigned to is_superuser.")) return self.create_user(email, first_name, last_name, password, **other_fields) def create_user(self, email, first_name, last_name, password, **other_fields): if not email: raise ValueError(_("You must provide an email address")) email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("Email Address"), unique=True) first_name = models.CharField(_("First Name"), max_length=150, unique=True) last_name = models.CharField(_("Last Name"), max_length=150, unique=True) mobile = models.CharField(_("Mobile Number"), max_length=150, blank=True) is_active = models.BooleanField(_("Is Active"), default=False) is_staff = models.BooleanField(_("Is Staff"), default=False) is_driver = models.BooleanField(_("Is Driver"), default=False) is_responsable = models.BooleanField(_("Is Responsable"), default=False) is_customer = models.BooleanField(_("Is Customer"), default=False) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) objects = UserAccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] class Meta: verbose_name = "Account" verbose_name_plural = "Accounts" def __str__(self): … -
How to insert a 3d model and display in django
class orders(models.Model): orderitem = models.CharField(max_length=100) orderprice = models.CharField(max_length=100) 3dimage = models.ImageField(max_length=100) '''can we use the image format in the model to insert a 3d model''' -
Django - Write test to upload multiple Images
I have this code below that generates a fake image then tries to send it to this endpoint. I have a breakpoint at the first line of def post(self, request) and when I look into request.data I don't see an images key and when I do request.FILES, it's an empty multi-dict. I'm trying to allow the user to upload multiple images, which is why it's in a list. How do I properly add images to a request to test upload? test.py from django.core.files.base import ContentFile from PIL import Image from six import BytesIO def create_image(storage, filename, size=(100, 100), image_mode='RGB', image_format='PNG'): """ Generate a test image, returning the filename that it was saved as. If ``storage`` is ``None``, the BytesIO containing the image data will be passed instead. """ data = BytesIO() Image.new(image_mode, size).save(data, image_format) data.seek(0) if not storage: return data image_file = ContentFile(data.read()) return storage.save(filename, image_file def test_image_upload_authorized(self): image = create_image(None, 'test.png') image_file = SimpleUploadedFile('test.png', image.getvalue()) response = self.client.post(reverse('post'), data={'creator_id': str(self.user.uuid), 'images': [image_file]}, content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) view.py def post(self, request): serializer = PostSerializer(data=request.data) if serializer.is_valid(): try: serializer.save() except django.db.utils.InternalError as e: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
InvalidParameterValueError - Source bundle is empty or exceeds maximum allowed size: 524288000
I use eb cli to deploy django applicatoin. It suddenly started showing error InvalidParameterValueError - Source bundle is empty or exceeds maximum allowed size: 524288000 while deploying my app using eb deploy command. It showing error for both my production and stating environment. My source bundle size should be below the limit. What is the cause and how to fix it? -
DEBUG = False / "Server Error (500)" - Django
I have a fully built Django python website and now I'm launching it into production. I'm trying to set DEBUG equal to False for production with limited success. I have been working on this problem on and off for about a week and here is what I've got. settings.py DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) This makes most pages work and I think the pages where it works are the HTML pages that are extended from another page that looks for the CSS files and images in the head tag or at least that is the only correlation I can see. Some pages properly show the contents and when there is an error it shows "Server Error (500)" or something along those lines. For other pages that don't work, they never display the proper contents and just automatically show "Server Error (500)" or something along those lines. When it does always give this error I get an error in my terminal that says raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'style.css' I do have a static CSS file called style.css that contributes to some of … -
got an error while connecting MySQL to Django as backend database
In order to connect MySQL as Backend Language for Django I have made some changes in settings.py and I have given the changed code below # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'PASSWORD':'2684', 'HOST':'127.0.0.1', 'PORT':'3306', 'USER':'root' } } after saving it and while I execute the command python manage.py makemigrations I got an Error mentioned E:\Python\sample_django\root>python manage.py makemigrations C:\Users\2684j\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (1193, "Unknown system variable 'default_storage_engine'") warnings.warn( No changes detected My database Details given below database Name : django MySQL password : 2684 Port : 3306 Host : localhost User : root -
How to apply throttling just to create action in DRF viewsets?
I have a viewset and I want to apply throttling to only create action of that viewset and I don't want it to be applied to update, destroy, retrieve and etc... class UserViewSet(viewsets.ModelViewSet): # should only be applied to the create action throttle_classes = [SomeThrottle] ... -
How to install django with python3.9 on ubuntu aws
I'm having challenges installing django using the command sudo python3.9 -m pip install Django. The error I get running that command is: Traceback (most recent call last): File "/usr/lib/python3.9/runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/usr/lib/python3/dist-packages/pip/__main__.py", line 19, in <module> sys.exit(pip.main()) File "/usr/lib/python3/dist-packages/pip/__init__.py", line 217, in main return command.main(cmd_args) File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 242, in main with self._build_session( File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 66, in _build_session session = PipSession( File "/usr/lib/python3/dist-packages/pip/download.py", line 321, in __init__ self.headers["User-Agent"] = user_agent() File "/usr/lib/python3/dist-packages/pip/download.py", line 93, in user_agent zip(["name", "version", "id"], platform.linux_distribution()), AttributeError: module 'platform' has no attribute 'linux_distribution' When I created the aws ubuntu server instance I ran python3 -V and the ouput was that python3.5 was running on the machine. I upgraded it to python 3.9. Now when I run python3 -V the output is: Python 3.9.4. After upgrading to python3.9 I created and activated another virtual enviroment. Now when I try to install django using the command sudo python3.9 -m pip install Django I get the above error. If I use sudo python3 -m pip install Django the django is installed with python3.5 because, thereafter when I run sudo python3 manage.py migrate it … -
how do i run this program from git hub properly
I am trying to run this program from Github (https://github.com/dhvanilp/Hybrid-Cryptography) I can't seem to do it right either that or it's is broken please help me confirm this. If it works how do I run it properly. I have followed the instructions provided verbatim and it still would not work. -
Wagtail Images Suddenly Not Rendering on Front End
I have just encountered an odd problem I'm trying to debug but cannot figure out what is wrong. I have a wagtail site with images that were all working. At one point I refreshed the browser, and the images suddenly all disappeared from every page. wagtailimages_tags is there static is all loaded the images are all in the correct media directory as specified and have been uploaded through the CMS if i inspect element, the image is in fact coming through in the code perfectly. But the site itself just does not show the image. I have checked the CSS and nothing has changed there and it is not hiding the image somehow. My last resort - I actually started the project over completely in a new environment and added each application one by one to see if I could solve the issue ... nope. No images on the new install from scratch either! No idea why all the images would suddenly just fail to appear in browser. Just seems super strange to me. Any ideas on debugging appreciated. -
Creating new Objects instead of updating - Django
I am trying to use Update in Django, but it is not being updated, rather a new object of the model is being created in the database. For example, if I try to change product label "Laptop" to "Smartphone", Django creates a new product called "Smartphone" instead of updating "Laptop". This is my code Model: class Products(models.Model): label = models.CharField(max_length=50) description = models.CharField(max_length=250) first_price = models.FloatField(null=True) price = models.FloatField() quantity = models.IntegerField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.label @property def imageURL(self): try: url = self.image.url except: url = '' return url Form: class ProductForm(ModelForm): class Meta: model = Products fields = ['label', 'description', 'first_price', 'price', 'quantity', 'image'] View: @login_required(login_url='login') def editProduct(request, id): product = Products.objects.get(id=id) form = ProductForm(instance=product) if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, 'Product was edited.') return redirect('index') context = { 'form': form } return render(request, 'store/edit-product.html', context) Template: <h3>Edit Product</h3> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.label.label }} {{ form.label }} {{ form.description.label }} {{ form.description }} {{ form.first_price.label }} {{ form.first_price }} {{ form.price.label }} {{ form.price }} {{ form.quantity.label }} {{ form.quantity }} {{ form.image.label }} {{ form.image }} <input type="submit" name="Add product"> {{form.errors}} </form> Thank you …