Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload images to wagtail images using django rest framework?
I have a bit of a problem, any help would be appreciated: I have a model which has an icon field, which is related to wagtailimages.Image How do I upload images to that field which is ForeignKey related to wagtailimages.Image This is the serializer of my model: class CommunitySerializer(serializers.ModelSerializer): class Meta: model = Community fields = [ "id", "icon", "name", "description", "short_description", "website", ] And this is my models.py: class Community(ClusterableModel): ............ icon = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) .......... So, how should i go about uploading images to the "icon" field using DRF? I have tried to use both the DRF's FileField and ImageField but without success, maybe I am missing something? -
How can I get a size of SVG in Python?
From Django CMS admin I upload a SVG image and I need to validate its size For some other formats (jpeg, png) it works just fine def validate_social_icon(fieldfile_obj): w, h = get_image_dimensions(fieldfile_obj) if w > 100: raise ValidationError("The icon width must be <= 100 pixels. Yours is %i pixels." % w) if h > 100: raise ValidationError("The icon height must be <= 100 pixels. Yours is %i pixels." % h) But if I upload a SVG file, it says h and w are None, so there is an exception bc Python can't compare None to int. Is there a similar way to do that for SVG? -
Placing functions in vue.js that accept parameters and do not operate on variables in the component
I've been trying to wrap my head around best practices in vue.js (+ pinia as store). I'm coming from using Django templates where one can use template functions on variables to massage data for displaying. However, I'm not sure where to put such functions in vue.js. Suppose I have a variable holding a string and I want to cut off trailing digits. The variable is coming from a vue.js for-loop over a dict variable present in the store. I would create some function to do so: displayString(s) { const re = /\d+$/; return s.replace(re, ""); } I would use it in the template in some way: <th v-for="(item, index) in store.myDict" :key="index"> {{ displayString(item) }} </th> To me, neither place for putting the function (methods/computed or actions/getters in pinia) would be right as they are all intended to use data from the store or component (and not all of them accept parameters anyway). Conceptually, where would a function go that does not return data from the component or store but accepts a parameter and returns a modified version of it? Or should I design things differently, writing getters/computed functions that massage the dict in some way for displaying the data? … -
invalid connection option "ssl" when connecting to postgres using sqlalchemy
I used this code to connect my django application with postgresql using sqlalchemy ORM: DB_CONN_STRING = "{driver}://{user}:{password}@{host}:{port}/{dbname}?options='-c client_encoding=utf8&sslmode=require".format( driver=settings.DATABASES['db']['ENGINE'].split('.', -1)[-1], user=settings.DATABASES['db']['USER'], password=settings.DATABASES['db']['PASSWORD'], host=settings.DATABASES['db']['HOST'], port=settings.DATABASES['db']['PORT'], dbname=settings.DATABASES['db']['NAME']) db_engine = sqlalchemy.create_engine(DB_CONN_STRING, echo=settings.SQLALCHEMY_ECHO, pool_recycle=1800, pool_size=1, max_overflow=9, pool_use_lifo=True, pool_pre_ping=True, connect_args=ssl_args) db_session = scoped_session(sqlalchemy.orm.sessionmaker(bind=db_engine), scopefunc=get_current_request_id) But it raises this error when I run select query: (psycopg2.ProgrammingError) invalid dsn: invalid connection option "ssl" Is there a wrong with my connection string? -
Django TabularInline and field from related models
using django admin on an existing database i set up a many to many relation between "Contact" and "Groupe" based on a intermediate model "Contactgroup". In the "Group" Admin form i add a tabular in line to show all Contactgroup. It's OK but i get on error while adding fields from related Contact. model.py class Contact(models.Model): id = models.IntegerField(primary_key=True) e_mail = models.TextField() ... class Contactgroup(models.Model): id = models.IntegerField(primary_key=True) id_contact = models.ForeignKey(Contact, on_delete=models.CASCADE,db_column="id_contact", blank=False, null=False, verbose_name='Contact') id_groupe = models.ForeignKey(Groupe, on_delete=models.CASCADE,db_column="id_groupe", blank=False, null=False, verbose_name='Groupe') admin.py class MyContactgroupInline(admin.TabularInline): model = Contactgroup fields = ['id','id_contact'] MyGroupeModelAdmin.inlines = [MyContactgroupInline,] Then i try to add the Contact e_mail field : class MyContactgroupInline(admin.TabularInline): model = Contactgroup fields = ['id','id_contact', 'id_contact__e_mail'] MyGroupeModelAdmin.inlines = [MyContactgroupInline,] I get : Unknown field(s) (id_contact__e_mail) specified for Contactgroup -
Django path in pycharm
PS C:\Users\rajla> django-admin startproject mymall . django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject mymall . + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoun dException + FullyQualifiedErrorId : CommandNotFoundException this is the issue i am facing i am totally confused and i am getting headache so please help me -
TypeError: all() missing 1 required positional argument: 'self' while using AbstractUser model
class User(AbstractUser): nickname = models.CharField(max_length=32) birthday = models.DateField() objects = MyUserManager class Meta: ordering = ('-id',) I created an custom user model and defined the MyUserManager class to manage the model. class MyUserManager(UserManager): def _create_user(self, username, email, password, **kwargs): if not username: raise ValueError('id는 필수입니다.') user = self.model(email=self.normalize_email(email), **kwargs) user.set_password(password) user.save() return user def create_user(self, username, email=None, password=None, **kwargs): kwargs.setdefault('is_admin', False) return self._create_user(username, email, password, **kwargs) def create_superuser(self, username, email=None, password=None, **kwargs): kwargs.setdefault("is_staff", True) kwargs.setdefault('is_admin', True) return self._create_user(username, email, password, **kwargs) I was going to create a createuse function that receives values for the custom fields as parameters. However, first of all, I would like to resolve the errors that have occurred now. class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializers This is views.py in account app and error have occured this code. Why can't I find a self instance? What instance does the original User.objects return? Is there a problem with the MyUserManager class? -
How to order a queryset using related_name in django
I've got a User model which is related to the DriverCar model using related_name='driver'. Each user could be related to multiple drivercars. DriverCar model has a field "reference_number" of type integer. I want to show a list of all users ordered by thereference_number of the last DriverCar object related to the user. Using a query like User.objects.filter(archive=False).order_by('-driver__reference_number') gives me the wrong answer. But if I use order_by('-pk') everything works perfectly. Is there any way to do this correctly? class User(AbstractUser): archive = models.BooleanField(default=False) class DriverCar(models.Model): user = models.ForeignKey(User , on_delete=models.CASCADE , related_name='driver') reference_number = models.BigIntegerField(default=0, null=True, blank=True) -
How to update db setting in django at runtime?
To be more specific, I want to retrieve db setting from a config server when django project starts, and use it to setup django db connection Someday in the future, the setting in the config server may be changed (for example, change the user password) and pushed to django project then reset the db connection, so I can use new setting without restarting django project or updating project code Is there a way to do that? Or what's the right way to hide the db sensitive information (password, etc) from django project code? Any helps will be grateful, thanks~ -
How To Add UPI method in Django or DJANGO REST FRAMEWORK [closed]
How To Add UPI method in Django or DJANGO REST FRAMEWORK lIKE THIS IN BELOW Image -
Python Sendgrid send email with all extension file attachment django
I want to send an email with an attachment using SendGrid API with all extensions in Django. Here is my code for mail sending. views.py def submitTicket(request): try: if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') subject = request.POST.get('subject') comment = request.POST.get('comment') atchfile = request.FILES['fileinput'] allinfo = " Name : " + name + "\n E-Mail : " + email + "\n Comment : " + comment recipients_list = ['abc@gmail.com'] if allinfo: message = Mail(from_email='xxx@gmail.com', to_emails=recipients_list, subject=subject, html_content=allinfo) with open(atchfile, 'rb') as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() attachedFile = Attachment( FileContent(encoded_file), FileName(atchfile), FileType(atchfile), Disposition(atchfile) ) message.attachment = attachedFile sg = SendGridAPIClient('0000000000000000000000000000000') sg.send(message) return HttpResponseRedirect('submitTicket') except Exception as e: print("Exception = ", e) return render(request, 'submitTicket.html') I am getting below error while trying to perform this. TypeError at /submitTicket expected str, bytes or os.PathLike object, not InMemoryUploadedFile -
Django Admin site with different Superuser permissions and roles
In addition to default superuser " that has access to all apps in the project and all permissions " I want to create two more types of superuser, The maker has able to do All operations Of CRUD on all apps without executing in database in django admin , And the checker has to view one table " operations " to Approve or reject these operations. is superuser = True is_superuser with is_maker = True is_superuser with is_checker = True How could I check the user login in admin.py Django admin site panel to control other stuff ? models.py class User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_maker = models.BooleanField(blank=True, null=True, default=False) is_checker = models.BooleanField(blank=True, null=True, default=False) class Operation(models.Model): name = models.CharField(max_length=255, blank=True, null=True) model_name = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.SET_NULL) old_value = models.TextField(default='', null=True, blank=True) new_value = models.TextField(default='', null=True, blank=True) rejection_reason = models.TextField(null=True, blank=True, default='') status = models.CharField(choices=STATUS_CHOICES, max_length=50, blank=True, null=True, default=STATUS_PENDING) created_by = models.ForeignKey(User, blank=True, null=True, db_column='created_by', on_delete=models.CASCADE) -
Can't import youtubesearchpython into my code
Pip install youtube-search-python And than when i try : from youtubesearchpython import * I see an error tells me that the module not found What is the problem -
Django won't load admin dashboard css with ngnix
I have a problem that has been holding me up in development for 1 week and I can't get out of it by seeing other users' answers. My project consists of a backend in Django and a frontend in React, the whole application is Dockerized and is served using ngnix. Now with the current configuration the Django css is not loading, what am I doing wrong? I thank everyone for the help. settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('DigitalMapping.urls')), path('test', test, name='test'), path('notificationCompletedOperation', NotificationCompletedOperation, name='notificationCompletedOperation'), path('notificationErrorOperation', NotificationErrorOperation, name='notificationErrorOperation'), path('', include('notifications.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Dockerfile FROM python:3.8.5 WORKDIR /backend COPY ./ ./ RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN python manage.py collectstatic ENV PYTHONPATH ./backend default.conf upstream django { server django:8002; } server { listen 8080; location / { root /var/www/react; } location ~ ^/(api|admin)/ { proxy_pass http://django; proxy_set_header Host $http_host; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; # # Om nom nom cookies # add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # # Custom … -
TailwindCSS infinite reloading bug in Django-app on Heroku
I'm running a Django-app on Heroku and use TailwindCSS. When I deploy, the app ends up endlessly loading. Looking at Network in Chrome's dev-tool, I noticed that the endless loading originates from my app trying to load browser-sync-client.js. Basically, it waits for ~4 minutes for that script to load, doesn't get a response, and then stops loading. The app works perfectly fine, it's just annoying to have something loading in the back all the time. What I've tried so far is following the answer to this question. So I've edited the tailwind.config.js file's purge settings to include the right HTML/js files. But this still won't fix the endless loading bug. Has anybody experienced something similar? Any ideas on how to fix this? -
How to use Group by clause without model's id in Django ORM?
This is my Model class Model1(models.Model): category = models.CharField() name = models.CharField() I want to get count of category. So I wrote ORM like below: from django.db.models import Count result = Model1.objects.values('category').annotate(Count('sns_type')) but the result shown like below <QuerySet [{'category': 'A', 'category__count': 1}, {'category': 'B', 'category__count': 1},...]> I felt so weird, so I printed a query of this result. query shown like below SELECT "example_table"."category", COUNT("example_table"."category") AS "category__count" FROM "example_table" GROUP BY "example_table"."category", "example_table"."id" I don't know Why id is included in this query. Query I want to use is like below: SELECT "example_table"."category", COUNT("example_table"."category") AS "category__count" FROM "example_table" GROUP BY "example_table"."category" -
how to use regex in django.db.models.query
I am trying to get values from django.db.models.query, but I wanna use something like latest_stichtag_values.values("buchung__" + any character), example of it in normal python regex would be like r"^[buchung__]\w*", which matches buchung__ buchung__fdsaf buchung__ddd But not asss_buchung__ aaaa So, my question is how can use it in latest_stichtag_values.values("buchung__" + any character) thank you in advance -
after parent signup, parent should be able to create two child and the child should be unique to parent's account in django rest framework?
views.py class ChildCreateAPIView(ListCreateAPIView): serializer_class = ChildListSerializer permission_class = (IsAuthenticated,) def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) # ---> getting the data from serializers class if serializer.is_valid(raise_exception = True): # queryset = Child.objects.create(full_name=full_name, username=username, pin=pin, confirm_pin=confirm_pin) full_name = serializer.validated_data['full_name'] # full_name2 = serializer.validated_data['full_name2'] username = serializer.validated_data['username'] # username2 = serializer.validated_data['username2'] pin = serializer.validated_data['pin'] # pin2 = serializer.validated_data['pin2'] print(pin) # print(pin2) # child = Child.objects.create(username=username, full_name=full_name, pin=pin) guardian = Child.objects.create(username=username,full_name=full_name, pin=pin) # guardian = Child.objects.get(id = Guardian.id) guardian.save() # Guardian= Child.objects.get(guardian=request.user.id) # Guardian = Guardian.objects.get(id=Child.guardian_id.id) # child2 = Child.objects.create(username=username2,full_name=full_name2, pin=pin2) # child.is_verified = True # child.save() # Guardian.add(child) # guardian_id = kwargs.get('guardian_id') # Guardian = Guardian.objects.get(id=guardian_id) # Guardian.add(child) return Response(serializer.data) def get_queryset(self): return Guardian.objects.all() -
Merge three json result into one json
I have these three json file: First: [ { "amount": 100, "id": 1 } ] Second: [ { "new_id": 0, "id": 1, "date": 01/01/2023 } ] Third: [ { "new_id": 0, "start_date": 01/01/2024 } ] I want to merge these three json response together, the ideal result should be: Final: [ { "amount": 100, "new_id": 0, "id": 1, "date": 01/01/2023 "start_date": 01/01/2024 } ] I tried the method of update and update the first and second using a dict(hashmap). Is there a way to do this all together? by depending on two field "id" and "new_id"? merged = {} with open('File1.json') as f: for line in f: jsonified = json.loads(line) merged[jsonified['id']] = jsonified with open('File2.json') as f: for line in f: jsonified = json.loads(line) merged[jsonified['id']].update(jsonified) -
Alert Popup if a value is being removed from already selected values in django admin many to many field
In django admin on change; if a value is being selected for removal from Many to many field, I want to validate if or not that value is eligible for removing and alert user if it cannot be removed else allow user to perform the operation. How do I pass the value or values that are selected for removal on many to many field filtered horizontal widget for example If I want to remove rahulverma from chosen tags and move to available tags, I want to run a javascript call and check if he can be removed from the chosen tags. -
celery doesn't run task at all / periodicly
this function i was using under management/commands and it was working but i'd like to use it to update feeds periodically. like every 15 mins or so. celery.py from celery import Celery import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") app = Celery('mysite', broker='redis://', backend='rpc://', include=['mysite.tasks'], timezone='UTC') if __name__ == '__main__': app.start() tasks.py from .celery import app from news.models import Feed, Article import feedparser from datetime import datetime, timezone @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(60.0, handle.s(), name='update feeds every 60 seconds') @app.task def handle(self, *args, **kwargs): feeds = Feed.objects.all() for feed in feeds: new_list = feedparser.parse(feed.url) for entry in new_list.entries: start = datetime.now(timezone.utc) end = datetime(*(entry.published_parsed[0:6])).replace(tzinfo=timezone.utc) if (start - end).days < 2 and not Article.objects.filter(url=entry.link).exists(): article = Article() article.title = entry.title article.url = entry.link article.description = entry.description dateString = end.strftime('%Y-%m-%d %H:%M:%S %z') article.publication_date = dateString article.save() else: pass i run celery -A mysite worker -l INFO and there is [tasks] . mysite.tasks.handle i tried also celery -A mysite beat no errors but i don't see any effect on my site -
Django Form, make readonly field
I'm trying to create a Form with Django and i'm aiming to have a readonly field, without success. The field should contain a code that is calculated in the view but i need to show it to the user. This is the Model: class Customer(models.Model): name = models.CharField(max_length = 250) note = models.CharField(max_length=500,blank=True,null=True) code = models.IntegerField(null=True,blank=True,unique=True) This is the Form: class NewCustomerForm(forms.ModelForm): class Meta: model = Customer fields = ['name', 'code', 'note'] That should be pretty easy but i'm facing a lot of problems. What I've already tryed: Field.disabled = True (the documentation don't explaine where should i put this attribute so maybe i'm getting something wrong) self.fields['code'].widget.attrs['readonly'] = True in __init __ self.fields['code'].widget.attrs['disabled'] = True in __init __ In all of three method the field remain editable by the user -
Relation "django_celery_beat_periodictask" does not exist after dockerizing celery_beat
I have a Django app with Nginx, Gunicorn, PostgreSQL and Celery that I've been dockerizing. When trying to add celery_beat in my docker-compose.yml, I get a django.db.utils.ProgrammingError: relation "django_celery_beat_periodictask" does not exist even though the migrations have been ran successfully, and on the admin panel I can see all the celery beat stuff displayed. However celery_beat doesn't start because of this error, but I have no idea where it could be coming from. Here is my docker-compose.yml: version: '3.8' services: rabbitmq3: container_name: rabbitmq image: rabbitmq:3-alpine ports: - 5672:5672 postgres: container_name: postgres hostname: postgres image: postgres:latest env_file: - env environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=password - POSTGRES_DB=db ports: - "5432:5432" restart: on-failure volumes: - postgresql-data:/var/lib/postgresql/data django_gunicorn: container_name: django_gunicorn volumes: - static:/app/static - media:/app/media env_file: - env build: context: . ports: - "8000:8000" command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000" depends_on: - postgres nginx: container_name: nginx build: ./nginx volumes: - .:/code - static:/static ports: - "80:80" depends_on: - django_gunicorn celery: container_name: celery volumes: - media:/app/media build: context: . command: celery -A main worker -P eventlet -c 100 -l INFO env_file: - env restart: always depends_on: - rabbitmq3 - postgres - django_gunicorn celery_beat: container_name: celery_beat … -
Received unregistered task of type 'vubon'. - Getting unregistered error even when all the tasks are shown when starting celery. Why?
The command used to run celery which gives me the output shown in the image.As you can see in the image it says key error vubon. And I don't have any task named "vubon". What maybe the issue is it import structure or something else??? celery -A patronpay worker -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler -
Django DRF Django-filters how to provide a default value if filter argument was not provided?
So in this example from the documentation of django-filters, how would I set a default value for max_price if max_price was not provided as filter option with the API call? class ProductFilter(filters.FilterSet): min_price = filters.NumberFilter(field_name="price", lookup_expr='gte') max_price = filters.NumberFilter(field_name="price", lookup_expr='lte') class Meta: model = Product fields = ['category', 'in_stock'] class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = ProductFilter