Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SQL query in django
I need to do the following sql query in django specifically in the views window, I need to filter the "Nota" according to which "Profesor" it belongs to SQL QUERY select * from nota n join profesor on (profesor.id_asignatura = n.id_asignatura) models.py class Nota(models.Model): id_nota = models.IntegerField(primary_key=True) nota = models.IntegerField() tipo_evaluacion = models.CharField(max_length=15) fecha_evaluacion = models.DateField() id_libro = models.ForeignKey(LibroClases, models.DO_NOTHING, db_column='id_libro') id_asignatura = models.ForeignKey(Asignatura, models.DO_NOTHING, db_column='id_asignatura') rut_alumno = models.ForeignKey(Alumno, models.DO_NOTHING, db_column='rut_alumno') class Meta: managed = True db_table = 'nota' class Profesor(models.Model): rut_profesor = models.IntegerField(primary_key=True) dv_profesor = models.CharField(max_length=1) p_nombre = models.CharField(max_length=15) s_nombre = models.CharField(max_length=15, blank=True, null=True) ap_paterno = models.CharField(max_length=15) ap_materno = models.CharField(max_length=15, blank=True, null=True) especialidad = models.CharField(max_length=35) fecha_contrato = models.DateField() direccion = models.CharField(max_length=25) id_colegio = models.ForeignKey(Colegio, models.DO_NOTHING, db_column='id_colegio', blank=True, null=True) id_asignatura = models.ForeignKey(Asignatura, models.DO_NOTHING, db_column='id_asignatura') id_comuna = models.ForeignKey(Comuna, models.DO_NOTHING, db_column='id_comuna') class Meta: managed = True db_table = 'profesor' Views.py def vistaProfesor(request): rut= request.user.rut_user notas = Nota.objects.select_related?????????? -
Input data django to microsoft sql
I not migrate Django to DB. But, I already connect to microsoft sql server. I have create my table. How to make crud app? -
How to paginate two models after being combined
class Book(models.Model): title = models.CharField(max_length=32, blank=True) class Read(models.Model): user = models.ManyToManyField(UserModel) book = models.ManyToManyField(Book) I want to paginate it the way first list the books user has read and then show other books without duplicates my solution is to first fetch Read based on user__id and then exclude Book where title is in Read but i have problem with pagination. -
How to get the selected text by dragging my mouse in Python?
I am trying to build a web service that enables users to copy text easily. I want to copy a selected text automatically to the clipboard when I drag the mouse. I thought I can make it easily at first with pyautogui. So I make the script in Python3 below, but it doesn't work. import pyautogui as pya import pyperclip def copy_text(): if pya.drag(): pya.hotkey('ctrl', 'c') time.sleep(.01) sentence= pyperclip.paste() return sentence var = copy_text print (var) Please help me to make it work. I know that pyautogui has mouse functions, however, it is to move the mouse automatically. I want to automate copying by dragging the mouse manually. Thank you for your help. -
Django: Adding user to a permission group more than once
I have an application containing users who can belong to multiple organizations and via a job with a certain role for each. Each role has specific permissions to control what the job can do. I plan on using Django's built-in permissions to create a permission group for each role and assign them to a user. However, it does not feel correct from a design perspective to assign a permission group to a user because the permission belongs to the job specific role which can be held across multiple organizations. This creates messy logic when a job is removed since I must also check if the user also has another job with the same role before adding or removing permissions for the user. Is there a way to add a user to a permission group multiple times. E.g once for each role they hold across different jobs to simplify this logic? The Django documentation is unclear on how to do this. e.g of what I want to do from django.contrib.auth.models import Group sales_group = Group.objects.get_or_create(name='sales') sales_job = request.user.job.filter(role='sales', organization__name="Google") sales_job_two = request.user.job.filter(role='sales', organization__name='Microsoft') #is it possible to do this ??? sales_group.add(user, job=sales_job_one) sales_group.add(user, job=sales_job_two) models.py class Users: first_name = models.CharField(max_length=255) last_name … -
Django order_by is not ordering results of query
Django not ordering results by date. Am using Django-Rest-Framework to create API for app initially had a filter by on the query and after reading similar issues where people faced same problem when combining order_by and filter I removed the filter and manually filtered using a for loop but still keep getting the same results. Initially query was: progresslogs = ProgressLog.objects.filter(user__userprofile__coach=request.user).order_by('-date') But reading similar issues I changed the query and filtered manually think there is an issue with using filter and order by together but am still getting the results out of order: class ProgressLogAPI(APIView): def get(self, request: Request, format=None): if request.user.is_authenticated: if request.user.is_staff: logger.info('API: Staff {} fetched progress logs'.format(request.user.id)) progresslogs = ProgressLog.objects.order_by('-date') # Below loop added to manually filter results filteredlogs = [] for progress in progresslogs: if progress.user.userprofile.coach == request.user: filteredlogs.append(progress) serializer = ProgressLogSerializer(filteredlogs, many=True) return Response(data=serializer.data) But in each case the results are coming out of order, wondering is this some bug in Django, I suppose could probably sort the results manually but am thinking this would drastically increase the time for the API call to get the results so don't really want to do this. For reference the first 3 result from the API call are … -
SyntaxError: positional argument follows keyword argument in Django Serializer
yeah honestly I can't figure out the issue with this code, I'm sorry I'm new to Django but I need your help to solve this issue. I keep getting this "SyntaxError: positional argument follows keyword argument". Here's the file/code my terminal is pointing the error to. from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from rest_framework.authtoken.models import Token from userauth.models import Employee, Client class EmployeeRegistrationSerializer(RegisterSerializer): employee = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False home_address = serializers.CharField(required=True) phone_number = serializers.CharField(required=True) def get_cleaned_data(self): data = super(EmployeeRegistrationSerializer, self).get_cleaned_data() extra_data = { 'home_address' : self.validated_data.get('home_address', ''), 'phone_number': self.validated_data.get('phone_number', ''), } data.update(extra_data) return data def save(self, request): user = super(EmployeeRegistrationSerializer, self).save(request) user.is_employee = True user.save() employee = Employee(employee=user, area=self.cleaned_data.get('phone_number'), home_address=self.cleaned_data.get('home_address'), employee.save() return user class ClientRegistrationSerializer(RegisterSerializer): client = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False order_address = serializers.CharField(required=True) def get_cleaned_data(self): data = super(ClientRegistrationSerializer, self).get_cleaned_data() extra_data = { 'order_address' : self.validated_data.get('order_address', ''), } data.update(extra_data) return data def save(self, request): user = super(ClientRegistrationSerializer, self).save(request) user.is_client = True user.save() Client = Client(client=user,order_address=self.cleaned_data.get('order_address')) client.save() return user -
I want to use Ajax to send message in Django
I want to post comment using ajax in Django. I have Message Class related to Post class, and I using PostDetailView to show content of the post and coments. I'm getting error Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user\\/(?P<username>[^/]+)\\Z'] Also I have highlighted at link for bootstrap. I tried to delete these two corresponding parts, but I still getting the same error. this is my code urls.py urlpatterns = [ path('',PostListView.as_view(),name='blog-home'), path('user/<str:username>',UserPostListView.as_view(),name='user-posts'), path('post/<int:pk>',PostDetailView.as_view(),name='post-detail'), ] views.py class PostDetailView(DetailView): model = Post def get(self, *args, **kwargs): form = CommentForm() comments = Message.objects.all() return render(self.request, 'blog/post_detail.html', {"form": form, "comments": comments}) def post(self, *args, **kwargs): if self.request.is_ajax and self.request.method == "POST": form = CommentForm(self.request.POST) if form.is_valid(): instance = form.save() ser_instance = serializers.serialize('json', [ instance, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error": ""}, status=400) html(where is link to 'user-posts') <div class="post-header"> <h2 class="post-title">{{object.title}}</h2> </div> <div class="author-detail"> <a href="{% url 'user-posts' object.author.username %}" class="roomListRoom__author" > <div class="avatar avatar--small"> <img src="{{object.author.profile.image.url}}" /> </div> <span>@{{object.author.username}}</span> </a> <img class="rounded-circle account-img" src="{{object.author.profile.image.url}}" /> <div class="author-info"> <p> @<a href="{% url 'user-posts' object.author.username %}"> {{object.author}} </a> </p> <p>{{object.date_posted|timesince|split_timesince:"," }}前</p> </div> </div> script.js $(document).ready(function () { $("#comment-form").submit(function (e) { e.preventDefault(); var serializedData = … -
Trouble paginating results from a 3rd party API in Django
I'm making a portfolio project where I'm using the Google Books API to do a books search, and the Django Paginator class to paginate the results. I've been able to get search results using a CBV FormView and a GET request, but I can't seem to figure out how to get pagination working for the API response. The solution I can think of is to append &page=1 to the url of the first search, then pull that param on every GET request and use that to paginate. The problem is, I can't figure out how to append that param on the first search, and I don't know how I'd increment that param value when clicking the pagination buttons. Here's what I've got now: Form: class SearchForm(forms.Form): search = forms.CharField(label='Search:', max_length=150) View: class HomeView(FormView): template_name = "home.html" form_class = SearchForm pageIndex = 0 def get(self, request, *args, **kwargs): # get submitted results in view and display them on results page. This will be swapped out for an AJAX call eventually if "search" in request.GET: # getting search from URL params search = request.GET["search"] kwargs["search"] = search context = super().get_context_data(**kwargs) # Rest API request response = requests.get( f'https://www.googleapis.com/books/v1/volumes?q={search}&startIndex={self.pageIndex}&key={env("BOOKS_API_KEY")}' ) response = response.json() … -
login required don't take effect - django
when i try to make this page view as required login it don't do that , it's open the page without ask for login this is my code views.py @method_decorator(login_required, name='dispatch') @register.inclusion_tag('survey/surveys.html', takes_context=True) def all_surveys(context): surveys = Survey.objects.all() return {'surveys': surveys} so what is the problem here any idea guys ? also anyone can explain why that happened thanks . -
Django ORM: SUM of grouped MAX
I am trying to translate this SQL query: SELECT user_id, SUM(max_score) FROM (SELECT user_id, MAX(score) AS max_score FROM submissions GROUP BY exercise_id, user_id) AS subquery GROUP BY user_id; where the table submissions has the columns user_id, exercise_id and score. Translating the inner subquery results in: subquery = ( Submission.objects .values("exercise", "user") .annotate(max_score=Max("score")) .values("user", "max_score") ) with a queryset like this: <QuerySet [{'user': 1, 'max_score': 27}, {'user': 2, 'max_score': 50}, {'user': 1, 'max_score': 16}, {'user': 3, 'max_score': 14}, {'user': 1, 'max_score': 14}, ...]> However, when I try to sum it up by user using subquery.annotate(total_score=Sum("max_score")) I get: FieldError: Cannot compute Sum('max_score'): 'max_score' is an aggregate How could I implement this in Django ORM instead of an inefficient solution like this: scores = defaultdict(int) for row in subquery: scores[row['user']] += row['max_score'] -
How to check if a booleanfield ina django modelform is true and add whatever it is true under to a list?
I am trying to create an e-commerce site (CS50 Project 2) that allows the user to add a listing item to their watchlist. I have decided to use a django modelformw ith a booleanfield that corresponds with the WatchList model to do this. I have created the form but am not sure how to check if it is true and save the listing to the WatchList model. views.py def listing(request, id): listing = Listings.objects.get(id=id) listing_price = listing.bid sellar = listing.user watchlist_form = WatchListForm() watchlist_form = WatchListForm(request.POST) if watchlist_form == True: listing.add() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "watchlistForm": watchlist_form }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "watchlistForm": watchlist_form }) models.py class WatchList(models.Model): listing = models.ManyToManyField(Listings) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") add_to_watchlist = models.BooleanField(default=False) Thank you so much for all the help! Please let me know if you need any more code. -
aws lambda zappa deployment with django : ModuleNotFoundError
I ve created the most basic django website. Nothing except django-admin startproject hello cd hello python manage.py makemigrations python manage.py migrate The command python manage.py runserver gives me the default website with access to admin with /admin url. But when I deploy it with zappa deploy, i get a "Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 500 response code." And when I try to go the the url provided by zappa, i get No module named 'hello.urls'. I also have the same error when i try to go to the zappa_url/admin page. The urls.py file only contains : from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] How can i solve this so my website is up and running? -
Why am I automatically logged out of django admin
I deployed a Django website with Nginx on DigitalOcean and now I'm having the problem that I can login to admin but if I'm logged in for a short time I get logged out automatically -
Django ORM multiple tables query
I trying to make some queries in Django ORM (migration from SQL). My models looks like this class Iv2(models.Model): s_id = models.AutoField(primary_key=True) l_eid = models.CharField(max_length=265) t_id = models.CharField(max_length=265) class Sv2(models.Model): id = models.AutoField(primary_key=True) s_id = models.OneToOneField(Iv2, on_delete=models.PROTECT) gdd = models.DateTimeField(default=datetime.now) class Ev2(models.Model): id = models.OneToOneField(Iv2, to_field='l_eid', on_delete=models.PROTECT) s_id = models.ForeignKey(Iv2, on_delete=models.PROTECT) car = models.CharField(max_length=265) I want to write a query, given t_id. I want get corresponding Sv2.gdd and Ev2.car I'm thinking to get s_id and l_eid with the t_id. And when I get s_id. I can query Sv2 and with l_eid I can query Ev2. Is it possible to achieve everything with one ORM query ? can prefetch/select_related work here? -
Remove django inline Admin label row labels
I have the following TabularInline: class ProcessVariableInlineAdmin(TabularInline): model = ProcessVariable fields = ( 'variable', 'station_rank',) readonly_fields = ( 'variable', 'station_rank', ) ... and would like to remove the small line variables on each row: I tried poking around on the django docs for TabularInline but came up short. Is there a way to do this that I'm overlooking? Thank you in advance! -
How to create dynamic reports for Django
I have looked around a lot and have seen many tools like jasper reports, Birt, pentaho, kool report etc etc but all are in java or php, none in python. That is not the problem either because as I have seen and tested with Jasper and Birt you can connect to them with their API but there are no good resources as to how do I integrate those with Django backend using Django Rest Framework or with my frontend. Jasper has Visualize Js but is paid only, BIRT has from my experience terrible report design tool, you can't even resize or move a simple text field, there seems to be a way to do that with css, I think but why? Jasper's report designer is pretty good but again no good resource as to how to use it. I want to use it in my student management sysrem where I can print fee vouchers report cards admission slips, general reports, detail reports etc but how do I tell jasper which student or which data to use, it just uses whatever is specified in the designer. Any guidance on this matter would be immensely helpful as I am learning all this … -
Can't change value in model object with button
I need to change the quantity value of item then user pressed button on page. My code works, but only one time: if I press button at the first time, value is changing, but at second or third time nothing happens views.py def item(request, item_id): item = Item.objects.get(id=item_id) context = {'item': item} return render(request, 'main/item.html', context) def change_quantity(request, item_id): item = Item.objects.get(id=item_id) context = {'item': item} if request.method == 'GET': item.quantity +=1 return render(request, 'main/item.html', context) urls.py urlpatterns = [ path('', views.index, name='index'), path('categories/', views.categories, name='categories'), path('categories/<category_id>/', views.category, name='category'), path('topics/', views.topics, name='topics'), path('categories/category/<item_id>/', views.item, name="item"), path('categories/category/item/change_quan/<item_id>/', views.change_quantity, name='change_quan') models.py class Item(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) title = models.CharField(max_length = 150) description = models.CharField(max_length = 250) text = models.TextField() photo1 = models.ImageField(upload_to = 'static/') photo2 = models.ImageField(upload_to = 'static/') small = False quantity = 1 def __str__(self): return self.title item.html {% extends "main/base.html" %} {% load static %} <body> {% block content %} <li> <img src="{{item.photo1.url}}"> <img src="{{item.photo2.url}}"> <p> Название {{ item.title}} </p> <p> Краткое описание {{ item.description | linebreaks }} </p> <p> Большое описание {{ item.text | linebreaks }}</p> <p> Количество {{ item.quantity }} </p> <form action="{% url 'main:change_quan' item.id %}" method="get" > {% csrf_token %} <button type="submit" … -
Python deploying django with django channels on heroku
I have been trying to deploy my application on heroku with django channels and I always get the following error 2022-05-26T20:09:58.137436+00:00 app[web.1]: ModuleNotFoundError: No module named 'core' I have seen previous questions such as Deploying asgi and wsgi on Heroku but even when following these steps I can't get the deployment to work. My channel layers in settings.py: ASGI_APPLICATION = "server.asgi.application" CHANNEL_LAYERS = { 'default': { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')] }, 'ROUTING': 'server.routing.channel_routing', } } My asgi.py: import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = get_asgi_application() My wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') application = get_wsgi_application() My Procfile web: daphne server.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 chatworker: python manage.py runworker --settings=server.settings -v2 My file structure server | |_ _ chat | | | |_ __init__.py | | | |_ admin.py | | | |_ consumers.py | | | |_ models.py | | | |_ routing.py | | | |_ urls.py | | | |_ views.py |_ _ server | | | |_ __init__.py | | | |_ asgi.py.py | | | |_ routing.py | | | |_ settings.py | | | |_ urls.py | | | |_ wsgi.py | |_ _ … -
Localize dependency model name
I want to localize the DJANGO OAUTH TOOLKIT app and models names. But as it's a dependency, it's not included in my project as a custom app and I cannot change the verbose name from verbose_name = "Django OAuth Toolkit" to verbose_name = _("Django OAuth Toolkit") I could just include oauth2_provider as a entire app inside my project, but in case we need to update that dependency with a new version published in github, we should replace the entire folder. Can I just override the oauth2_provider models verbose names without creating a new Class that inherits from the original oauth2_provider class that exists as a project dependency? -
HighlightJS not highlighting certain code fragments
I'm using HighlightJS to format code that's being stored in a model's TextField of my Django application. Here is the template HTML: <pre> <code class="{{ compiler.highlight_js_alias }}">{{ compiler.unit_test_boilerplate_code }}</code> </pre> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/default.min.css" <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script> <script>hljs.highlightAll();</script> Example output: <pre> <code class="ruby hljs language-ruby"> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Person</span> : <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span> ( <span class="hljs-params"> <span class="hljs-variable language_">self</span>, name, age</span> ): <span class="hljs-variable language_">self</span> .name = name <span class="hljs-variable language_">self</span> .age = age me = Person( <span class="hljs-string">"Nathan"</span> <span class="hljs-number">32</span> ) print(me.name) </code> </pre> Why are certain fragments not highlighted? Thank you for any advice. -
Do I need to have AWS CLI to use Boto3?
I have a Django application that needs to use Boto3 to create and manage EC2 instances. When I host the Django application, do I need to install AWS CLI in the server to use Boto3 in the Django application? -
Django Rest Framework Nested Serializers with multiple types of Query Filters
Sorry for the not so descriptive title, hard to put into words what I am trying to do. My Models have various Many to Many relationships. I am trying to make my Serializers act in a very similar way to the queries I listed out below. Essentially, I am looking to get my TeamStats Model Serialized in various ways. If I need the whole leagues stats, I filter by season, if just a single team, I filter by team etc. These queries will also be read only, they won't be written to, they are just for viewing purposes on the front end. In addition, I need the serializer to be nested in such a way that whatever is filtering the query, is top data in JSON. For example, if I was doing TeamStats by Season, I would have Division Nested inside of Season, Team nested inside of Division. If I was just calling TeamStats by Division, I would have just Team nested inside of Division. Models class BaseModel(LifecycleModelMixin, models.Model): date_modified = models.DateTimeField(auto_now=True) date_created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: abstract = True class SeasonTest(BaseModel): name = models.CharField(max_length=50) class DivisionTest(BaseModel): name = models.CharField(max_length=50) seasons = models.ManyToManyField(SeasonTest, through='SeasonDivision') … -
Change webpage logo for every user in django
How can I change website logo for every other user login into django platform? For example: User-A when login, will see different logo on website, while User-B will see different and so on. -
Django exclude only works with get_context_data
Can I use exclude() without having to use get_context_data with generic class based views? I want to exclude the is_removed for the soft delete. I have seen examples where it's not used. It only works with a form variable school_district_model_form with an SchoolApplicationModelForm in get_context_data and using it in the template. Below works. I was expecting the default form variable in the template to exclude the fields and it still includes all fields. models.py class SchoolDistrictModelForm(forms.ModelForm): class Meta: model = SchoolDistrict exclude = ("is_removed",) view.py class SchoolDistrictCreateView(SchoolDistrictBaseView, CreateView): """View to create a new school district""" def get_context_data(self, **kwargs): context = { "school_application_model_form": SchoolApplicationModelForm(), } return context schooldistrict_form.html <div class="container d-flex justify-content-center mt-5" style="width: 25%;"> <div class="col mt-5"> <form action="" method="post"> {% csrf_token %} <table class="table"> {{school_district_model_form.as_table}} </table> </form </div> </div>