Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Getting fullcalendar javascript click data to django modelform
i want to click event on Fullcalendar, then it open another page, like this <script> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { dateClick: function(info) { window.open("{% url 'create-book' %}","_self"); }, . but how to get data from fullcalendar ? there are function dateStr for show date, and resource.id, to show resource in timeline view(fullcalendar) alert('clicked ' + info.dateStr + ' on resource ' + info.resource.id); . what i want is bring dateStr and resource.id clicked data to django modelform, here views.py @login_required(login_url='login') def create_book(request): booking_forms = BookingForm(initial={ 'resourceId':'xxxx', 'startdate':'xxxx' }) im not sure what should i put on xxxx to get this through url on other page.. Thanks.. -
How to sort the fields in CreateView of Django?
I just learned django last January and I'm currently working on website to store and show lyrics. My problem is that in createview the fields are not sorted. Here is my models.py: class Lyrics(models.Model): title = models.CharField(max_length=50) singer = models.ForeignKey(Singer, on_delete=models.RESTRICT) type = models.ForeignKey(Type, on_delete=models.RESTRICT) lyrics = models.TextField() Views.py: class AddSongView(LoginRequiredMixin, CreateView): model = Lyrics fields = ['title', 'singer', 'type', 'lyrics'] Screenshot in the browser As you can see in the attached screenshot, the choices from singer field is not sorted. How to sort those choices? Thank you! -
A guidance for a mechanical bachelor student for getting start
I'm a undergraduate mech student and my first coding experience is learning python(in my 20th) that made me get over mech. Now I am looking for best process I can go through to become a django coder, front_end , back_end developer and things related on. What should I start to learn now?(your suggestion depend on what skill is suitable for a beginner to find a average job) -
Misaka Installation Error in a Django Project
I am using python 3.8. Whenever I try to install misaka in my Django project, it shows this error message: fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directory I tried to clone the misaka repository from github but still this error persists. What should I do? -
Problem with connecting to localhost on Ubuntu WSL3
I set up locally Apache2 server for django project, and it worked perfectly well. The problem is that after one day off i got back to it and tried getting on server, and somehow i couldn't connect to it, even after checking if apache service is running, and reloading configuration just to be sure. I couldn't access it from localhost, and any other local tag. So after that i tried with django runserver command. Server was running, but i couldn't get on it as well. 2 days before, it worked without any issues. I'm using Ubuntu on WSL 3, and on windows i can run server without any problems. Tried pinging localhost and got 100% package loss. What i did then was restarting whole Ubuntu service with wiping all data. After setting up system everything worked again. The thing is that this is second time that this problem is occuring, and last time i get rid of it the same way, just restarting whole Ubuntu with removing all data. Second time after setting everything up and running server i tried restarting my computer to check if this problemm occurs, after windows restart, but it worked. -
Django-Snowflake external Browser connection issue when hosting in IIS Server
I have connected Snowflake from Django using authenticator as external browser.But when I hosted the application in IIS Server am not able to connect snowflake, Its not going for external browser and showing error like this HTTP Error 500.0 - Internal Server Error C:\TESTCASE_AUTOMATION-PYTHON-featue_UI\venv\Scripts\python.exe - The FastCGI process exceeded configured request timeout -
how i can assign a specific link to every user by which i can visit his profile
i want to assign a link for every user by which anyone can visit his profile i did this to achieve that hting but it doesn't work how i can do that my urls.py from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from . import views from .views import SearchResultsView # Template Urls! app_name = 'accounts' urlpatterns = [ path('Skolar/',views.base, name= 'base'), path('Register/',views.register,name='register'), path('login/', views.my_login_view, name='login'), path('logout/',views.user_logout,name='logout'), path('<slug:username>/',views.profile, name='profile'), path('EditProfile/',views.update_profile,name='editprofile'), path('search/', SearchResultsView.as_view(), name='search'), ] my models.py for every user it created automatically with the help of signal from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User ,on_delete=models.CASCADE,) profile_pic = models.ImageField(upload_to='profile_pics',default='default.png',) twitter = models.URLField(max_length=80, blank=True,) facebook = models.URLField(max_length=80, blank=True,) about = models.CharField(max_length=1500, blank=True,) joined_date = models.DateTimeField(default=timezone.now,editable=False) dob = models.DateField(blank=True,null=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, *args, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() how i can assign that by which that link ony open that user profile which is assigned to it please help if you know how to do it -
Why can't I put values from database into "time" with python
I can't put values from database into type="time" please help me. {% for round in room_round %} <tr> <td> <div class="col-sm-6"> <input type="time" class="form-control" id="room_start" name="room_start[]" value={{round.room_start}} required>{{round.room_start}} </div> </td> <td> <div class="col-sm-6"> <input type="time" class="form-control" id="room_stop" name="room_stop[]" value={{round.room_stop}} required>{{round.room_stop}} </div> </td> <td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove">Delete</i></button></td> </tr> {% endfor %} -
How to serialize a dataframe in django? Is there a way to return dataframe along with queyset in django?
What I'm trying to do here is get a query based on users' choices like date, group, and symbol. I would like to convert this queryset to a data frame using django_pandas. I tried to convert the data frame generated to JSON object but it gives some errors like: TypeError: Object of type 'DataFrame' is not JSON serializable. My viewset looks like this: 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,) def get_queryset(self): queryset = super(StockPriceDataViewSet, self).get_queryset() result = generate_df(queryset=queryset) return queryset, result def generate_df(queryset): df = queryset.to_dataframe() df = df.drop(['s_n'], axis=1) df = df.set_index(['org','id'],inplace=True) result = df.to_json() return result When I run the above code in an interactive shell it runs smoothly without any errors but when Django handles the request an error pops up: 'NoneType' object has no attribute 'to_json' Also, the format of JSON is not standard as I was expecting. What am I doing wrong here? Can anyone explain. Any help will be appriciated. -
Session is not working in django restviews
Hi i am trying to set a value in session but not getting the value, I don't know what I am doing wrong. Setting Value class ClView(GenericAPIView): def get(self, request, *args, **kwargs): # Get Method Code def post(self, request, *args, **kwargs): cid = request.data['id'] request.session['myid'] = cid request.session.modified = True return Response(status=status.HTTP_202_ACCEPTED) Getting Value class MainView(APIView): def get(self, request, *args, **kwargs): cid = self.request.session.get('myid') return Response({"id":cid}) 'django.contrib.sessions.middleware.SessionMiddleware', in the middlewares -
Django Nested Annotate
I have 3 models class QuestionsModel(models.Model): created = models.DateTimeField(auto_now_add=True) Question = models.CharField(max_length=200) class AnswersModel(models.Model): Question = models.ForeignKey(QuestionsModel, related_name='QuestionAnswer') Answer = models.CharField(max_length=200) class UsersAnswerModel(models.Model): Answer = models.ForeignKey(AnswersModel, related_name='UsersAnswer') RegistrationID = models.CharField(max_length=200) I am trying to Count How many UsersAnswer the Question what I tried : class DashboardAdmin(admin.ModelAdmin): class Meta: model = QuestionsModel change_list_template = 'admin/Dashboard_change_list.html' date_hierarchy = 'created' def has_add_permission(self, request): return False def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'totalAnswers' : models.Count('QuestionAnswer'), 'totalUsersAnswer' : models.Count(UsersAnswer=OuterRef('QuestionAnswer')) } response.context_data['summary'] = list( qs .values('Question') .annotate(**metrics) .order_by('-totalUsersAnswer') ) return response admin.site.register(DashboardModel, DashboardAdmin) I could not solve 'totalUsersAnswer' : models.Count(UsersAnswer=OuterRef('QuestionAnswer')) how to count nested foreign key any help please -
Django Rest Framework serializer is printing tuples instead of json
I've got the following serializer: from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): """ Serializer for Product object """ class Meta: model = Product fields = ['name', 'slug', 'description', 'image', 'price', 'active',] and the following test: from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status from .factories import ProductFactory from .models import Product from .serializer import ProductSerializer PRODUCTS_URL = reverse('product-list') def create_product(**params): """ Helper function to create a new product """ return Product.objects.create(**params) class PublicProductApiTests(TestCase): """ Test the public products' API """ def setUp(self): self.client = APIClient() def test_only_active_products_are_returned(self): ProductFactory.create_batch(2) products = Product.objects.all() serializer = ProductSerializer(products, many=True) print(serializer.data) When I print serializer.data on the screen, I'm getting: [OrderedDict([('name', 'Shane Fields'), ('slug', 'shane-fields'), ('description', 'Chance yourself conference.'), ('image', '/media/position/school.tiff'), ('price', '2.66'), ('active', False)]), OrderedDict([('name', 'Michael Hall'), ('slug', 'michael-hall'), ('description', 'Office city material room character number cause way.'), ('image', '/media/American/know.txt'), ('price', '-90244357.41'), ('active', True)])] after passing the queryset to the serializer and printing its data, isn't supposed to print in JSON format? what am I missing? -
Django: User not authenticating correctly
When logging into my app, the user is not authenticating correctly. Views.py ''' from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import authenticate, login from django.urls import reverse from users.forms import CustomUserCreationForm from django.http import HttpResponse from users.models import Blog from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.decorators import login_required # Create your views here. def intro(request): return render(request, "intro.html") def logmein(request): return render(request, "logmein.html") def login(request): username1 = request.POST.get('username') password1 = request.POST.get('password') user = authenticate(request, username=username, password=password) login(user, request) if user.is_authenticated: return render(request, "users/mainmenu.html") else: return render(request, "intro.html") def mainmenu(request): return render(request, "users/mainmenu.html") ''' Mainmenu.html ''' {% extends 'base.html' %} {% block content %} <h2>MainMenu</h2> Hello, {{ user.username }} {% endblock %} ''' When mainmenu.html is displayed following login, the user.username is showing as the SuperUser, regardless of what username and password is used to login. -
Access Django server running on local host from a computer with a certain IP address . Computers not on same network
I am a full stack engineer but know very little about networking. I have a django application running on my local host. I am interested in allowing only a specific IP address to be allowed access to my django server running on my computer. This computer is not on the same network as mine, so it would be a connection across the internet. Is such a thing possible? how is it done? my research so far shows me ways to do what I am trying to do, but to access my django server from a computer on the same network, and also does not restrict access to a certain IP address -
Django Application on Kubernetes is unable to send e-mails
I have a problem! I created an application (Python / Django) that is running on Linode with Kubernetes. Everything there is working perfectly, however, I can't send emails. I did tests using TLS (587) / SSL (465) and in the Dev environment (which I don't use Kubernetes) everything works with excellence, but, in Production my application doesn't send the e-mail and keeps processing without stopping until then showing error 502 (Bad Gateway | nginx / 1.19.2). What should I do? Thanks! -
Django object into JSON array into coordinates on a map
I'm just confused about one part here for JSON keys and values. So I have calculated a list of stores that is closest to my user's location shown below storages = Storage.objects.annotate(distance=Distance("location", user_location)).order_by("distance")[0:6] print(storages) data = serializers.serialize('json', storages) return JsonResponse(data, safe=False) next step I did is to convert it back into key value pairs. }).then(response => response.json()) .then(response => JSON.parse(response)) This way I can access the variables that I want through a code like so console.log(response[0].fields.location) however, my location data is stored as location: "SRID=4326;POINT (-122.9498219318841 49.21875514983133)" I want to loop through the array through first the response,fields, and then into locations, but the value has both long and lat. My initial thought is to perhaps created another nested element within location with long and latitude, not sure what is the correct way to do this. I followed a tutorial that was able to convert the django object into the template, but since this is an xmlhttprequest and also more dynamic, I cannot do that. Thank you!