Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load images using JavaScript in Django in a Jinja format?
Basically what I am doing is here there is a emotion detection model running in background which will detect the emotion and create an emoji in .svg format. This svg file keeps on changing as the emotion changes. Like if emotion="Happy" then an image with a happy face will be generated in a svg file format. Now I want this generated image to be displayed in by Django template but I am getting error. This is my view.py def epred(emotion): global ep ep = emotion def res(request): global sc_id,cc_id,hc_id,ht_id,a_id,fht_id,ct_id, ep sc_id = request.GET.get('skincolor') cc_id = request.GET.get('clothingcolor') hc_id = request.GET.get('haircolor') ht_id = request.GET.get('hairtype') a_id = request.GET.get('accessory') fht_id = request.GET.get('facialhairtype') ct_id = request.GET.get('clothingtype') update(fht_id, ct_id, cc_id, a_id, hc_id, ht_id, sc_id, ep) return render(request, 'result.html') def gen(camera): while True: frame = camera.get_frame() update(fht_id, ct_id, cc_id, a_id, hc_id, ht_id, sc_id, ep) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type ='multipart/x-mixed-replace; boundary=frame') This is my result.html file where I need the image to be displayed <body style="background-color:#9ADCFF"> <h1 id="mh1">LOOK AT THE CAMERA</h1> <div class="row"> <div class="column" id="cols"> <img src = "{% url 'video_feed' %}"> </div> <div class="column" id="cols"> <img id="resimg" src="{% static 'output/emoji1.svg' %}"> <div id="resbtn"> <a href="#"><button class="btn btn-primary" … -
How can I truncate serializer CharField value if it exceeds a certain length
I have a model field that I want to restrict to a certain length (max_length=200). I however want the serializer to truncate any value that exceeds that length (max_length=200). How can I achieve this model field description = models.CharField(max_length=2000) serializer field description = serializers.CharField( max_length=2000, required=False, allow_blank=True, default="" ) -
How to allow users to input in only 5 fields out of 10 in django model form
I have developed a django project to test 10+2 students online. I used django model forms.In the question paper, there will be 90 questions. In each subject 30 questions. Out of 30 , in each subject, first 20 are multiple choice. In that I don't have any problem. But in the remaining 10, students have to input integer values . But only 5 out of 10. How to restrict them not to input more than 5 in that 10 questions in each subject. Pls advice me. I am not rendering questions, only form to collect options and integers. Pls advice me -
How to get top n rows in django rest framework serializers using serializers relations
I have a serializer that is working fine for all of the data, which is getting from the Database. I want to get top n numbers of rows sorted by some value. Below is my code in views.py: @api_view(['GET']) def org_api(request, org_id): if request.method == 'GET': try: org = Organization.objects.prefetch_related('team').get(org_id=org_id) except Organization.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializers = OrgSerializers(org) return Response(serializers.data) And here is my serializers.py code: class OrgSerializers(serializers.ModelSerializer): team = TeamSerializer(many=True, read_only=True) class Meta: model = Organization fields = ['org_id','name', 'team'] And here is my TeamSerializers Code: class TeamSerializer(serializers.ModelSerializer): ticker = serializers.PrimaryKeyRelatedField(queryset=Team.objects.all()) class Meta: model = Team fields = ['name', 'resignation', 'org_id'] It is returning all of the team members of the same organization like below: { "org_id": "ABC", "name": "Stocks Telegraph", "team": [ { "name": "Mr. Timothy D. Cook", "title": "CEO & Director", "org_id": "ABC" }, { "name": "Mr. Luca Maestri", "title": "CFO & Sr. VP", "org_id": "ABC" }, { "name": "Mr. Jeffrey E. Williams", "title": "Chief Operating Officer", "org_id": "ABC" }, { "name": "Ms. Katherine L. Adams", "title": "Sr. VP, Gen. Counsel & Sec.", "org_id": "ABC" }, { "name": "Ms. Deirdre O'Brien", "title": "Sr. VP of People & Retail", "org_id": "ABC" }, { "name": "Mr. Chris Kondo", "title": "Sr. … -
Adding a 'show all' to django search with js/ajax if results > 5
I have a simple django search functionality using js/ajax. I want to add functionality so that when the queryset is greater than 5 a 'Show all' href will appear in the search results and it will redirect to a page with all the queryset. This is for the case when a queryset returns a large number of results, rather than have them in one big box. I thought I could just add a dictionary to my queryset, e.g. data.append({'pk': <add number to querset>, 'name': 'Show all results'}) but then I think this will mess around with the js logic with the forEach loop. I'd want each search result up to 5 to link to the detail view, but then the last one should link to a completely different view. I'm not sure what the best option is here. My search in views.py: def search_results(request): """ Handles search logic """ if request.is_ajax(): res = None quote = request.POST.get('quote') qs = Quote.objects.filter(name__icontains=quote) if len(qs) > 0 and len(quote) > 0: data = [] for pos in qs: item = { 'pk': pos.pk, 'name': pos.name, 'image': str(pos.image.url) } data.append(item) res = data else: res = 'No quotes found...' return JsonResponse({'data': res}) return JsonResponse({}) … -
How to return Google Login URL via REST api using django-allauth library?
There is a project with connected and working Google authorization using the django-allauth library. The problem is that django-allauth returns an html template with a redirect button to Google Auth by url .../account/google/login. How to return NOT a TEMPLATE, but a link to Google Auth? The provider_login_url variable is inserted only into the template and there is no access to it. -
Django import my app models AppRegistryNotReady
I will import my models in celery.py. But when I import and run the runserver command, I get the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") My import code line: from app.models import model1, model2 -
Django admin form fields are all on one line
I have an admin action which is followed by a form where users can choose several dates. class AddReportDateForm(forms.Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) date = forms.DateField(required=False, widget=forms.SelectDateWidget(years=[timezone.now().year, timezone.now().year-1, timezone.now().year-2])) date1 = forms.DateField(required=False, widget=forms.SelectDateWidget(years=[timezone.now().year, timezone.now().year-1, timezone.now().year-2])) date2 = forms.DateField(required=False, widget=forms.SelectDateWidget(years=[timezone.now().year, timezone.now().year-1, timezone.now().year-2])) But on the admin form all these datewidgets are inline. Is there an easy way to get them all on a separate line. Without creating an admin template. Thanks in advance -
Django didn't create test database
I have a postgresql database defined in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'blog', 'USER': 'blog', 'PASSWORD': 'blog', 'HOST': 'postgres', 'PORT': '5432', }} Also I have a dummy test that creates a few objects in db class LogicTestCase(TestCase): @classmethod def setUp(cls): User.objects.create(username='test_user') Tag.objects.create(name='test_tag') Post.objects.create(title='test_title', post_text='test post text', author=User.objects.get(username='test_user')) def test_home(self): self.view = Home() print(self.view.get_context_data()) But when I run the tests - Django does not create a test database, instead of it Django uses my main DB to create objects. What have I done wrong with configuring my project? Django version==3.2.9 I run tests in a docker container, here is my docker-compose version: '3' services: blog: build: . command: bash -c 'python manage.py runserver 0.0.0.0:8000' ports: - "8000:8000" container_name: blog volumes: - .:/usr/src/blog restart: always depends_on: - postgres redis: image: redis restart: always postgres: image: postgres volumes: - '/tmp/postgres:/var/lib/psql/data' environment: POSTGRES_DB: 'blog' POSTGRES_USER: 'blog' POSTGRES_PASSWORD: 'blog' PGDATA: 'var/lib/psql/data/postgres' celery: restart: always build: . container_name: 'blog_celery' command: bash -c 'celery -A justblog worker -l INFO -E -B' -
Error while trying to switch the identifier to email in Django User model
I want to change the unique identifier of Django's User model from Username to Email so I write this: models.py: from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUserManager(BaseUserManager): ''' Custom user model manager where email is the unique identifier for authentication instead of username.' ''' def create_user(self, email, password, **extra_fields): ''' Create and save a User with the given email and password. ''' if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): ''' Create and save a SuperUser with the given email and password. ''' extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField('email address', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser # Register your models here. class CustomUserAdmin(UserAdmin): model = CustomUser list_display = ('email', 'is_staff', 'is_active') list_filter = ('email', 'is_staff', 'is_active') fieldsets = … -
How to migrate specific models in another database in django?
I have two databases in my Django project settings (app1_db, app2_db) and I have a model in app1 that I want to migrate to app1_db. How can I do this? I tried to use Django routers but it didn't work for me. the router goes to sync all models in an app to a specific database but I want that just a specific model goes to that database. -
How do I get the oldest item in an SQLite3 database with django [closed]
Using Django, how would I get the oldest object in my SQLite3 database and delete it if a specific condition is true? I am hoping to do this from the views.py file in my app. -
NameError: name 'model_object' is not defined
I'm trying to get all model operations in my django app with the following code but it returns an error. I get the error NameError: name 'model_object' is not defined def admin_main(request): logs = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(model_object).pk, object_repr=unicode(obj), object_id=obj.id, message="", action_flag=ADDITION if create else DELETION) logs = logs.order_by('-action_time')[:40] return render(request,'history.html', {"logs":logs}) -
DJANGO : How to filter the last data collected for each type of object in a model?
Let's say I have this model class TreeCensus(models.Model): name = models.CharField() #Oak, elm, ... identified_at = models.DateTimeField(auto_now_add=True) I want to get a QS with the last Census of each tree. I tried naively this TreeCensus.object.order_by('name').last() But It obviously returned me the last of all the TreeCensus objects. So what is the best way (or at least a good one) to do this? For example if there are 2 Oak in the QS I want to get the first one filtered -
Terminate previous Celery task with same task id and run again if created
In my django project, I have made a view class by using TemplateView class. Again, I am using django channels and have made a consumer class too. Now, I am trying to use celery worker to pull quearyset data whenever a user reflesh the page. But the problem is, if user again reflesh the page before the task gets finished, it create another task which causes overload. Thus I have used revoke to terminate the previous running task. But I see, the revoke permanently revoked the task id. I don't know how to clear this. Because, I want to run the task again whenever user call it. views.py class Analytics(LoginRequiredMixin,TemplateView): template_name = 'app/analytics.html' login_url = '/user/login/' def get_context_data(self, **kwargs): app.control.terminate(task_id=self.request.user.username+'_analytics') print(app.control.inspect().revoked()) context = super().get_context_data(**kwargs) context['sub_title'] = 'Analytics' return context consumers.py class AppConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() analytics_queryset_for_selected_devices.apply_async( args=[self.scope['user'].username], task_id=self.scope['user'].username+'_analytics' ) -
Django ORM Query to get number of currently subbed user
I use an Event log that tracks subscriptions and unsubscriptions to given mailing lists. My objective is to hit the database one time (sqlite) to get the number of subscribed users, I don't need the objects, just a number. models.py class MailingListEvent(models.Model): """Events on mailing lists. This represents subscribes, unsubscribes, and bounces. We'd like to understand what happens and when, not just the current state of the system. """ class EventType(models.TextChoices): SUBSCRIBE = 'sub', 'inscription' UNSUBSCRIBE = 'unsub', 'désinscription' BOUNCE = 'bounce', 'bounce' user = models.ForeignKey(User, on_delete=models.CASCADE) mailing_list = models.ForeignKey(MailingList, on_delete=models.CASCADE) event_timestamp = models.DateTimeField(default=django.utils.timezone.now) event_type = models.CharField(max_length=6, choices=EventType.choices) So far I found only this solution to work with : def user_subscribe_count(mailing_list): """Return the number of users currently subscribed to the mailing list. We want to know how many users are currently subscribed. Note that individual users might subscribe and unsubscribe multiple times. Other (future) events could happen as well. """ user_list = MailingListEvent.objects.filter(mailing_list=mailing_list).values_list('user',flat=True).distinct() users_subscribed = list() for user in user_list: user_state = user_current_state(User.objects.get(pk=user),mailing_list) if user_state.event_type == MailingListEvent.EventType.SUBSCRIBE: users_subscribed.append(user_state) return len(users_subscribed) I know there is a .count() method on Django, but converting to list already hits the database anyway. Can someone suggest a query that would return the number of users … -
Django - How to return multiple querysets with get_queryset() - ListView
I have a blog with an option to view a specific user's profile showing a list of posts the user posted. The posts are being returned in a ListView. Each post also comes with comments. So currently, my get_queryset() method returns a queryset of the comments for the post ordered by total of highest likes. models.py class Post(models.Model): title = models.CharField(max_length=100, help_text="100 characters or less") content = models.TextField() category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) liked = models.ManyToManyField(Profile, blank=True, related_name='likes') views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): return ( super() .get_queryset() # Prefetch comment using a Prefetch object .prefetch_related( Prefetch( "comment_set", # Specify the queryset to annotate and order by Count("liked") queryset=Comment.objects.annotate( like_count=Count("liked") ).order_by("-like_count"), # Prefetch into post.comment_list to_attr="comment_list", ) ) ) How can I return another queryset? I read from another discussion to use chain(), but it didn't work for me. How to return multiple queryset object or add queryset result from get_queryset method in Django Right now, this returns Post.objects.all() But I want to return #second queryset user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') I could add this to a context as below … -
Django - How to query top products for each date in given interval of dates using aggregation and filter the results of TruncDay
If I have these 4 models of Order, LineItem, Payment, and Product. How can I get the most sold products at given days? class Product(models.Model): sku = models.CharField(...) ... class Order(models.Model): ... class LineItem(models.Model): order = models.ForeignKey(Order, ...) product = models.ForeignKey(Product, ...) amount = models.PositiveIntegerField(...) ... class Payment(models.Model): order = models.ForeignKey(Order, ...) paid_at = models.DateTimeField(...) .... I have tried to approach this from the LineItem model. ten_days_ago = timezone.now() - timedelta(days=10) queryset = LineItem.objects.filter( order__payment__paid_at__gte=ten_days_ago ) .annotate(date=TruncDay("order__payment__paid_at") .aggregate( max_sales=Max( "amount", filter=Q( order__payment__paid_at__gte="date", order__payment__paid_at__lte=F("date") + timedelta(days=1), ), ) ) this gives a django.core.exceptions.ValidationError: ['“date” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I doubt the query will work even with valid date format, but, assuming it will work how do I do I format the "date" and F("date") expression to valid date? And if it indeed will not work, how do I query such cases? thank you. -
how I can open page for each user in list and add more information python django
I have a list of users in the table. I want when I click on any user it open "user_information page". "user_information page" has two buttons "ADD MORE" and "SAVE". The "SAVE" button saves the information and shows them as a block, and it should save for that user. The "ADD MORE" button allows user to fill the fields with different information (user name, work address, user position) -
Django: Only the First Image getting to Database with every pickd instance even though all images are properly read from the excel sheet
Hey guys I am having trouble extracting image links from an excel sheet and saving to database in django. The problem is, even though all image links are being extracted correctly, only the first image is getting into database. For example, if Picked is a model, and PickedImage has a foreign key to Picked. then even after extracting all images, only the first image is getting stored in database. if I provide 6 different images to PickedImage for a single Picked instance. The rest of the images are in the list but not getting stored to database instead the first image will be stored 6 times. This is the code, can someone help. for pickd in data['pickd']: # loop to create pickd image model instance if pickd['title'] is None or pickd['title'] == '': continue i += 1 try: if pickd['image1'] is not None: bulk_image.append(Image(picks=instance[i], images=downloadImage(pickd['image1'], pickd['title']).open(mode='rb'), main=True)) if pickd['image2'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image2'], pickd['title']).open(mode='rb'))) if pickd['image3'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image3'], pickd['title']).open(mode='rb'))) if pickd['image4'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image4'], pickd['title']).open(mode='rb'))) if pickd['image5'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image5'], pickd['title']).open(mode='rb'))) if pickd['image6'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image6'], pickd['title']).open(mode='rb'))) except Exception as e: continue def downloadImage(url, Name): """ Method to download images from a given url """ … -
request.user always returns AnonymousUser
I have created a django model which includes a foreign key to a user as follows: from authentication.models import User from django.db import models class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) My serializers.py file is as follows: class EventSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Event fields = ['user', 'dr_notice_period', 'dr_duration', 'dr_request'] My views.py is as follows: from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from vpp_optimization.serializers import EventSerializer @api_view(['POST']) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save(commit=False) instance.user = request.user instance.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) What I need to do is to go to a URL and login as a user. Then I need to go to another URL and add with POST request some details about the event and save the details as well as the user in the database. However after login and POST request I get the following error: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f7daf1469d0>": "Event.user" must be a "User" instance. It seems that it always returns an AnonymousUser, although I have logged in. Any idea of … -
how to create a python django model for elasticsearch with base library
In my view I query elasticsearch db but it isn't good pratice. I want follow mvc pattern, so how to create a python django model for elasticsearch? I use simple base elasticsearch library. Please, guide me. controller-view view_home.py from django.shortcuts import render, redirect from django.conf import settings from pygiustizia.models.model_users import Users from pygiustizia.models.model_docfields import * import logging import json from elasticsearch import Elasticsearch from django.http import JsonResponse from django.template.loader import render_to_string def show_results(request): print('####### show_results ########') ELASTICSEARCH_URL = getattr(settings, 'ELASTICSEARCH_URL', 'localhost:9200') ELASTICSEARCH_INDEX = getattr(settings, 'ELASTICSEARCH_INDEX', 'civile') print(ELASTICSEARCH_INDEX) esSearchPageClient = Elasticsearch([ELASTICSEARCH_URL]) size = 2 fromSize = 0 bodyPageAllDoc={ "size": size, "from": fromSize, "query": { "match": { "distretto": "MI"} }, "_source": ["text"], "sort": [{"_id": "asc"}] } resPage = esSearchPageClient.search(index=ELASTICSEARCH_INDEX, body=bodyPageAllDoc) #print(resPage) html = render_to_string('pygiustizia/home/process_show_results.html') return JsonResponse({'cat':1,'html':html}) -
Streaming video using Python - two different site users
I want to make a website where users can join that can be seen through their webcams. I mean streaming video of two different users of the site through their webcams e.g. on a laptop. I will be setting up the website probably on AWS. I want to do this using Python (Flask/Django, nginx, Ubuntu etc). Can you recommend a library/some sources to make this possible? OpenCV? Or something else? -
Django Ajax POST request fail to redirect
I am trying to create a website to capture picture from client's camera and save it in the database. However after everything was saved, I cant seem to redirect the page. views.py def facial_capture(request): if request.method == 'POST': file = request.FILES['snap'] if file: student = Student.objects.get(id=request.session['id']) if student: FaceImage.objects.create(student=student, image=file) return HttpResponse("{'status': 1}", content_type='application/json') return HttpResponse("{'status': 0}", content_type='application/json') return render(request, 'id_capture/facial_capture.html') face_capture.html {% block body %} <div class="container"> <form>{% csrf_token %} <video id="video" width="640" height="480" autoplay></video> <button id="send">Submit</button> <canvas id="image_canvas" width="640" height="480"></canvas> </form> </div> {% endblock %} face_capture.js $(document).ready(function () { var video = document.getElementById('video'); var canvas = document.getElementById('image_canvas'); var context = canvas.getContext('2d'); var w = 640, h = 480; if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(stream => { video.srcObject = stream; video.play(); }); } document.getElementById("send").addEventListener("click", function() { context.translate(w, 0); context.scale(-1, 1); context.drawImage(video, 0, 0, w, h); canvas.toBlob(upload, "image/jpeg"); }); function upload(file) { var formData = new FormData(); formData.append("snap", file); const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; $.ajax({ headers: {'X-CSRFToken': csrftoken}, type: 'POST', url: '/signup/facial_capture', data: formData, cache: false, processData: false, contentType: false, enctype: 'multipart/form-data', success: function(data){ console.log('response received'); if (data.status == 1) { console.log('status ok'); window.location.href = "login"; } else { console.log('status failed'); window.location.reload(); } } }) } }); I assume … -
How to fix absolute import problem in Django?
I try to figure it out why can't I import a module but I have no success. My structure is very simple: exitinterview firm stressz -models.py performance -emails.py I want to import Projects class from stressz.models into emails.py like this: from stressz.models import Project But I always get this error: ModuleNotFoundError: No module named 'stressz' I have stressz in my settings.py in the INSTALLED_APPS