Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MQTT and data reading
I have 3 temperature sensors and I want to read their data and put it on a dashboard to monitor it in real time, how to do it? I want to use MQTT protocol, Python and Django or Flask. Are there tutorials videos where to start? Need help. Is it possible to create such a platform for use at home? Is it possible to create such a platform for use at home? I have 3 temperature sensors and I want to read their data and put it on a dashboard to monitor it in real time, how to do it? I want to use MQTT protocol, Python and Django or Flask. Are there tutorials videos where to start? Need help. Is it possible to create such a platform for use at home? -
How to remove relation from django model with ManyToMany field?
How to remove relation from model with ManyToMany field? I've got a model with ManyToManyField relation. I need to remove relation but not data from the following model: class TxHomes(models.Model): user = models.ManyToManyField(settings.AUTH_USER_MODEL) home_id = models.PositiveIntegerField(primary_key=True, unique=True, null=False) name = models.CharField(max_length=255, null=True) geo_name = models.CharField(max_length=255, null=True) payload = models.JSONField() Django ORM got tables generated: -- auto-generated definition create table main_txhomes ( home_id integer unsigned not null primary key, name varchar(255), geo_name varchar(255), ... ); create table main_txhomes_user ( id primary key autoincrement, txhomes_id ..., user_id ... ); When I apply to do that with a following code TxHomes.objects.filter( home_id__in=TxHomes.objects.filter(user=USER_ID).values('home_id') ,user=USER_ID).delete() i got entire data deleted from main_txhomes I want to keep data in main_txhomes table, what i need is to delete relations from main_txhomes_user table. How to do that? -
Django-ckeditor showing content as textarea
I'm working with django ckeditor now and I can't display content that can be saved normally and is displayed in the admin panel. Content is always displayed as textarea As you can see at the image, editor is working properly, also if i go to admin panel everything is OK, but if i want to display content of "body" ({{ form.body|safe}}), it will display only textarea of HTML code. models.py class Stage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) game_id = models.ForeignKey(Game, on_delete=models.CASCADE) name = models.CharField(max_length=128) sequence = models.IntegerField(null=False) body = RichTextUploadingField(config_name='LeftFields', blank=True, null=True) def get_questions(self): return Question.objects.filter(stage_id = self.id) def __str__(self): return str(self.name) forms.py class StageForm(ModelForm): class Meta: model = Stage fields = ['body','name'] widgets = { 'name': TextInput(attrs={ 'class': "left_input", 'style': "width: 69.3%;", }), } views.py @login_required(login_url='/signin') @user_passes_test(lambda u: u.is_staff) def edit(request, gameid,id): stage = Stage.objects.get(pk=id) if request.method == 'POST': form = StageForm(request.POST, instance=stage) if form.is_valid(): form.save() return redirect('/edit/' + gameid + '/' + id) form = StageForm(instance=stage) return render(request, "homeSuperuser/edit_stage.html", {'stage': stage, 'form': form,'gameid':gameid}) edit_stage.html <!doctype html> <html> <head> {% load static %} <link rel="stylesheet" href="{% static 'css/edit_pages.css' %}" /> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'js/edit.js' %}"></script> </head> <body> … -
Should I use Django, Spring Boot or React?
there are 4 of us in the company and I am the only software guy. We are going to make a web app for a client where orders are going to be taken into account and manufacturing orders (MO) are created in an optimal way. Our client is going to provide us with the data to train an artificial intelligence model that will create the manufacturing orders in an optimal way. The data will be: employees (schedule, calendar...), orders that are created, and manufacturing processes (MP) with their respective dependencies in terms to other MPs. I am thinking about creating the AI with python and deploying it. Then create a web (I don't know which technologies to use. If frontend React or do it all with Spring Boot or Django) and make requests to the AI API. I have no experience with React and with the other two I have very little experience. Which technology should I use? I would also appreciate any help regarding artificial intelligence since I only know that I am going to use Python for it. I think the best solution is to use Django since I understand Python and the project is in a bit … -
Passing a list to Django template from include
I have an include tag for template that needs to render a list passed from include tag. https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#include {% include "list.html" with animal_list=["Cat","Dog"] %} -
Need to edit django get request to include list of models given a list of id's
I'm currently creating the backend for a website in which users can add public events/gatherings to their favorites list. I'm currently creating a model in Django which models a user created account named Account. I want to implement it so that Account includes a field called "favorites" which stores the id's of the Events that the specific account added to their favorites. class Account(models.Model): username = models.CharField(max_length=20, null=True) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) email = models.EmailField(max_length=254, null=True) phone_number = models.CharField(max_length=254, null=True) class Favorites(models.Model): favorite = models.PositiveIntegerField(null=True) account = models.ForeignKey(Account, related_name='favorites', on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.favorite}" class Events(models.Model): event_image = models.ImageField(null=True) # will have to figure out where this image is uploaded to event_name = models.CharField(max_length=50, null=True) event_date_time = models.DateTimeField(max_length=50, null=True) event_location = models.CharField(max_length=50, null=True) event_description = models.TextField(null=True) Currently I can send a post request of this form, for this example this specific account favorited Events with id of 15 and 17. { "username": "Name", "first_name": "John", "last_name": "Doe", "email": "Johndoe@gmail.com", "phone_number": "6666666666" "favorites": [{favorite: "15"}, {favorite: "17"}] } However after sending a post request like that I want to have my get request be of this form { "username": "Name", "first_name": "John", "last_name": "Doe", "email": "Johndoe@gmail.com", … -
Unable to authenticate using cookie-based authentication in Django React
I am trying to run a Django server and React app with cookie-based authentication. The authentication is being done using django-graphql-jwt and Apollo Client. The authentication process works correctly and I am receiving a JWT token, but the cookies are not being set. Here is my setting files: basic.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'todolist', # Pip packages 'stripe', 'corsheaders', "graphene_django", 'graphql_jwt', 'graphql_jwt.refresh_token.apps.RefreshTokenConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # Corsheaders 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # Whitenoise #"django_graphql_ratelimit.middleware.ParseClientIpMiddleware", # Django graphql ratelimit ] # Password validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] development.py import os DEBUG_VALUE = os.getenv('DEBUG') SECRET_KEY = os.getenv('SECRET_KEY') # Server is running in production if DEBUG_VALUE == False or DEBUG_VALUE == 'False': # HTTPS settings CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # Corsheaders CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:8000', 'http://localhost:3000', 'https://my-todo-app-frontend-site.netlify.app' ] ALLOWED_HOSTS = [ '127.0.0.1', '.vercel.app', 'www.my-todo-app-frontend-site.netlify.app' ] # Whitenoise STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ROOT_URLCONF = 'backend.urls' WSGI_APPLICATION = 'backend.wsgi.application' … -
django unique constraint fails
I am creating a book model, and with that model, there is a isbn variable that should have the unique constraint set to true which should stop there from being duplicate isbn values in my database. however when unit testing this model, the test_isbn_must_be_unique() test fails to raise the validation error even though I have set unique to be true in the book model. I was expecting the test to pass since I had set unique to be true in the list of constraints for the isbn variable. however, the test fails. `# models.py file from django.core.validators import RegexValidator from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField( max_length=30, unique=True, validators=[RegexValidator( regex=r'^@\w{3,}$', message='Username must consist of @ followed by at least three alphanumericals' )] ) first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) email = models.EmailField(unique=True, blank=False) bio = models.CharField(max_length=520, blank=True) class Book(models.Model): isbn = models.CharField(max_length=13, unique=True, null=False, blank=False) book_title = models.TextField(blank=False, max_length=500) book_author = models.CharField(blank=False, max_length=255) year_of_publication = models.CharField(max_length=13, blank=False) publishers = models.CharField(blank=False, max_length=255) image_url_s = models.CharField(blank=False, max_length=255) image_url_m = models.CharField(blank=False, max_length=255) image_url_l = models.CharField(blank=False, max_length=255)` `"Testing Book Model" from django.test import TestCase from django.core.exceptions import ValidationError from clubs.models import Book class BookModelTestCase(TestCase): def setUp(self): … -
'User' object has no attribute 'user_type' - Django Custom User model issue
I've created a custom user abstract model and profile model to collect additional information once the user registers. I am collecting "User type: Employer/employee" at the time of registration but this doesn't seem to be recognized in the profile view. Despite the user being correctly added into the DB (I checked via Admin). For example, I created user: asus23910 (employer user type). But when I login and redirect to http://127.0.0.1:8000/employer_profile/asus23910/, I get following error: 'User' object has no attribute 'user_type'C:\Users\ASUS\PycharmProjects\Content\content\content\views.py, line 112, in employer_profile_view 1. Here's my employer_profile_view.py code: def employer_profile_view(request, username): user = User.objects.get(username=username) if user.user_type != User.EMPLOYER: # Redirect to the correct profile page if the user type is not employer return redirect('employee_profile', username=request.user.username) if request.method == 'POST': form = EmployerProfileForm(request.POST, instance=user.employerprofile) if form.is_valid(): employer_profile = form.save(commit=False) employer_profile.user = user employer_profile.save() return redirect('employer_profile', username=request.user.username) else: form = EmployerProfileForm(instance=user.employerprofile) context = { 'form': form, 'username': username, } return render(request, 'employer_profile.html', context) 2. Employer Profile model and connector class EmployerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField( max_length=10, choices=User.USER_TYPE_CHOICES, default=User.EMPLOYER ) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) title = models.CharField(max_length=255) company_name = models.CharField(max_length=255) company_logo = models.ImageField(upload_to='company_logos/') company_location = models.CharField(max_length=255) company_website = models.URLField() company_twitter = models.URLField() #one-2-one connector @receiver(post_save, sender=User) def … -
How to limit the image file size in image field in django admin panel (on client side)?
I am having few inline fields which have image field in them, what i'm trying to do is to determine the file size at the time of image selection, by selection I i would like to restrict the user before the request has been submitted. and I can do the file size check on the server using validators but in a few cases even before the validator can handle issue I got DATA_UPLOAD_MAX_MEMORY_SIZE exception, I do have enlarged the size , but still i could get that error that error of request body is exceeding max upload size. here is my code for the menu image class MenuImage(models.Model): """Salon Image Model""" class Meta: verbose_name = _("Menu Image") verbose_name_plural = _("Menu Images") salon = models.ForeignKey( Salon, on_delete=models.CASCADE, related_name='menu_images', null=True, blank=True) image = models.ImageField(upload_to='salon_images', help_text="Dimensions should in 175 x 100 px") def __str__(self): return self.salon.full_name def save(self, *args, **kwargs): compressed_image = ImageResizing.custom_resizing_and_compress(self.image) self.image = compressed_image super().save(*args, **kwargs) and this is how I am using it as an inline field class SalonModelAdmin(DjangoObjectActions, admin.ModelAdmin): inlines = [OpeningHoursInline, GalleryInline,MenuImageInline, SalonBankDetailInline, SalonLegalDocumentInline, SalonContactInline] fields = ("full_name","contact_number","neighbourhood", "salon_location","explore","salon_service","home_services", "featured","categories","commission", "cover_image","transportation_cost", "home_service_order_limit","logo_image", "salon_description","preference","auto_booking", "trending", "disable",) list_display = ("salon", "featured", "home_services", "contact_number", "commission",) search_fields = ['full_name'] list_filter = ("featured", … -
Django: How do I assign a button to take info and save()
Is there a way for the button to do the following? : When user press the button it takes the user.username of the current user and automatically fill up a form of BookInstance from models.py and save it to the database. From models.py : class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) book = models.ForeignKey("Book", on_delete=models.RESTRICT, null=True) imprint = models.CharField(max_length=200, blank=True, null=True) due_back = models.DateField(blank=True, null=True) borrower = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On Loan'), ('a', 'Available'), ('r', 'Reserved') ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='a') class Meta: ordering = ['due_back'] def __str__(self): return f'{self.id} - {self.book.title}' def get_absolute_url(self): return reverse("catalog:book_list") class Book(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey( 'Author', on_delete=models.SET_NULL, null=True) summary = models.TextField( max_length=500, help_text="Enter brief description") isbn = models.CharField('ISBN', max_length=13, unique=True) genre = models.ManyToManyField(Genre, help_text="Select genre") language = models.ForeignKey( "Language", on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("catalog:book_detail", kwargs={"pk": self.pk}) This is my from my views.py : def borrowBook(request, pk): context = { 'book_instance': BookInstance.objects.all() } success_url = reverse_lazy('catalog:index') if request.method == "POST": form = BorrowForm(request.POST or None) if form.is_valid(): book_instance.id = BookInstance.objects.get(pk=pk) book_instance.book = BookInstance.objects.get(book=book) book_instance.borrower = request.user book_instance.status = 'o' book_borrowed_count = BookInstance.objects.filter( owner=request.user).count() if book_borrowed_count < … -
Using S3 and Django project: Imported javascript modules are not including the "X-Amz" parameters thus getting 403
On the HTML page I'm including a script with: <script type="module" src="{% static 'home/js/country/country.detail.js' %}"></script> That script loads just fine and then imports other modules: // country.detail.js file import FooConverter from "./foo.converter.js"; import Alert from "/static/app/alert.messenger.js"; import MESSAGES from "/static/app/messages.txt.js"; When the browser makes the request to fetch those other modules from the S3 bucket I get a 403 - Forbidden status code, because the browser is not including the "X-Amz" parameters: This is the request when the browser is fetching the fee.converter.js script (this one load fine): https://bucketname.s3.us-east-2.amazonaws.com/static/home/js/country/country.detail.js?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=creds%2F20230207%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20230207T145100Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=a5364797888bb0b7ce5ead84c656734dbd8b3093af43cf4ddc34a5734c28d743 This is the request when fetching alert.messenger.js (the response is 403, because it's missing the X-Amz parameters): https://bucketname.s3.us-east-2.amazonaws.com/static/app/alert.messenger.js How can I solve this? django-storages==1.13.1 Django==3.2.6 This is the CORS configuration in the bucket: { "CORSRules": [ { "ID": "allow-auth", "AllowedHeaders": [ "Authorization" ], "AllowedMethods": [ "GET" ], "AllowedOrigins": [ "*" ], "MaxAgeSeconds": 3000 }, { "ID": "allow-GET-locahost", "AllowedHeaders": [ "*" ], "AllowedMethods": [ "HEAD", "GET" ], "AllowedOrigins": [ "http://localhost" ], "ExposeHeaders": [ "ETag", "x-amz-meta-custom-header" ] } ] } -
django pagination with search not working
MultiValueDictKeyError at /search/ 'search' Request Method: GET Request URL: http://127.0.0.1:8000/search/?page=2 Django Version: 4.1.5 Exception Type: MultiValueDictKeyError Exception Value: 'search' Exception Location: C:\Python311\Lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: blogs.views.search Python Executable: C:\Python311\python.exe Python Version: 3.11.0 views.py def search(request): search = request.POST["search"] blog_search = Blog.objects.filter(Q(title__icontains=search) | Q(description__icontains=search)) paginator = Paginator(blog_search, 5) page_number = request.GET.get('page') blogs = paginator.get_page(page_number) return render(request,"frontend/searchblogs.html",{"blogs":blogs}) <div class="container"> <nav class="navbar navbar-light bg-light justify-content-end"> <form class="form-inline" method="post" action="{%url 'search' %}"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id="search" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </nav> <h4 class="mt-4"></h4> {% for blog in blogs %} <div class="card mb-3" > <div class="row no-gutters"> <div class="col-md-4"> <img src="{{blog.cover_img.url}}" alt="..." class="bd-placeholder-img card-img-top img-fluid"> </div> <div class="col-md-8"> <div class="card-body"> <h4 class="card-title text-truncate">{{blog.title}}</h4> <p class="card-text text-truncate">{{blog.description}}</p> <div class="d-flex justify-content-between align-items-center"> <p class="text-muted">{{blog.date.date}}</p> <p class="text-muted"><i class="fa fa-eye pl-2"></i> {{blog.view}}</p> </div> </div> </div> </div> <a href="{%url 'blogdetail' blog.id %}" class=" stretched-link "></a> </div> {% endfor %} <nav aria-label="Page navigation example"> <ul class="pagination justify-content-end"> {% if blogs.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ blogs.previous_page_number }}">Previous</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1" aria-disabled="True">Previous</a> </li> {% endif %} {% if blogs.number|add:'-4' > 1 %} <li class="page-item"><a class="page-link" href="?page={{ blogs.number|add:'-5' }}">&hellip;</a></li> {% … -
Django OTP authenticate user without password
I want to send a link to my users and when they press it, it asks for an OTP sent to the same email address. I would like to allow users with an email to login with OTP. To manually authenitcate django seems to require a Password to be passed. The user doesn't have a password I want them to login with the OTP sent to the email. What would be the best way to go about this? -
Multiple Dependent Dropdown in Django
I Need two pair dependent dropdown Field name: Country Field name: State note - Field name: Country and Field name: state should be dependent dropdown Field name: Product(Vegitable,Fruit) Field name: name of product note - Field name: Product(Vegitable,Fruit) and name of product should be dependent dropdown if I select Vegetable then Cabadge,Patato has to reflect and i select Fruit then Apple, Orange has to reflect 5. Field name : Status Category are Testing1,Testing2,Testing3 6. DateTime : mm-dd-yyyy hh:mm:ss Request please create small crud -
RuntimeError at /signup: Change your form to point to 127.0.0.1:8000/signup/ , or set APPEND_SLASH=False in your Django settings
RuntimeError at /signup You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/signup/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. I got this problem while using forms. Please help I have used bootstrap for styling <form action="/signup/" method = "post" > {% csrf_token %} <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1">@</span> <input type="text" class="form-control" placeholder="Username" name = "username" aria-label="Username" aria-describedby="basic-addon1"> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Firstname" name="fname" aria-describedby="basic-addon1"> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Lastname" name="lname" aria-describedby="basic-addon1"> </div> <div class="input-group mb-3"> <input type="email" class="form-control" placeholder="Recipient's email" name="email" aria-describedby="basic-addon2"> <span class="input-group-text" id="basic-addon2">@gmail.com</span> </div> <div class="input-group mb-3"> <input type="password" placeholder="password" name = "password" class="form-control"> </div> <div class="input-group mb-3"> <input type="password" placeholder="confirm password" name = "con_password" class="form-control"> </div> <div class="input-group mb-3"> <button type="submit" class="btn btn-primary">Signup</buttpn> </div> </form> </div> Views.py def signup(request): if (request.method == "POST"): username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") con_password = request.POST.get("con_password") User.objects.create_user(username=username, first_name=fname, last_name=lname, email=email, password=password) User.save() messages.success(request, "Account created successfully") return redirect("login") Should Redirect to login Page -
how to validation fields for TabularInline in django admin?
I create a BaseInlineFormSet like this: class `enter code here`ProductPictureRequiredFormSet(forms.models.BaseInlineFormSet): def clean(self): if self.cleaned_data["image"] == None: raise ValidationError("error") return self.cleaned_data["image"] and use this formset in my TabularInline class: class ProductPictureAdminInline(SortableTabularInline): formset = ProductPictureRequiredFormSet fields = ("title", "image", "is_default", "order", "created_by", "created_at", "updated_at") readonly_fields = ("created_by", "created_at", "updated_at") model = ProductPicture extra = 3 but i got this error: -
How to convert export Django QuerySet to one dictonary?
How to convert export Django QuerySet to one dictonary? I want to insert Django QuerySet as data_source into DataTable for Bokeh queryset = Model.objects.all() qs = queryset.values() qs = dict(qs) header = [field.verbose_name for field in Model._meta.get_fields()] columns = [TableColumn(field=col, title=col) for col in header] source = ColumnDataSource(qs) data_table = DataTable(source=source, columns=columns) script, div = components(data_table) qs = dict(qs) ^^^^^^^^ ValueError: dictionary update sequence element #0 has length 11; 2 is required -
Django (v4) request.META['REMOTE_ADDR'] not working anymore?
I had been using for years (Django 1.9 & Python 2.7) request.META dictionary and ['REMOTE_ADDR'] header to get client's IP address. I have recently moved to Django 4.1.5 and found out that my code is not able anymore to get client's IP address, so I had to use: x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip which works fine. I've tested my old code in development mode and tried to log request.META.get('REMOTE_ADDR'). The code will log IP only if the IP address is localhost (127.0.0.1). With any other IP address, REMOTE_ADDR header stays blank. I'm just curious, could someone tell me why this is happening? -
Greater than for INET IP address field in PostgreSQL Version > 9
So I have wrote my own lookups for PostgreSQL INET field in my DRF App as Django does not natively support those PostgreSQL specific fields. I use my own IP field in my objects to support my own lookups. All my lookup work find, except for those two: class HostGreaterOrEqual(Lookup): """ Lookup to check if an IP address is greater than or equal. Used for net ranges""" lookup_name = "host_greater_or_equal" def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return "%s >= %s" % (lhs, rhs), params class HostLessOrEqual(Lookup): """ Lookup to check if an IP address is less than or equal. Used for net ranges""" lookup_name = "host_less_or_equal" def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return "%s <= %s" % (lhs, rhs), params In my models I have a address and address_end field to store IP Ranges. I wanted to use those lookups above to make the proper queries like this: items = queryset.filter( Q(address__host_greater_or_equal=value) & Q(address_end__host_less_or_equal=value) ) In the documentation for PostgreSQL Version 9 I can see the operators for "is lass or equal" and "is … -
Having trouble with pyodbc on django
I am working on django project. And testing Sql Server database. I am using korean linux hosting service gabia. So I don't have any root access. Even this hosting company blocked yum and rpm. Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: libodbc.so.2: cannot open shared object file: No such file or directory I am keep having this kind of trouble when I import pyodbc. But I can fully use pymssql module. I have no idea what is wrong with this linux... This is when I connect django to mssql database with mssql-django package. Traceback (most recent call last): File "/web/.local/lib/python3.9/site-packages/mssql/base.py", line 16, in <module> import pyodbc as Database ImportError: libodbc.so.2: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/web/.local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 130, in __call__ signals.request_started.send(sender=self.__class__, environ=environ) File "/web/.local/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 176, in send return [ File "/web/.local/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/web/.local/lib/python3.9/site-packages/django/db/__init__.py", line 46, in reset_queries for conn in connections.all(): File "/web/.local/lib/python3.9/site-packages/django/utils/connection.py", line 76, in all return [self[alias] for alias in self] File "/web/.local/lib/python3.9/site-packages/django/utils/connection.py", line … -
display an image on my pdf generate with render_to_pdf
I would like to display an image on my pdf that I generated from information views.py class GeneratePdf(View): def get(self, request, *args, **kwargs): data={'name':'toto','age':122,'service':'smapa'} pdf = render_to_pdf('cart/commande.html',data) return HttpResponse(pdf, content_type='application/pdf') utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return result.getvalue() return None commande.html {% load static %} "" <body> <div class='wrapper'> <div class='header'> <p class='title'>Invoice # </p> <img src="{% static 'images/tof.png' %}" style="width:100px;height: 100px;"> </div> <div> <div class='details'> name: {{name}}<br/> age: {{age}} <br/> service: {{service}} <hr class='hrItem' /> </div> </div> </body> "" I cannot display the image, at the level of the pdf document it is mentioned at the level of the execution console, Need a valid file name -
"LoadMore" button on "Category product list" does not sort products by category
I did "Load More" button for "Product list" with tutorial and trying do like this on "Category product list", but it doest work normal. My files: Views.py def product_list(request): total_data = Product.objects.count() data = Product.objects.all().order_by('-id')[:1] cats = Product.objects.distinct().values('category__title', 'category__id') return render(request, 'product_list.html', { 'data': data, 'cats': cats, 'total_data': total_data, }) def category_product_list(request, cat_id): category = Category.objects.get(id=cat_id) total_data = Product.objects.filter(category=category).count() data = Product.objects.filter(category=category).order_by('-id')[:1] return render(request, 'category_product_list.html', {'data': data, 'total_data': total_data}) def load_more_data(request): offset = int(request.GET['offset']) limit = int(request.GET['limit']) data = Product.objects.all().order_by('-id')[offset:offset+limit] t = render_to_string('ajax/product-list.html', {'data': data}) return JsonResponse({'data': t}) def load_more_dataCat(request): offset = int(request.GET['offset']) limit = int(request.GET['limit']) data = Product.objects.filter(category=True).order_by('-id')[offset:offset+limit] t = render_to_string('ajax/category_product_list.html', {'data': data}) return JsonResponse({'data': t}) custom.js $(document).ready(function(){ $("#loadMore").on('click', function(){ var _currentProducts = $(".product-box").length; var _limit = $(this).attr('data-limit'); var _total = $(this).attr('data-total'); console.log(_total) // Start Ajax $.ajax({ url:'/load-more-data', data:{ limit: _limit, offset: _currentProducts }, dataType:'json', beforeSend:function(){ $("#loadMore").attr('disabled',true); $(".load-more-icon").addClass('fa-spin'); }, success:function(res){ $("#filteredProducts").append(res.data); $("#loadMore").attr('disabled',false); $(".load-more-icon").removeClass('fa-spin'); var _totalShowing = $(".product-box").length; if(_totalShowing==_total){ $("#loadMore").remove(); } } }); // End }); }); $(document).ready(function() { $("#loadMoreCat").on('click', function () { var _currentProducts = $(".product-box").length; var _limit = $(this).attr('data-limit'); var _total = $(this).attr('data-total'); console.log(_total) // Start Ajax $.ajax({ url:'/load-more-dataCat', data:{ limit: _limit, offset: _currentProducts }, dataType:'json', beforeSend:function(){ $("#loadMoreCat").attr('disabled',true); $(".load-more-icon").addClass('fa-spin'); }, success:function(res){ $("#categoryProducts").append(res.data); $("#loadMoreCat").attr('disabled',false); $(".load-more-icon").removeClass('fa-spin'); var _totalShowing = $(".product-box").length; … -
why first parameter is send as id to views in django
while writing urls if i write interchange position of int:post_id with share it is not working. urls.py of application urlpatterns = [ #path("",views.list_view,name="post_list"), path("",views.PostListView.as_view(),name="post_list"), path("<str:post>/<int:id>/",views.post_detail,name="post_details"), path('<int:post_id>/share/',views.post_share,name="post_share"), #if i write a path like this path('share/<int:post_id>/',views.post_share,name="post_share"), #it is not working. ] views.py (only part where i have problem) def post_share(request,post_id): #post=get_object_or_404(Post,status=Post.Status.PUBLISHED,id=post_id) #post=get_object_or_404(Post,status=Post.Status.PUBLISHED,id=id) post = get_object_or_404(Post,id=post_id, status=Post.Status.PUBLISHED) #post=Post.objects.get(id=3) sent=False if request.method=='POST': form=EmailPostForm(request.POST) if form.is_valid(): cd=form.cleaned_data print(cd) post_url=request.build_absolute_uri(post.get_absolute_url) subject=f"{cd['name']} recommends {post.title}" message=f'Here is the link to read {post_url}' send_mail(subject,message,'abcxyzalpha42@gmail.com',[cd['to']]) sent=True else: form=EmailPostForm() context={'form':form,'post':post,'sent':sent} return render(request,'app1/post/post_share.html',context) -
Get all records with the same Field1 and different Field2 Django ORM
Good afternoon! I have a model of the following format class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') address = models.CharField(max_length=255, null=True, blank=True) .... I need to get all the records with the same address, but with different user. Tell me, please, how can I fulfill this request? A request in this format outputs an error orders = Order.objects\ .filter(...)\ .distinct('address', 'user')\ .annotate(Count('address')\ .filter(address__count_gt=1) NotImplementedError: annotate() + distinct(fields) is not implemented. And if so, then count counts incorrectly and I lose data because of values (I need not to lose the order object) orders = Order.objects\ .filter(...)\ .values('address', 'user')\ .distinct()\ .annotate(Count('address')\ .filter(address__count_gt=1)