Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i serve media and static files in production (aws ec2) of django project which is there on aws s3?
While I am running my project locally it is properly serving the static and media files from AWS s3 but when it is hosted on ec2 through Nginx it is serving the files from local static files? How can I fix the issue? -
'Page not found error' while creating rest-api using django rest framework
I declared the URL pattern correctly, but I get 'Page Not Found error' if I go to the 'localhost:8000/rest' URL. here is the code snippet - from myspace import views from rest_framework import routers from rest_api import views as rest_api_views router = routers.DefaultRouter() router.register(r'post', rest_api_views.GetEntryViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('rest/',include('rest_framework.urls', namespace='rest_framework')), path('', include('myspace.urls')), ] -
Add more classes to my forms' attrs in my Django app
So I have a form in Django and I render in in a HTML file. I have widgets in my form with a class named 'form-control'. What I want is to add more than one class to it, because I want to add the 'is-invalid' class to check the validation and show feedback with colors to the user as I would do in a normal form class in HTML. The problem is that I have tried adding the class but it won't work. My form.py: class WordForm(forms.Form): Word1 = forms.CharField(required = True, label= 'Word1', widget= forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter First Word' })) Word2 = forms.CharField(required = True, label= 'Word2', widget= forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Second Word' })) Word3 = forms.CharField(required = True, label= 'Word3', widget= forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Third Word' })) Result = forms.CharField(label= 'Result', required=False, widget= forms.TextInput(attrs={'class': 'form-control', 'readonly': 'True'})) My form.html <div class="form-group"> <div class="inputs "> <form method="post" class="needs-validation" novalidate> {% csrf_token %} <h2>Inputs</h2> {{ form.as_p }} </form> </div> As you can see, I have the {{form.as_p}} there, so I can't add classes to the inputs normally. How do I do it? Help is much appreciated -
Django and materialized views
I have connected my Postgres ddbb with django. With inspectdb I have brought all my tables to models.py. However, I can't find any command for bringing my materialized views to models.py I have tryed: python manage.py inspectdb --database=name_ddbb --include-views But it only gives me the views, not the materialized views. How can I add automatically the materialized views to django? Thanks! -
Django: Change root url in application
I have a working application/system (Python 3.9, Django 3.1) on my server. Now I need to move it to another server with an alias. From this www.myserver.com to this www.otherserver.com/myapp. In Apache2 config I have line WSGIScriptAlias /myapp /path/to/myapp/wsgi.py. But now I have a problem with all links in app, e.g. link from index page to catalog page redirects to www.otherserver.com/catalog but I need www.otherserver.com/myapp/catalog. Is there any feature in Django? Is it possible to set just some global variable in settings.py? Do I need to edit all the links in the templates? What is the best solution? -
Django advanced searching
I was hoping that somebody could give me advice on what i'm trying to do. I have created a search engine for my application but i would like to take it to the next level. Here's my current query method : def search(self, query=None) : qs = self if query is not None : qs = qs.filter(Q(name__icontains=query) | Q(tags__name__icontains=query)).distinct() return qs I would also like to return objects with similar names. For example, if i have an object named "Children" and the query is "Child", the search won't return my object. Is there to compare the number of similar charcaters. I hope that you understand my question, considering how terrible my english is. Thanks for your help -
Django how to get one result using slicing queryset
I have to fetch the usernames of my authors' posts Here the views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.utils import timezone from .forms import CreateUserForm from .models import Post from .forms import PostForm def counter(request): authors = Post.objects.values_list('author', 'title') authors_id = Post.objects.values_list('author') authors_name = User.objects.get(id=authors_id) context = {'authors':authors, 'authors_name':authors_name} return render(request, 'account/counter.html', {'authors': authors}) My models.py is: from django.db import models from django.conf import settings from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title And here my forms.py: from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import Post class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2','user_permissions','is_staff','date_joined'] class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'text', 'author'] Now the problem is that on 'authors_id' I have this Error: The QuerySet value for an exact lookup must be limited to one result using … -
is there anyway i can replace the number by input in the code to variable in django?
I am writing the code like this for now. But what i want is to replace the 0.00024 to variable. {{'Total (USD)'}} {{order.initial_total | times: 0.00024 | integer}}$ -
how to transfer context from a view to another or even make it global
I would like to use profile_form.instance.class_key in other views or make it a global variable.THe profile_form.instance.class_key variable only works on the register view('home.html' template).How can I make it work in other templates too? views.py def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data = request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile_form.instance.class_key = request.user.class_key profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True return redirect('/login/') else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'home.html', {'user_form': user_form, 'profile_form':profile_form, 'registered' : registered}) I defined the forms and the models. forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) repeat_password = forms.CharField(widget=forms.PasswordInput()) def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError("username already exists") return username def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email already exists") return email def clean(self): data = self.cleaned_data password = self.cleaned_data.get('password') repeat_password = self.cleaned_data.get('repeat_password') if repeat_password != password: raise forms.ValidationError("Passwords don't match") class Meta(): model = User fields = ('username', 'email', 'password','repeat_password') class UserProfileInfoForm(forms.ModelForm): DEMO_CHOICES = ( ('empty', 'empty'), ('11A', '11A'), ('11B', '11B'), ) security_key = forms.CharField(max_length=6) class_key = forms.ChoiceField(choices=DEMO_CHOICES,required=True) def clean(self): security_key = self.cleaned_data.get('security_key') class_key = self.cleaned_data.get('class_key') if security_key == 'a45id8' and class_key == '11A' : … -
How is postgis treating coordinates sent with different SRID
I am running a django application and I am using the PostGis extension for my db. I am trying to understand better what happens under the hood when I send coordinates, especially because I am working with different coordinate systems which translate to different SRIDs. My question is threefold: Is django/postgis handling the transformation when creating a Point or Polygon in the DB. Can I query it back using a different SRID Is it advisable to use the default SRID=4326 Let's say I have a model like this (note I am setting the standard SRID=4326): class MyModel(models.Model): name = models.CharField( max_length=120, ) point = models.PointField( srid=4326, ) polygon = models.PolygonField( srid=4326, ) Now I am sending different coordinates and polygons with different SRIDS. I am reading here in the django docs that: Moreover, if the GEOSGeometry is in a different coordinate system (has a different SRID value) than that of the field, then it will be implicitly transformed into the SRID of the model’s field, using the spatial database’s transform procedure So if I understand this correctly, this mean that when I am sending an API request like this: data = { "name": "name" "point": "SRID=2345;POLYGON ((12.223242267 280.123144553))" "polygon": "SRID=5432;POLYGON … -
Wow Slider is not showing data from database as a slider
I am creating an E-Commerce site using Django and Django Rest API. In front end I am using an E-commerce template created using Bootstrap 3 framework. There is a Wow Slider Version 2 in the website, where product is showing from database using ajax. When I use plain HTML the slider is showing product horizontally in a row but when I use product from database all the product is showing vertically, one after another not as a row. My code : <div class="block-top-categori"> <div class="title-of-section">Hot Categories</div> <div id="HotCategoriesList" class="owl-carousel nav-style2" data-nav="true" data-autoplay="false" data-dots="true" data-loop="true" data-margin="20" data- responsive='{"0":{"items":1},"480":{"items":2},"640":{"items":3},"768": {"items":2},"992":{"items":4}}'> </div> </div> <script> var xhttp2 = new XMLHttpRequest(); xhttp2.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var AllHotCategoriesList = JSON.parse(this.responseText); var HotCategoriesList = document.getElementById("HotCategoriesList"); var AllHotCategoriesListLength = (AllHotCategoriesList.length); for (i = 0; i < 6; i++) { HotCategoriesList.innerHTML += `<div class="block-top-categori-item"> <a href=""><img src="{% static 'images/home5/h3.jpg' %}" alt="h3"></a> <div class="block-top-categori-title">Shoes Sport</div> </div>` } } }; xhttp2.open("GET", "{% url 'ListAddCategory' %}", true); xhttp2.setRequestHeader("content-Type", "application/json"); xhttp2.send(); </script> -
ModuleNotFoundError: No module named MY_APP problems with django web deployed with Heroku
I deployed my Django web site with Heroku but there's an application error. I can run this in local server with "heroku local" also in virtual env with "python manage.py runserver" and the site has been deployed. I've made requirements.txt , runtime.txt and Pacfile too. I see error messages when I command 'heroku logs --tail' 2021-02-16T20:26:35.823862+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-02-16T20:26:35.823862+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-02-16T20:26:35.823863+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked 2021-02-16T20:26:35.823863+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-02-16T20:26:35.823863+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-02-16T20:26:35.823864+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-02-16T20:26:35.823864+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked 2021-02-16T20:26:35.823864+00:00 app[web.1]: ModuleNotFoundError: No module named 'portfolio' 2021-02-16T20:26:35.824001+00:00 app[web.1]: [2021-02-16 20:26:35 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-02-16T20:26:35.856818+00:00 app[web.1]: [2021-02-16 20:26:35 +0000] [4] [INFO] Shutting down: Master 2021-02-16T20:26:35.856905+00:00 app[web.1]: [2021-02-16 20:26:35 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-02-16T20:26:35.918015+00:00 heroku[web.1]: Process exited with status 3 2021-02-16T20:26:35.980096+00:00 heroku[web.1]: State changed from starting to crashed 2021-02-16T20:26:36.601488+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=poianakim.herokuapp.com request_id=93a834d5-7212-499d-9f98-f02936bc7459 fwd="95.239.217.192" dyno= connect= service= status=503 bytes= protocol=https 2021-02-16T20:26:37.057729+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=poianakim.herokuapp.com request_id=34840aae-ab2d-49d5-8143-df2f0d30d8bf … -
A large number of problems with react, django, django rest and axios
I am going through a very good course about setting up an e-shop, but I have reached the stage, where I am not that much sure, what is the exact purpose of the code, which I have written. (especially the async function in HomeScreen.js) We are using React and Django. My issue is related to the homepage or HomeScreen.js file, which was working fine, when I was loading the products from the static products.json file, but later on in the course, we had to switch this and load the products from an api using django-rest and axios and my problem now is, that I am not able to load the products to the HomeScreen.js and all I see is a blank page with the header instead of a full page. I am running the react server through the npm start command, but also tried to run the django server, It gives me this error - OSError: [WinError 123]. Please let me know, if You can see some solution these problems. Thank You very much for any help in advance. The page looks like this - And it should look like this - When I am looking to my console, I … -
Django serializer won't save to database
im making small rest api that takes ip address then sends it to ipstack and saves returned data do database. The problem is my data is not saving when calling serializer.save. I'm sure that this is some small issue but i spend soo much time looking at this code that i don't see anything Don't mind if the data from ip isn't correct here I've changed it let's start with the models.py class Location(models.Model): ip = models.CharField(max_length=15) type = models.CharField(max_length=6) latitude = models.DecimalField(max_digits=10, decimal_places=8) longitude = models.DecimalField(max_digits=10,decimal_places=0) continent_code = models.CharField(max_length=2) continent_name = models.CharField(max_length=20) country_code = models.CharField(max_length=10) country_name = models.CharField(max_length=70) region_code = models.CharField(max_length=10) region_name = models.CharField(max_length=50) city = models.CharField(max_length=100) zip = models.CharField(max_length=10) def __str__(self): return str(self.ip) serializer from rest_framework import serializers from .models import * class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location exclude = ['id'] vievws ip = '89.64.124.126' if ip: try: data = location_search.get_location(ip) if data is None: return Response(status=status.HTTP_400_BAD_REQUEST,) except: return Response("Our services are temporarily unavailable", status=503,) serializer = self.serializer_class(data=data) print(serializer) print(serializer.is_valid()) if serializer.is_valid(): serializer.save() return Response("Data was successfully added", status=status.HTTP_201_CREATED,) else: return Response("Database error occurred, try again later",status=status.HTTP_500_INTERNAL_SERVER_ERROR,) this is what i get when printing LocationSerializer(data={'ip': '89.64.124.126', 'type': 'ipv4', 'continent_code': 'EU', 'continent_name': 'Europe', 'country_code': 'PL', 'country_name': 'Poland', 'region_code': … -
Building a Dashboard App with Django Rest framework
I'm trying to create a charts dashboard with Django REST framework in the backend and Reactjs in the front end. This would be my second django project. I'm connected to my Postgres database table and can produce it whole in JSON using APIview. I've explored Django-rest, but the demos and examples doesn't show how to consume postgres data and return prepared data using RESTful APIs. How do I edit my views.py file to write SQL queries within my Django project? I want to have 4 different dash app instances linking different url paths. Below is an example of how dash renders tinyurl.com/195nnyts from rest_framework.response import Response from rest_framework.views import APIView from .models import superstore from .serializers import storeSerializer class storeList(APIView): def get(self, request): item = superstore.objects.all()[:100] serializer = storeSerializer(item, many=True) return Response(serializer.data) -
How to access value from dic in django?
views.py <pre>class BoardDetailView(DetailView): model = Board def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['columns'] = Column.objects.filter(board = self.get_object()) context['labels'] = Label.objects.filter(board = self.get_object()) for column in context['columns']: context[str(column)] = Task.objects.filter(column = column) context['comments'] = Comment.objects.all() context['tasks'] = tasks print(context) return context </pre> from the 1st print stmt I got four obj [progress, bugs, finished, delayed] i.e. <QuerySet [<Column: progress>, <Column: bugs>, <Column: finished>, <Column: delayed>]> and from 2nd print stmt I got these obj which are dependent on first four. {'progress': <QuerySet [<Task: 1 - elementorTemplate>, <Task: 2 - logodesign>]>, 'bugs': <QuerySet [<Task: 6 - fix model>]>, 'finished': <QuerySet []>, 'delayed': <QuerySet [<Task: 3 - watermark>]>} I am unable to access value in template. please help me. Template.py {% for column in columns %} <div class="grid-item"> <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'board-detail' column.id %}">{{ column.title }}</a> {% for task in column.title%} <! –– ––> <div class="article-metadata"> <a class="mr-2" href="#">{{ tasks.color_category }}</a> <a class="mr-2" href="#">{{ task.title }}</a> <small class="text-muted">{{ task.description }}</small> <a class="mr-2" href="#">{{ task.priority }}</a> <a class="mr-2" href="#">{{ board.task.labels }}</a> </div> {% endfor %} {% endwith %} </div> </div> </article> </div> {% endfor %} -
Django filter: Searching in User and Profile Models with paginator
I'm trying to create an admin panel where the admin can search for a user by username, first_name, last_name, zip_code (from profile model), etc. For some reason, the paginator works, but when I try to search using django-filter, nothing happens. The results don't change and I still see the whole list of all the users. Models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthdate = models.DateField(null=True, blank=False, max_length=8) phone_number = PhoneNumberField(null=True, blank=False, unique=True) filters.py import django_filters from django_filters import CharFilter from django.contrib.auth.models import User from .models import * class AdminUserFilters(django_filters.FilterSet): first_name_bitch = CharFilter(field_name='first_name', lookup_expr='icontains') # last_name = CharFilter(field_name='last_name', lookup_expr='icontains') # zip_code = User.profile.objects.filter(author__user__profile__screenname__icontains=w) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email',) views.py User_list = User.objects.all().order_by('username') User_filter = AdminUserFilters(request.GET, queryset=User_list) paginator = Paginator(User_filter.qs, 10) page_num = request.GET.get('page', 1) try: User_list = paginator.page(page_num) except PageNotAnInteger: User_list = paginator.page(1) except EmptyPage: User_list = paginator.page(paginator.num_pages) context = {'User_list': User_list, 'User_filter':User_filter, 'paginator':paginator, 'page_num':page_num,} return render(request, "admin/listusers.html", context) listusers.html {{ User_filter.form }} <br> <button type="submit" type="button" style="height:40px; width:120px" class="btn btn-primary">Search</button> <br><br> {% for user in User_list %} <tr> <td><a href='/edit_user?edit_username={{ user.username }}'>{{ user.username }}</a></td> <td style="min-width: 110px">{{ user.date_joined}}</td> <td><a href='/add_household?username={{ user.username }}'>Edit Household</td> <td>{{ user.first_name }}</td> <td>{{ user.last_name }}</td> <td>{{ user.profile.birthdate }}</td> <td>{{ user.email … -
Auto Swagger add list quotes before dict quotes
https://drf-yasg.readthedocs.io/ - talking about this swagger In source can't find that would answer me - https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/utils.py#L33 Picture: what i want to get -
How can I process a specific query in django?
In my viewset, I have given filterset_fields to query the model through an API endpoint. I want to convert the retrieved queryset to a dataframe for processing the data in the model using pandas. For this, I used the django-pandas's to_dataframe() method. Following are the Viewset and the function used in the viewset: class StockPriceDataViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = StockPriceData.objects.all() serializer_class = StockPriceDataSerializer filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields = { 'date':['gte','lte'], 'org__symbol':['exact'], 'org__group':['exact'], } permission_classes = (AllowAny,) @action(methods=['GET'], detail=False, url_path='stock') def get_df(self, request): queryset = self.queryset result = generate_df(queryset=queryset) return Response(result, status=status.HTTP_200_OK) def generate_df(queryset): df = queryset.to_dataframe() df = df.drop(['s_n','id'], axis=1) result = df.to_json(orient='records', date_unit='ms', lines=True).splitlines() return result In an interactive shell when I filter the queryset for specific values it works fine. What am I doing wrong here? The queryset filtering doesn't work on the API endpoint for get_df() while it works normally for the queryset method. Also, the data is not being paginated for the get_df() method. What can I do here to achieve this? -
how to display the latest updated records in table -Django
I am having a table in the template file and I'm updating the data by using the .xls file. Can anyone please help me with how to display the latest added records with some hint(or by adding another column) OR how to differentiate which are updated records and which are newly added records? below is my logic code to upload data. import time import simplejson as json count = [ ] ##Global variable lap =[] from datetime import datetime def CTA_upload(request): lap.clear() i = 1 print('Counter value at starting::::::::: :', len(count)) allcta = CTA.objects.all() allcta = allcta.filter(Shift_timing__exact='Morning') allcta7 = 50 now = datetime.now() current_time = now.strftime("%H:%M:%S") # start = '06:30:00' # end = '15:30:00' print('Current Time:',current_time) try: if current_time > '06:30:00' and current_time < '23:59:59': if len(count) <= allcta7: if request.method == 'POST': movie_resource = CTaResource() print('movie_resource', movie_resource) ##we will get data in movie_resources#### dataset = Dataset() print('Dataset ka Type', dataset) new_movie = request.FILES['file'] if not new_movie.name.endswith('xls'): messages.info(request, 'Sorry Wrong File Format.Please Upload valid format') return render(request, 'app/uploadcta.html') messages.info(request, 'Starting...') imported_data = dataset.load(new_movie.read(), format='xls') print('abcdefghijk:', type(imported_data)) messages.info(request, 'Checking File content)') for data in imported_data: print('data2',data[1]) datax=data[1] if data[1] != '' : value = CTA( data[0], data[1], data[2], data[3], data[4], data[5], … -
Django ORM get related from queryset (self)
I have a table with a self many-to-many relationship like so: class User(models.Model): id = models.BigIntegerField(primary_key=True) username = models.CharField(max_length=100, blank=True) follows = models.ManyToManyField('self', blank=True, symmetrical=False) Effectively creating a follower style relationship between the Users I am trying to do a "lookalike" style query, where I take a source user, (1) find everyone who follows them, (2) then find everyone they follow. I can succesfully do step (1) as so: followed_by = User.objects.get(id=359).user_set.all() Which returns me a QuerySet. But then, to get the people that followed_by -> follows I am struggling: related = followed_by.select_related('follows__id') Returns me an error that no field is found. I have also tried: User.objects.filter(id__in=followed_by).values('follows__id') But this just gives me a list of id=359. Effectively I am just looking to carry out another join on the objects that are returned. -
How to define the foriegn key relationship?
I'm new to django and the database concepts. I'm getting the 1042 error code when I'm trying to register student via frontend and don't know where my mistake is, if anyone can help that'd be great. I tried different ways but none was beneficial. I can add the student via the admin panel of django but cannot do the same via frontend. models.py class Session(models.Model): session = models.CharField(max_length=150, default=" ") def __str__(self): return self.session def get_absolute_url(self): return reverse('datapage') class Student(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) phone_number = models.CharField(max_length=20, blank = True) semester = models.CharField(max_length=20, blank = True) session_year = models.ForeignKey(Session, on_delete = models.CASCADE) def __str__(self): return str(self.user) forms.py session_years = Session.objects.all() session_year_list = [] for session_year in session_years: single_session_year = (session_year.id, session_year.session) session_year_list.append(single_session_year) class StudentSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email = forms.EmailField(required=True) username = forms.CharField(required=True) phone_number = forms.CharField(required=True) semester = forms.CharField(required=True) def clean_email(self): email = self.cleaned_data.get('email') email = email.lower() if User.objects.filter(email__iexact=email).exists(): raise forms.ValidationError('A user has already registered using this email') return email def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(email__iexact=username).exists(): raise forms.ValidationError('A user has already registered using this username') return username class Meta(UserCreationForm.Meta): model = User fields = ['first_name', 'last_name', 'email', 'username'] @transaction.atomic def save(self): … -
django pagination not work in host with falsifying debugging
I used Django pagination, which works properly on the local server, but after placing the code on the host and falsifying the debugging, pagination does not work and all the data is displayed on one page. class ArticleList(ListView): paginate_by = 18 template_name = 'articles/articles_list.html' model = Article def get_queryset(self): articles = Article.objects.filter(active=True).order_by('created_at').reverse() grouped_articles = list(my_grouper(3, articles)) return grouped_articles def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['setting'] = SiteSetting.objects.first() context['categories'] = Category.objects.all() return context -
AWS S3 stored images link is not working in Gmail newsletter
I'm trying to send a newsletter using Django SMTP.But image links in the newsletter are dead in Gmail. I'm using a custom domain name and the images are stored in a public S3 bucket. The html code for newsletter: class Mail(generics.ListAPIView): def post(self,request,*args,**kwargs): subject = 'Newsletter' message = '' html_content = f''' <!doctype html> <html lang=en> <head> <meta charset=utf-8> <title>Test</title> </head> <body> <div style="width:100%;background-color:#F3F2EF;display:flex"> <div style="width:430px;display:block;margin:1rem auto;background-color:white;padding:1rem"> <div style="display:flex;height:60px;width:100%;align-items:center;"> <a href="https://www.example.com" style="display:flex;margin:auto"><img src="https://www.example.com/image.jpg" style="display:block" alt="logo" title="img" width="150px" height="50px" /></a> </div> </div> </div> </body> </html> ''' from_email = os.getenv('MAILADDRESS') to = 'user@gmail.com' msg = EmailMultiAlternatives(subject, message, from_email, [to]) msg.content_subtype = 'html' msg.mixed_subtype = 'related' msg.attach_alternative(html_content,"text/html") msg.send() return Response(status=status.HTTP_200_OK) -
Related Field got invalid lookup: icontains Error on Django rest framework Search filters
In the below class 'dep' is a Foreign Key field associated with Employee model class Emp(ListAPIView) queryset=Employee.Objects.all() serializer_class = EmployeeSerializer filter_backends = [SearchFilter] search_fields = ['dep'] but when I pass dep has a filter to the endpt , it throws Related Field got invalid lookup: icontains Error