Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Application Error - Giving (H=10) error
Tried lots of stackoverflow suggestion still can't get rid of this problem. Application deployed successfully but showing nothing. Error: 2022-05-30T12:04:32.860229+00:00 app[web.1]: mod = importlib.import_module(module) 2022-05-30T12:04:32.860230+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module 2022-05-30T12:04:32.860231+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-05-30T12:04:32.860231+00:00 app[web.1]: File "", line 1050, in _gcd_import 2022-05-30T12:04:32.860231+00:00 app[web.1]: File "", line 1027, in _find_and_load 2022-05-30T12:04:32.860231+00:00 app[web.1]: File "", line 1006, in _find_and_load_unlocked 2022-05-30T12:04:32.860232+00:00 app[web.1]: File "", line 688, in _load_unlocked 2022-05-30T12:04:32.860232+00:00 app[web.1]: File "", line 883, in exec_module 2022-05-30T12:04:32.860232+00:00 app[web.1]: File "", line 241, in _call_with_frames_removed 2022-05-30T12:04:32.860232+00:00 app[web.1]: File "/app/bazaar/wsgi.py", line 16, in 2022-05-30T12:04:32.860232+00:00 app[web.1]: application = get_wsgi_application() 2022-05-30T12:04:32.860233+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2022-05-30T12:04:32.860233+00:00 app[web.1]: django.setup(set_prefix=False) 2022-05-30T12:04:32.860233+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/init.py", line 19, in setup 2022-05-30T12:04:32.860233+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2022-05-30T12:04:32.860234+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/init.py", line 83, in getattr 2022-05-30T12:04:32.860234+00:00 app[web.1]: self._setup(name) 2022-05-30T12:04:32.860234+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/init.py", line 70, in _setup 2022-05-30T12:04:32.860234+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2022-05-30T12:04:32.860234+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/init.py", line 177, in init 2022-05-30T12:04:32.860234+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module 2022-05-30T12:04:32.860235+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "", line 1050, in _gcd_import 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "", line 1027, in _find_and_load 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "", line 1006, in _find_and_load_unlocked 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "", … -
How to use `docker compose exec` with both grep and ANSI color?
I'm only casually familiar with Docker, and how TTYs work in Linux. At work, I use commands like docker compose up to start the development stack (Postgres + Django), and docker compose exec web python manage.py ... to run Django commands during development. Conflicting problems: I can't pipe in input or grep output without adding -T. I don't know why, I just know it works with it, and not without it. I populate the DB with docker compose exec -T db psql -U username myproj < snapshot.sql because without the -T the input doesn't make it to psql. I also add -T when I have to grep the output, like: docker compose exec web python manage.py showmigrations | grep '[ ]'. However, when I use -T, it screws up ANSI coloring and formatting. Without -T: With -T: Question: What's the correct method? How do I properly connect STDIN & STDOUT without messing up color & formatting? -
Javascript, showing blob images
So I have this codes in my Django project. I am adding this with jQuery when I upload a file to html input tag which looks like: <input type="file" name="photo" accept="image/*" id="id_photo" multiple> JS (jQuery): ...append(`<img scr="${URL.createObjectURL(files[i])}" width="100px" height="100px">`) // files[i] comes from looping over multi-uploaded images html after uploading: <img scr="blob:http://127.0.0.1:8000/0929d4cc-972f-4f2b-b5ea-635020c47afa" width="100px" height="100px"> the blob image url (blob:http://127.0.0.1:8000/0929d4cc-972f-4f2b-b5ea-635020c47afa): So it actually shows the image in that url, but it looks like it can't identify the image in html. The question is why image is not shown on html? Thanks. -
Take the current admin
serializers.py class RegSerializer(serializers.ModelSerializer): admin = serializers.SlugRelatedField(slug_field='username', read_only=True) class Meta: model = Registration fields = [ 'id', 'rooms', 'first_name', 'last_name','admin', 'pasport_serial_num', 'birth_date', 'img', 'visit_date', 'leave_date', 'guest_count', 'room_bool'] models.py class Rooms(models.Model): objects = None room_num = models.IntegerField(verbose_name='Комната') room_bool = models.BooleanField(default=True, verbose_name='Релевантность') category = models.CharField(max_length=150, verbose_name='Категория') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Комнату' verbose_name_plural = 'Комнаты' class Registration(models.Model): objects = None rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', help_text='Номер в который хотите заселить гостя!', ) first_name = models.CharField(max_length=150, verbose_name='Имя') last_name = models.CharField(max_length=150, verbose_name='Фамилия') admin = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Администратор') pasport_serial_num = models.CharField(max_length=100, verbose_name='Серия паспорта', help_text='*AB-0123456') birth_date = models.DateField(verbose_name='Дата рождения') img = models.FileField(verbose_name='Фото документа', help_text='Загружайте файл в формате .pdf') visit_date = models.DateField( default=django.utils.timezone.localdate, verbose_name='Дата прибытия') leave_date = models.DateField(blank=True, null=True, verbose_name='Дата отбытия', default='После ухода!') guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей') room_bool = models.BooleanField(default=False, verbose_name='Релевантность', help_text='При бронирование отключите галочку') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.rooms},{self.last_name},{self.first_name},{self.room_bool}' class Meta: verbose_name = 'Номер' verbose_name_plural = 'Регистрация' how can I make it so that the name of the user who registered nomautofdn is indicated in the admin field and without the right to change only readonly? can this be done at all? thanks in advance for your reply -
django social all auth - multiple user type
I have two Registration pages: Register as Buyer, Register as Seller. on both Pages , I've included Normal Registration and social authentication using Google and Facebook. I've added social authentication using Django all-auth, but cannot get user_role. [1][Registration Page]: after Registration : user is redirected to home page and as there is no user_role set in social authentication , one cannot access Buyer or Seller 's section. [2][Signup with Google]: After signup : User is registered as Blank Login. check home page after Google signup: MY TASK : Is to assign user_type on both the buttons: Buyer and Seller. on click button redirect user to its particular Registration Page and Login/Signup with Social Authentication and after Successful-Login Redirect User to its Page and show user_type in Django-administration-panel as: User_type: Buyer; Email:test1234@gmail.com; is_active: True -
One app in Django is enough for whole website?
I'm new to Django framework and currently working on an ecommerce website. Not sure what would be better, when creating new project and new app in Django, does a single app is enough and fine for whole website functionally(all HTML pages, user login/registration etc) or should I use separate apps in my project? -
I want to give users ten coins each time they fill out one form
I want to give users ten coins each time they fill out one form , so i tried this code above and show this error TypeError at /profile unsupported operand type(s) for +=: 'DeferredAttribute' and 'int' error in views.py in line += 10 models.py class User(AbstractUser): user_pic = models.ImageField(upload_to='img/',default="",null=True, blank=True) coins = models.IntegerField(default=100) def gives_user_coins_after_create(sender, instance, created, **kwargs): if created: profile = instance.User.profile profile.coins += 10 profile.save() views.py @login_required(login_url='accounts/login/') def profile(request): # Gives the user 10 coins for fill up one form profile = get_user_model() profile.coins += 10 profile.save() return render(request,'account/profile.html') i tried many code but nothing work , any idea or help please -
Listen on given path using python
I am new to python basically i work in Infra. To test one of AWS service i have written below python code which listen "/ping" GET method and "/invocations" POST method. from flask import Flask, Response app = Flask(__name__) @app.route("/ping",methods=["GET"]) def ping(): return Response(response="ping endpoint", status=200) @app.route("/invocations",methods=["POST"]) def predict(): return Response(response="invocation endpoint here", status=200) if __name__ == "__main__": print("Traninig started") app.run(host="localhost", port=8080) This code works fine but Flask give warning like "Dont use in production". So i was looking to do the same in Django but not able to find appropriate ways to achieve this.Not sure what i am trying to do is even doable but i hope i made it clear what i am trying to do. -
How to print output of Python script on webpage
I want to print the output of pytchat module to my website import pytchat chat = pytchat.create(video_id="uIx8l2xlYVY") while chat.is_alive(): for c in chat.get().sync_items(): print(f"{c.datetime} [{c.author.name}]- {c.message}") See this image On side by side of embedded YouTube video I want to show live chat in the box how can How can I add this output to my website. -
how to use Exists and OuterRef in prefetch_related in Django?
I have 3 models and I need to display the area and need items only if there is at least 1 product connected. If there are no products in particular Area and Need models then it should not appear in my HTML file. I have checked the documentation and several answers related to this topic but I cannot implement it in my script. I also tried to create my custom filter so I can apply it directly in my template but nothing worked. My problem is that I am getting the list of all items from Need model and I don't know how to exclude empty items from HTML page. I will appreciate any help. models.py class Area(models.Model): title = models.CharField(max_length=75, blank=False) body = models.CharField(max_length=150, default='-', blank=False) publish = models.DateTimeField('publish', default=timezone.now) class Need(models.Model): title = models.CharField(max_length=75, blank=False, null=False, help_text='max 75 characters') body = models.CharField(max_length=150, default='-', blank=False) publish = models.DateTimeField(default=timezone.now) need_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='need_area') class ProductCategory(models.Model): title = models.CharField(max_length=400, blank=False, null=False, help_text='max 400 characters') body = models.TextField(default='-') publish = models.DateTimeField('publish', default=timezone.now) category_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='category_area', null=True) category_need = models.ForeignKey(Need, on_delete=models.CASCADE, related_name='category_need', null=True) class Product(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=400, blank=False) category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE, blank=True, related_name='products') … -
Django Detail view Mixin forms post method saving incorrectly
Blog detail page posting comment not saving correctly using django forms, What is the problem? I also searched about that problem but couldn't get problem Models.py file class BlogPost(models.Model): category = models.ForeignKey(Cateqory, related_name='category_id', on_delete=models.CASCADE) blog_image = models.ImageField('blog content backqround image', upload_to='img/') autor_avatar=models.ImageField('autor avatar', upload_to='img/') title = models.CharField('title',max_length=100,db_index=True) slug = models.SlugField(max_length=70,editable=False, db_index=True) content = models.TextField('content') autor_full_name = models.CharField('ful name',max_length=100) created_at =models.DateTimeField('createt_at',auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse_lazy('blog_detail', kwargs={ 'slug':self.slug }) class Comment(models.Model): blog = models.ForeignKey(BlogPost, related_name='blog_id', on_delete=models.CASCADE) user_fullname = models.CharField('full name',max_length=100) content = models.TextField('content') created_at =models.DateTimeField('created_at',uto_now=True) email = models.EmailField(max_length=70, default=None) def __str__(self): return (self.user_fullname) Views.py file class PostDetailView(DetailView, CreateView): template_name = 'blog-detail.html' model = BlogPost form_class = CommentForm def get_success_url(self): return reverse("blog-detail", kwargs={"slug": self.object.slug}) def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data(*args, **kwargs) post = BlogPost.objects.get(slug=self.kwargs['slug']) comments = Comment.objects.filter(blog_id=post) context["blog"] = post context["comment"] = comments context['form'] = CommentForm() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): return super().form_valid(form) when using Formview overwriting form_valid method like that works as expected, but I do not know what is the problem: def form_valid(self, form): new_comment = form.save(commit=False) new_comment.blog = self.get_object() new_comment.save() return super().form_valid(form) -
Django send_mail IntegrityError at /django-store-account/register/ - AWS ElasticBeanstalk
I deployed my aplication on AWS ElasticBeanstalk with https(SSL) and I want to send an verification e-mail to new registred accounts with send_mail but im getting the error that is in the title, I didn't configured environ or any other thing, all the code is below, my gmail is configured for less secure apps too settings.py: if DEBUG: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'pleaeseSomebodyHireMeIWillBeTheHardestWorker@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword bla bla bla' # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' activate page: {% autoescape off %} Hi {{ user.user_name }}, Sua conta foi registrada com https:/{{ jamelaumn.com }}{% url 'account:activate' uidb64=uid token=token %} {% endautoescape %} views.py def account_register(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' current_site = get_current_site(request) message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_message = "<br> oi </br>" email_body = message send_mail(subject=email_subject, message=email_body, from_email=settings.EMAIL_HOST_USER, recipient_list=[ email_to], html_message=html_message) email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to]) email.send() return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): … -
Multi select checkbox doesnt work creating object in django
I have a app where people can declare things, within a decla they can say who was present so they have to pay, only its not working. The edit function works but the fileDecla doesn't. The part that doensn't work is the present people. When i print the people present (via print(request.POST))before i save the decla it gives all the people selected but then it doesnt save them, and when i print(decla.present) i get --> None.(it should be all the people present. Does someone know a solution to this? models.py class Decla(models.Model): owner = models.ForeignKey(Lid, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True, blank=True) content = models.TextField(max_length=50) total = models.FloatField() present = models.ManyToManyField(Lid, related_name="present_leden") receipt = models.ImageField( upload_to="declas/", null=True, blank=True ) ## this will need to be put back to nothing when it ends verwerkt = models.BooleanField(default=False) views.py @login_required(login_url="login") def fileDecla(request): form = DeclaForm() if request.method == "POST": print(1, request.POST) form = DeclaForm(request.POST, request.FILES) if form.is_valid(): # print(form) decla = form.save(commit=False) decla.owner = request.user.lid # i tried this line bellow but it didnt work # decla.present.set(request.POST["present"]) decla.save() messages.info(request, "Decla was created") return redirect("agenda") context = { "form": form, "stand": Stand.objects.get(owner_id=request.user.lid.id).amount, } return render(request, "finance/decla_form.html", context) @login_required(login_url="login") def editDecla(request, pk): decla = Decla.objects.get(id=pk) … -
django.core.exceptions.ImproperlyConfigured: blog.apps.BlogConfig.default_auto_field 'db.models.BigAutoField' that could not be imported
I am following the Django project and I'm into creating class models for my database section for those who know, and my system can't seem to runserver anymore, i'm encountering the following error: Django.core.exceptions.ImproperlyConfigured: blog.apps.BlogConfig.default_auto_field refers to the module 'db.models.BigAutoField' that could not be imported. Initially, I thought it was my Django version, but I pip freeze and saw version 4.0.4 Model.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() post_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) -
Django admin - prevent changing a field after it has become true
i have model in admin.py: class OrderAdmin(admin.ModelAdmin): list_display = ('org_name', 'address', 'total_cost', 'phone', 'data_time', 'is_called', 'is_payed') search_fields = ('org_name', 'phone') list_filter = ('data_time', 'total_cost', 'data_time') list_editable = ('is_called', 'is_payed') readonly_fields = ('data_time', 'user', 'total_cost') inlines = [OrderItemsAdmin, ] I need to do something like: class OrderAdmin(admin.ModelAdmin): list_display = ('org_name', 'address', 'total_cost', 'phone', 'data_time', 'is_called', 'is_payed') search_fields = ('org_name', 'phone') list_filter = ('data_time', 'total_cost', 'data_time') list_editable = ('is_called', 'is_payed') readonly_fields = ('data_time', 'user', 'total_cost') inlines = [OrderItemsAdmin, ] if 'is_called' == True: readonly_fields.append('is_called') i think that it's possible, so the question is how to do that? -
ReadOnly on serializers.py
In this piece of code, in RegUpdate() field 'rooms' should be ReadOnly from rest_framework import serializers from .models import Registration class RegSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'rooms', 'first_name', 'last_name', 'admin', 'pasport_serial_num', 'birth_date', 'img', 'visit_date', 'leave_date', 'guest_count', 'room_bool', 'price') model = Registration class RegUpdater(serializers.ModelSerializer): class Meta: fields = ('id', 'rooms', 'leave_date', 'room_bool') #rooms should be ReadOnly model = Registration -
Pagination on searched data in DJANGO using AJAX call
Iam implementing pagination on searched data. When click on the next button it should display the next 5 sets of records and when click on the previous button it should display the previous 5 sets of records using ajax call.Now my doubt is that how to sent searched value and page number along with data?? read_data.html <!DOCTYPE html> {% load static %} <h3>User List</h3> <div class="card-body" > {% if word %} {% for words in word %} <table class="table table-bordered" style="width:85%;margin-right:auto;margin-left:auto;" id="exa" > <thead class="table-success"> {% endfor %} <tr> <th scope="col">Id</th> <th scope="col">Username</th> <th scope="col">Name</th> <th scope="col">Admin</th> <th scope="col">User</th> <th scope="col">Status</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> {% for words in word %} <tbody> <tr> <th>{{words.id}}</th> <th>{{words.username}}</th> <th>{{words.first_name}}</th> <th>{{words.is_superuser}}</th> <th>{{words.is_staff}}</th> <th>{{words.is_active}}</th> <th><a href="/update_user/{{words.id}}" class="btn btn-success" name="{{words.id}}" onclick="loadDiv3({{words.id}})">Update</a></th> <th><a href="/password_reset/{{words.id}}" class="btn btn-success" name="{{words.id}}" onclick="loadDiv2({{words.id}})">Reset Password</a></th> </tr> {% endfor %} </tbody> </table> <ul class="pagination"> {% if word.has_previous %} <li class="page-item"> <a href="?page={{word.previous_page_number}}&results={{query}}" class="page-link" onclick="loadDiv9({{page}})" id="previous"><<< Previous</center></a> </li> {% endif %} {% if word.has_next %} <li class="page-item"> <a href="?page={{word.next_page_number}}&results={{query}}" class="page-link" id="next">Next >>></a> </li> {% endif %} </ul> {% else %} <p>no records available</p> {% endif %} <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script type="text/javascript" src="{% static 'js/pagination.js' %}"></script> pagination.js $("#next").on('click',function(){ event.preventDefault(); var results=$('#results').val(); var page=$('#page_number').val(); … -
Social Network Login Failure with microsoft graph django allauth
I am trying to log in with outlook it gives an enter image description hereerror -
what should i do to be able to post multiple contents in my code in django rest framework?
This is my serializers.py: from rest_framework import serializers from .models import product class productSerializer(serializers.ModelSerializer): class Meta: model= product fields="__all__" views.py: from django.shortcuts import render from .models import * from rest_framework import viewsets from .serializers import productSerializer from rest_framework.parsers import JSONParser class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class=productSerializer When i want to post multiple contents like this: [ { "Number": 1, "name": "1005001697316642", "image": "https://", "description": "fffffffff", "price": "USD 23.43", "buy": "https://" }, { "Number": 2, "name": "1005002480978025", "image": "https://", "description": "dffdfdddddddddddddd", "price": "USD 0.89", "buy": "https://" } ] I get this error: HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } what should i do to be able to post multiple contents? -
host "localhost" (::1) and accepting TCP/IP connections on port 5432?
I'm trying to set up a Django website that connects to the "default" PostgreSQL db, all within Docker. Note, I'm trying to db inside the postgres image. After running the docker-compose up --remove-orphans command, the error within the title is executed. Can I do anything to fix this? What I am currently using is: Settings.py - DATABASES DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': 5432, } } Dockerfile FROM python:3.7-slim as production ENV PYTHONUNBEFFERED=1 WORKDIR /app/ RUN apt-get update && \ apt-get install -y \ bash \ build-essential \ gcc \ libffi-dev \ musl-dev \ openssl \ postgresql \ libpq-dev COPY requirements/prod.txt ./requirements/prod.txt RUN pip install -r ./requirements/prod.txt COPY manage.py ./manage.py COPY website ./website EXPOSE 8000 FROM production as development COPY requirements/dev.txt ./requirements/dev.txt RUN pip install -r ./requirements/dev.txt COPY . . docker-compose.yml version: "3.7" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: image: "django_image:latest" command: python manage.py runserver 0.0.0.0:8000 volumes: *service-volumes environment: *app-variables depends_on: - db_migrate ports: - "8000:8000" db_migrate: image: "django_image:latest" command: python manage.py migrate volumes: *service-volumes environment: *app-variables depends_on: - postgres postgres: image: "postgres:latest" ports: - "5432:5432" … -
Django / Sending email with Mail Service Prodiver like Mailjet
I have installed django-anymail My SPF and DKIM are configured in my ISP Here is my settings.py : EMAIL_BACKEND = "anymail.backends.mailjet.EmailBackend" ANYMAIL = { "MAILJET_API_KEY": os.getenv('MYAPP_MAILJET_API_KEY'), "MAILJET_SECRET_KEY": os.getenv('MYAPP_MAILJET_API_SECRET'), } EMAIL_HOST = 'in-v3.mailjet.com' EMAIL_HOST_USER = '????' EMAIL_HOST_PASSWORD = '????' EMAIL_HOST_PORT = 587 Views.py send_mail('contact form','click',mail1,[mail2],fail_silently=False) I got confused for EMAIL_HOST_USER and EMAIL_HOST_PASSWORD As I want to use mailjet, is it necessary ? Also is send_mail the right function in this case ? -
How to simulate user intercation in Django?
I have a Django project representing an abstract retail store. Let's say it's deployed on a server and is available in the local network. I want to write another program (or extend this one?) to generate a bunch of Users, automate the process of signing up and logging in and automate their interaction with the system: make them interact with the system to order goods. So it's not just unit testing of my system but rather demonstration of how it works in real life. And I want to spawn many users to see how my system can handle many requests at once. Is there some kind of framework for that? How would you implement this? Thanks. -
Make thumbnail after ImageField save
I want to make thumbnail of an uploaded image after the Imagefield model is saved. At this moment i'm getting raise Exception error: Could not create thumbnail - is the file type valid?". Can you guys help me how to get it working? models.py from django.contrib.auth.models import User from django.db import models from PIL import Image as Img class Image(models.Model): img_owner = models.ForeignKey(User, on_delete=models.CASCADE, default=User) image = models.ImageField(null=True, blank=False) thumbnail = models.ImageField(upload_to="thumbs", editable=False) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-date_added"] def save(self, *args, **kwargs): if not self.make_thumbnail(): # set to a default thumbnail raise Exception("Could not create thumbnail - is the file type valid?") super(Image, self).save(*args, **kwargs) def make_thumbnail(self): size = 128, 128 im = Img.open(self.image) im.thumbnail(size) im.save(self.image.name + ".thumbnail", "PNG") seralizers.py from rest_framework import serializers from .models import Image class ImageSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source="img_owner.username") thumbnail = serializers.ReadOnlyField() class Meta: model = Image fields = ["url", "author", "img_owner", "image", "thumbnail", "date_added"] views.py from rest_framework import permissions, viewsets from .models import Image from .serializers import ImageSerializer class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer permission_classes = [permissions.IsAuthenticated] """ Bellow definition overrides queryset and filter images by loged user. """ def get_queryset(self): user = self.request.user return Image.objects.filter(img_owner=user) -
Reduce time for Loop over multiple objects to get value Django
I have a Dataframe in which a column Code is increased significantly everyday and these codes are to be converted into object description for which I am doing something like the following: product = [] beacon = [] count = [] c_start = time.time() for i, v in df["D Code"].iteritems(): product.append(Product.objects.get(short_code=v[:2]).description) #how to optimize this? beacon.append("RFID") count.append(v[-5:]) c_end = time.time() print("D Code loop time ", c_end-c_start) Now initially when the rows were less it used to work in no time but as the data increased the combined Database call for every code takes too much time. Is there any more efficient Django method to loop over a list and get the value? The df['D Code]` looks something like this: ['TRRFF.1T22AD0029', 'TRRFF.1T22AD0041', 'TRRFF.1T22AD0009', 'TRRFF.1T22AD0032', 'TRRFF.1T22AD0028', 'TRRFF.1T22AD0026', 'TRRFF.1T22AD0040', 'HTRFF.1T22AD0003', 'TRRFF.1T22AD0048', 'PPRFP.1T22AD0017', 'TRRFF.1T22AD0047', 'TRRFF.1T22AD0005', 'TRRFF.1T22AD0033', 'TRRFF.1T22AD0024', 'TRRFF.1T22AD0042'], -
Looping through a nested JSON object format in datatables
I'm looking to iterate through a JSON object in javascript and I also, wonder that whether my json format is correct and efficient or not. https://datatables.net/ I want to show the relationship between tables in a single table. For example, I want to get: ID hospital date type suffix description name prefix description 1 01-01-2021 cov G result Oslo S result 2 03-03-2021 cov G result Oslo S result 3 05-05-2021 cov G result Kiev S result models.py class Samples(models.Model): hospital_date = models.DateField() source_sample = models.ForeignKey(SourceSample, on_delete=models.CASCADE) projects = models.ForeignKey(Projects, on_delete=models.CASCADE) class SourceSample(models.Model): type = models.CharField(max_length=128) suffix = models.CharField(max_length=128) description = models.CharField(max_length=256) class Projects(models.Model): name = models.CharField(max_length=128) prefix = models.CharField(max_length=128) description = models.CharField(max_length=256) json "data": { "samples": { "id": "1", "hospital_date": "01-01-2021", "source_sample": { "type": "T", "suffix": "G", "description": "result" }, "project": { "name": "Valencia", "prefix": "S", "description": "result" }, } } js var table = $('#example').DataTable({ "ajax": { url: "/json", type: "GET" }, "columns": [{"data": "id"}, {"data": "hospital_date"},] Thank you for help. Best regards.