Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store HStore field properly?
Here I have a HStoreField which will be taken from user Input. User gives the input in the format s:Small,l:Large But I think the HStoreField needs the data type like this{'s': 'Small','l':'Large'}. How can I covert the user data into this format so that I can store into the HStoreField. Or simply I need to store the data. How can I do it ? class MyModel(models.Model): properties = HStoreField() # view properties = request.POST.get('properties') print(properties) #properties has data in this format s:Small,l:Large, MyModel.objects.create(properties=properties) I get the error like this. django.db.utils.InternalError: Unexpected end of string LINE 1: ...antity_reserved") VALUES ('ttt', 11, 'ttt', '55', 'Small:rrr... -
Set null arraylist Django
How can I set null or empty value of my array list inorder to insert id autoincrement , I already tried 'None' but it returns error. Can anyone help me? error tuple indices must be integers or slices, not NoneType views.py def upload_excel_file(request): if request.method =='POST': person_resource = PersonResource() dataset = Dataset() new_person = request.FILES['myfile'] if not new_person.name.endswith('xlsx'): messages.info(request,'wrong format') return render (request,'dashboard.html') imported_data = dataset.load(new_person.read(),format="xlsx") for data in imported_data: value = Person( data[None], // It should Empty value data[1], data[2], data[3], data[4], data[5] ) value.save() return render(request,'dashboard.html') > model.py class Person(models.Model): person_id = models.AutoField(primary_key=True) covid_id = models.CharField(max_length=50) firstname = models.CharField(max_length=50) middle = models.CharField(max_length=50) lastname = models.CharField(max_length=50,blank=True) extension = models.CharField(max_length=50) -
Using MariaDB's 'DATE_FORMAT' within a Django Query Expression
Good afternoon, I'm trying to use the DATE_FORMAT (reference) function provided by MariaDB to convert a datetime field to str directly from the database; # Dummy Model class FooBar(models.Model): datetime = models.DateTimeField() # Query FooBar.objects.all().annotate(dt_field=Func('datetime', Value("'%W %M %Y'"), function='DATE_FORMAT')) If I check the resulting query the output is as expected. >>> print(FooBar.objects.annotate(str_date=Func('datetime', Value("'%Y-%m-%d %H:%M:%S'"), function='DATE_FORMAT')).query) SELECT DATE_FORMAT(`foobar`.`datetime`, '%Y-%m-%d %H:%M:%S') AS `str_date` FROM `foobar` However, the actual execution of the query fails: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 258, in __len__ self._fetch_all() File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 74, in __iter__ for row in compiler.results_iter(results): File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1096, in apply_converters value = converter(value, expression, connection) File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/operations.py", line 265, in convert_datetimefield_value value = timezone.make_aware(value, self.connection.timezone) File "/usr/local/lib/python3.8/site-packages/django/utils/timezone.py", line 270, in make_aware return timezone.localize(value, is_dst=is_dst) File "/usr/local/lib/python3.8/site-packages/pytz/__init__.py", line 237, in localize if dt.tzinfo is not None: AttributeError: 'str' object has no attribute 'tzinfo' I must be doing or assuming something incorrectly, any advice? -
How can i create Generated/Computed column Postgres/DJANGO?
How can I create Generated/Computed column Postgres/DJANGO? I tried in both ways: (1) By a Class: ERROR I GET: TypeError: init() got an unexpected keyword argument 'always_generated' class Product(models.Model): name = models.CharField(max_length=200, null=True) precio_costo = models.FloatField(null=True) cantidad = models.IntegerField(null=True) *****monto_stock = models.FloatField(always_generated='precio_costo * cantidad', stored=True)***** (2) Directly by POSTGRES Admin But I can't update or add a new field, Default value is required by Django. -
How to filter Django objects based on value returned by a method?
I have an Django object with a method get_volume_sum(self) that return a float, and I would like to query the top n objects with the highest value, how can I do that? For example I could do a loop like this but I would like a more elegant solution. vol = [] for m in Market.object.filter(**args): # 3000 objects sum = m.get_volume_sum() vol.append(sum) top = search_top_n(vol, n) From what I see here even with Python there isn't a single line solution. -
What is needed to successfully convert from referencing a model to sub classing it?
I am currently using two requests to create a User and a Doctor (or Patient). I would like to do it in a single request, so that it'll also be easier to determine the type of user later on. This is what I have for extending the User # models class User(AbstractUser): ROLES = ( ('d', 'Doctor'), ('s', 'Secretary'), ('p', 'Patient'), ) role = models.CharField( max_length=1, choices=ROLES, blank=True, default='p', help_text='Role') class Doctor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) clinic = models.ManyToManyField( Clinic, related_name="doctors", blank=True) appointment_duration = models.IntegerField(default=20, blank=True) # serializer User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password', 'role', 'first_name', 'last_name', 'email', 'phone') extra_kwargs = {'password': {'write_only': True, 'required': True} # viewset class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) Here's what I tried: class User(AbstractUser): pass class Doctor(User): clinic = models.ManyToManyField( Clinic, related_name="doctors", blank=True) appointment_duration = models.IntegerField(default=20, blank=True) First, before deleting the user field from Doctor, there was this error in the terminal clinic.Doctor.user: (fields.E305) Reverse query name for 'Doctor.user' clashes with reverse query name for 'Doctor.user_ptr'. HINT: Add or change a related_name argument to the definition for 'Doctor.user' or 'Doctor.user_ptr'. I then deleted the user property of Doctor, the error … -
Connecting Django application to Oracle database
I am trying to connect a django application to an oracle database using this configuration ```DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': '<my SID>', 'USER': '<My user name>', 'PASSWORD': '<My password>', 'HOST': '<my host IP address>', 'PORT': '<My port>' } }``` I tested the connection, which was successful using this code import cx_Oracle # Set folder in which Instant Client is installed in system path os.environ['PATH'] = '<path_to_instant_client>\\instantclient_19_8' # Connect to user account in Oracle Database 12cExpress Edition con = cx_Oracle.connect("<Username>", "<Password>", "IP:PORT/SID") print("Connected!") con.close()``` While trying to run `python manage.py migrate` for the very first time, I get this error `raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)` This table **django_migrations** did not exist in this database, when I run `python manage.py migrate`, it's created but from the error, the command want to create it again. Am not sure of what's happening here, kindly assist. -
estimating cloud provider price
I'm currently creating a startup and among the stuff I need to code/plan/etc I need to simulate my costs. I'm a student in AI and I have no experience using cloud providers. The project is a basic django rest application with a load balancer and a DBMS (I just started coding the MVP, some kind of private social network). My development server is my home htpc, a 12yo dual core celeron -T9400-and 2Gb of ram running with a bunch of docker apps, so absolutely not representative of a real use case All cloud providers estimators I've seen so far are using vCPUs, instances or bandwith to calculate their prices... But how does it translates in number of concurrent user? How can I use this estimation in pitches? -
Post method in django using ajax
I have a form that I am trying to implement with Ajax, after inputing some content on the textbox, when I click on the sumbit button using my mouse, everything works fine (page didnt refresh, data posted on database, and new data displayed on the page). But when I try to submit data by pressing enter, the page is displaying only the serialized data from my form (nothing more, html file do not work)and it says in the console: Resource interpreted as Document but transferred with MIME type application/json: "http://localhost:8000/try/". current page looks exactly like this after pressing enter button(nothing more): {"task": {"id": 52, "todo": "wws", "author": 1, "completed": false}} these are the data that came from my form. this is my views.py class TodoList(View): def get(self, request): todo_list = ToDo.objects.filter(author_id=request.user.id) form = AddTodo() context = { 'todo_list': todo_list, 'form': form, } return render(request, 'trylangto/try.html', context) def post(self, request): form = AddTodo(request.POST) if form.is_valid(): form.instance.author_id = request.user.id new_form = form.save() return JsonResponse({'task': model_to_dict(new_form)}, status=200) else: return redirect('trylang:todo-list') return redirect('trylang:todo-list') this is my main.js: $(document).ready(function(){ $("#createbutton").click(function(){ var formdata = $("#addtodoform").serialize(); $.ajax({ url: $("#addtodoform").data('url'), data: formdata, type: 'post', success: function(response){ $("#tasklist").append('<div class="card mb-1" ><div class="card-body">'+ response.task.todo +'<button type="button" class="close"><span aria-hidden="true">&times;</span></button></div></div>') } }); … -
Django ImageField Uploaded to Different Path than Reported by url property?
I'd like to allow users to upload profile pictures and then to display them. Here's my model.py: from django.db.models import CharField, ImageField, Model class Eater(Model): name = CharField(max_length = 30) image = ImageField(upload_to = 'images/eaters/') def __str__(self): return str(self.name) Here's my urls.py: from django.conf import settings # settings is an object, not a module, so you can't import from it. :( from django.conf.urls.static import static from django.urls import path from .views import EaterView, IndexView, post, sudo app_name = 'socialfeedia' urlpatterns = [ path('', IndexView.as_view(), name = 'index') ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) # Static returns a list of path, not a path itself. This is at the end of my settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR.joinpath('media/') Here's a line out of my index.html: <img class="post-profile-picture" src="{{ post.eater.image.url }}" alt="?"/> I successfully uploaded a file into this field - it got stored at: mysite/media/images/eaters/test_picture_64.jpg The image loads successfully if I visit it here: http://127.0.0.1:8000/socialfeedia/media/images/eaters/test_picture_64.jpg However, the img that shows up in my generated file is this: <img class="post-profile-picture" src="/media/images/eaters/test_picture_64.jpg" alt="?"> This file doesn't resolve - I just see a ? (the alt) instead. Should I be using something else to get the correct path to the file instead? Something … -
mailgun account disabled after deply app on heroku
I use heroku for deploying my django app. I used mailgun for email smtp. before deploying on heroku my mailgun smtp works correctly but after deploying,My accunt became disabled and I got the below message: Your account is temporarily disabled. ( exposed account credentials ) Please contact support to resolve. What shold I do? -
Django with Apache problem with virtual host configuration
I a new to Django. I am trying to deploy Django project on Linux using Apache virtual hosts. My project directory looks like below. Virtual host configuration is as follows: ServerAdmin webmaster@localhost ServerName ........... ServerAlias ........... DocumentRoot /var/www/djangotest1 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/djangotest1/static <Directory /var/www/djangotest1/static> Require all granted </Directory> <Directory /var/www/djangotest1/djtest1> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djangotest1 python-path=/var/www/djangotest1 python-home=/var/www/djangotest1/djenv WSGIProcessGroup djangotest1 WSGIScriptAlias / /var/www/djangotest1/djtest1/wsgi.py When trying to get the page I get following error: Fatal Python error: Py_Initialize: Unable to get the locale encoding Thanks for any help. -
django rest framework serializer doesn't return field when empty
I have a model with JsonField field that represented in a serializer. I want that field to always return all fields in response, even when empty, while listField should return as empty list in that case. In the way I created it, the None fields (allow_null=True) always return, even when empty, but the listField (default=list) doesn't return when it's empty. How can I make it also return in the response as empty list? I have this model (partial)- class MyModel(models.Model): objects_list = JSONField(default=dict) And this view - class MyModelViewSet(mixins.UpdateModelMixin, mixins.RetrieveModelMixin): serializer_class = ObjectsListSerializer This is the serializer - class ObjectsListSerializer(serializers.Serializer): days = serializers.IntegerField(allow_null=True, source='objects_list.days') user_list = serializers.ListField(child=serializers.CharField(), default=list, allow_empty=True, required=False, source='objects_list.user_list') manager = serializers.CharField(allow_null=True, source='objects_list.manager') def update(instance, validated_data): ....... -
NoReverseMatch at / Reverse for
this error is killing me please help I sat on in like for 3 hours and I couldn't even know why is the error happening I will give all the information needed , btw I am new to Django so please explain if you can Thank You, Error: NoReverseMatch at / Reverse for 'change_friends' with keyword arguments '{'operation': 'add', 'pk': 2}' not found. 1 pattern(s) tried: ['connect/(P.+)/(P\d+)/'] Here is my views.py from django.views.generic import TemplateView from django.shortcuts import render, redirect from django.contrib.auth.models import User from home.forms import HomeForm from home.models import Post, Friend class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) try: friend = Friend.objects.get(current_user=request.user) friends = Friend.users.all() except Friend.DoesNotExist: friends = None args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends } return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = HomeForm() return redirect('home:home') args = {'form': form, 'text': text} return render(request, self.template_name, args) def change_friends(request, operation, pk): friend = User.objects.get(pk=pk) if operation == 'add': Friend.make_friend(request.user, friend) elif operation == 'remove': Friend.lose_friend(request.user, friend) return redirect('home:home') Models.py from django.db import models from django.contrib.auth.models import … -
Django creating an instance of a model, negative number turns positive
I'm creating a new instance of a Referral_Commision and it's for a chargeback so I added a - sign in front of the 2 fields to make the variables negative. When it saves it's always positive when I check in the admin panel. I tried replacing the variable with an integer so it said =-20 and that worked fine when I checked in the admin panel. The transaction instance works fine and is negative when I check in the admin panel, so I'm really not sure why this happens. I even added a Decimal() cast to see if that works but it's still positive Models.py class Referral_Commision(models.Model): conversion_amount = models.DecimalField(max_digits=9,decimal_places=2) commision = models.DecimalField(max_digits=9,decimal_places=2) Signals.py Referral_Commision.objects.create(transaction=instance, referral_code=referrer.referral_code, user_referred=instance.user.referral, conversion_amount=-Decimal(instance.payout_coins), commision_percentage=referrer.referral_code.commision_percentage, commision=-Decimal(Decimal(instance.payout_coins)*referrer.referral_code.commision_percentage/100), chargeback=1) -
Accessing fields in a Queryset from a ManytoManyFIeld
Pretty new to Django and models and I am trying to make a wishlist where people can add to the wishlist an then view what is in their wishlist by clicking on the link to wishlist. I created a separate model for the wishlist that has a foreignfield of the user and then a many to many field for the items they want to add to the wish list. For right now i am trying to view the wishlist that i created for the user using the admin view in Django. The problem that i am having is that when I try to print their wishlist to the template the below comes up on the page. <QuerySet [<listings: item: Nimbus, description:this is the nimbus something at a price of 300 and url optional(https://www.google.com/ with a category of )>, <listings: item: broom, description:this is a broom stick at a price of 223 and url optional(www.youtube.com with a category of broom)>, <listings: item: wand, description:this is a wand at a price of 3020 and url optional(www.twitter.com with a category of sales)>]> What i ideally want is the query set to be split such that the two listings and their information would be … -
Dockerizing a Python Django Web Application, Nginx and Gunicorn
I'm trying to connect Gunicorn to my Django application, by Docker, to serve it as an HTTP server. The build was successful, with no errors. My problem starts in the race. That's the kind of message I get: [2020-10-01 12:55:18 +0000] [9] [INFO] Starting gunicorn 20.0.4 [2020-10-01 12:55:18 +0000] [9] [INFO] Listening at: http://0.0.0.0:8010 (9) [2020-10-01 12:55:18 +0000] [9] [INFO] Using worker: sync [2020-10-01 12:55:18 +0000] [13] [INFO] Booting worker with pid: 13 [2020-10-01 12:55:18 +0000] [13] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/local/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 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'wsgi' [2020-10-01 12:55:18 +0000] [13] [INFO] Worker exiting (pid: 13) [2020-10-01 12:55:18 +0000] [9] [INFO] Shutting down: Master [2020-10-01 12:55:18 +0000] … -
Unable to parse the date in the url Django
I have a url like this http://localhost:8000/getup/downloadrange/ef46219d-7b33-4bdc-aab1-c3bf073dca0e/datebottom=2019-10-10&datetop=2020-10-01/ My urls.py is like this path( "downloadrange/<uuid:id>/(?P<datebottom>\d{4}-\d{2}-\d{2})&(?P<datetop>\d{4}-\d{2}-\d{2})/$", views.getup, name="getup", ), The url pattern is not found for this. Kindly help me in this regard -
display login form errors with ajax without page refresh in django
i want to use ajax in my django login form that is in a bootstrap modal to display if there are errors such as wrong password or wrong email without the page being refreshed or the modal being closed NB: i'm new to django and especially ajax in my views.py if request.method == "POST": if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') in my forms.py class SigninForm(forms.ModelForm): class Meta: model = User fields = ('email', 'password') widgets = { 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control','id':'signin_email'}), 'password': forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control','id':'signin_password'}), } def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] in the template <form action="" method="POST" id="form_signin"> {% csrf_token %} {{signin_form.email}} {{signin_form.password}} <button type="submit" name="signin_form">Sign in</button> <hr> {% for message in messages %} <div class="alert alert-danger"> {{ message }} </div> {% endfor %} </form> -
How to index formset input fields with list elements
How can I use elements from a list as formset indexes instead of the generic 0,1,2 etc? Right now I have something like: Sizes = ["XS", "S", "M","L", "XL"] SizesFormSet = formset_factory(SizesForm, extra=len(Sizes)) And my formset input fields are indexed as 0,1,2... and I'd like to index them as "XS", "S", "M" etc The django documentation deals with renaming a formset input field prefix, but it doesn't deal with indexing. Thanks in advance for the help! -
Django-allauth creating custom registration form
I want to create a signup form with additional fields. I am using django-allauth. When I try to signup as a normal user I get this errror: [01/Oct/2020 12:28:15] "GET /accounts/signup/ HTTP/1.1" 200 438 Internal Server Error: /accounts/signup/ Traceback (most recent call last): File "/Users/home/Library/Python/3.7/lib/python/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/home/Library/Python/3.7/lib/python/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/home/Library/Python/3.7/lib/python/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Users/home/Library/Python/3.7/lib/python/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/home/Library/Python/3.7/lib/python/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/home/Library/Python/3.7/lib/python/site-packages/allauth/account/views.py", line 215, in dispatch return super(SignupView, self).dispatch(request, *args, **kwargs) File "/Users/home/Library/Python/3.7/lib/python/site-packages/allauth/account/views.py", line 81, in dispatch **kwargs) File "/Users/home/Library/Python/3.7/lib/python/site-packages/allauth/account/views.py", line 193, in dispatch **kwargs) File "/Users/home/Library/Python/3.7/lib/python/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/Users/home/Library/Python/3.7/lib/python/site-packages/allauth/account/views.py", line 104, in post response = self.form_valid(form) File "/Users/home/Library/Python/3.7/lib/python/site-packages/allauth/account/views.py", line 231, in form_valid self.user = form.save(self.request) AttributeError: 'CustomSignupForm' object has no attribute 'save' [01/Oct/2020 12:28:24] "POST /accounts/signup/ HTTP/1.1" 500 13665 I can create superuser. When creating superuser, it demands email but when logging in, it demands username. But I can enter email as username and log in successfully. forms.py: class CustomSignupForm(forms.Form): first_name = forms.CharField(max_length=30, label='First name') last_name = forms.CharField(max_length=30, label='Last name') … -
active button click in Django Javascript
This is my html file , i want to active button when click and colorized , i am using Django , but i think Javascript is good idea for this task. can any one help? html file <div class="menu_tabs"> <div class="menu_tabs_title"> </div> <a href="/aries" class="btn-skin ">Daily</a> <a href="/aries/love" class="btn-skin ">Loves</a> <a href="aries/finance" class="btn-skin ">Financial</a> <a href="aries/gambling" class="btn-skin ">Gambling</a> <a href="aries/sex" class="btn-skin ">Sexy</a> <a href="aries/pets" class="btn-skin ">Pets</a> css.file .btn-skin { border-radius: 2px; box-shadow: 1px 2px 5px rgba(0, 0, 0, .15); background: #4CAF50; color: #fff; width: auto; padding: 15px; transition: background-color 300ms linear; font-family: proxima-nova, sans-serif; font-size: 1rem; cursor: pointer; display: inline-block; margin: 8px 5px 5px 0; font-size: 20px; font-family: font2 } .active, .btn-skin:hover { background-color: #666; color: white; } -
i want to set null true when saving image in django rest api with base64
my models is class Profile(models.Model): store_picture1 = models.ImageField(null=True, blank=True) store_picture2 = models.ImageField(null=True, blank=True) store_picture3 = models.ImageField(null=True, blank=True) store_picture4 = models.ImageField(null=True, blank=True) store_picture5 = models.ImageField(null=True, blank=True) store_picture6 = models.ImageField(null=True, blank=True) def save(self,*args, **kwargs): if self.user_picture: im = Image.open(self.user_picture) output = BytesIO() im = im.resize((740, 610)) im.save(output, format='JPEG', quality=120) im.save(output, format='PNG', quality=120) output.seek(0) self.user_picture = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.user_picture.name.split('.')[0], 'image/jpeg',sys.getsizeof(output), None) self.user_picture = InMemoryUploadedFile(output, 'ImageField', "%s.png" % self.user_picture.name.split('.')[0], 'image/png',sys.getsizeof(output), None) self.user_picture = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.user_picture.name.split('.')[0], 'image/jpeg',sys.getsizeof(output), None) self.user_picture = InMemoryUploadedFile(output, 'ImageField', "%s.png" % self.user_picture.name.split('.')[0], 'image/png',sys.getsizeof(output), None) and this is my serializers.py class: class ProfileUpateSerializer(ModelSerializer): user_picture = Base64ImageField( max_length=None, use_url=True, ) store_picture1 = Base64ImageField( max_length=None, use_url=True, ) store_picture2 = Base64ImageField( max_length=None, use_url=True, ) store_picture3 = Base64ImageField( max_length=None, use_url=True, ) store_picture4 = Base64ImageField( max_length=None, use_url=True, ) store_picture5 = Base64ImageField( max_length=None, use_url=True, ) store_picture6 = Base64ImageField( max_length=None, use_url=True, ) class Meta: model = Profile fields ='__all__' i did set null=true and blan=true in my models.py for imageField but when i whant sent with image base64 with api notifies that it needs this field how cat in set null and blank true in my serializer class -
While saving data by overriding django admin's model forms save method, my code runs twice
While saving data by overriding Django admin's model form save method, in few cases my code runs twice causing few dependent actions to create multiple entries in DB and two success messages. I am unable to find why it is happening. This is hampering my usual workflow creating several bugs. Any help would be appreciated. -
Errno - 13 Permission denied: '/media/ - Django
I am using Django 3.1 in ubuntu, I got an error while uploading media files PermissionError at /admin/main/artist/1/change/ [Errno 13] Permission denied: '/media/artists' Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: '/media/artists' Exception Location: /usr/lib/python3.8/os.py, line 223, in makedirs Python Executable: /home/rahul/.local/share/virtualenvs/music-69qL54Ia/bin/python This code works in windows, but not in ubuntu Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / '/media/' Models.py class Artist(models.Model): image = models.ImageField(upload_to='artists/%Y/%m/%d/', default='demo-artist.jpg', null=True, blank=True) I tried this but didn't work https://stackoverflow.com/questions/21797372/django-errno-13-permission-denied-var-www-media-animals-user-uploads