Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import by filename is not supported
when i used include in django url but it raise the exception like this "Import by filename is not supported" -
Django Upon click, URL changes, but page is not loaded
I'm new to Django and Python. In my current project, a new home page was created. I was assigned to work on login & signup page that are part of the home page links. My login and signup pages are ready working fine when typing their respective URLs directly in the address bar; but when login/signup is connected to an anchor tag, only the URL in the address bar changes and the control remains in home page itself. I had to press enter on address bar to load the login/signup pages. Login/Signup are the first two links tried in this home page, there is no other working link in this page that I could refer for this issue's solution. This is the case for any links introduced in the home page. When trying debug option in VS, with breakpoint in urls.py file, one breakpoint in the home page class, it was identified that upon click, those breakpoints did not hit (ie) there was no function call upon those clicks. I tried the following as suggested in few related SO questions. Confirmed that there is no duplicate function names in the views.py file Checked the pattern of URL.py file values myproject/myproject/urls.py … -
Create models in Django using AWS S3 data
I would like to create models in Django using existing data in AWS S3 my models.py file class Video(models.Model): video_name = models.CharField(max_length=2000) video_url = models.CharField(max_length=2000, unique=True) my object creater function def create_model(**kwargs): return Video.objects.create(**kwargs) I can access my bucket using for s3_object_mp4 in my_bucket.objects.all(): path_mp4, key_mp4 = os.path.split(s3_object_mp4.key) create_model(video_name=str('key_mp4'), video_url='??') How can I pass the url of the video stored in aws s3 in the to be created model so I can access the video from my html using the following ? <video controls> <source src="{{ detailedview.video_url }}"> </video> What I have Tried: url = client.generate_presigned_url('get_object',Params={'Bucket': bucket_name, 'Key': key_mp4}, ExpiresIn=3600) Two things here: 1) I get <Error><Code>NoSuchKey</Code><Message>The specified key does not exist. 2) If this link will expire in 3600seconds, does that mean I have delete, and re-populate my models everyday ? -
can i run migrate after all content types are inserted?
i write some migrate file for my service. that code use contenttype data to create custom permission. when i run migrate below error occured "ContentType matching query does not exist." so, i want my migration code to run after all contenttypes are inserted. it is avaliable?? -
Trying to use the SUM of a related field in a Django ORM query
Suppose I have two models: class Task(Model): duration = models.IntegerField(default=100) class Record: minutes_planned = models.IntegerField(default=0) task = models.ForeignKey(Record, related_name=records) I would like to get ahold of all the objects whose total minutes planned across all related Records is lower than the object's duration. I've been having trouble finding a solution in the docs. Could someone point me to it? Task.objects.filter(duration__gt=F('records__minutes_planned'))) Task.objects.filter(duration__gt=Sum('records__minutes_planned')) Task.objects.filter(duration__gt=Sum(F('records__minutes_planned'))) but so far nothing has worked. The first one ran successfully, but from what I can tell, it compared them one-by-one instead of to a total of all records. -
Django split urls.py into submodule
let's say i have long urls.py and would love to split into urls/ a_urls.py b_urls.py c_urls.py is this possible? Note: there is app_name in urls.py. -
Why is Celery Async Task working slower than Synchronous task?
I'm working on a Django application that uses Celery to run some tasks Asynchronously. I tried to perform load testing and check response time using Apache Bench. From what I could figure out from the results is that response time is faster without celery async tasks. I'm using: Django: 2.1.0celery: 4.2.1Redis (Broker): 2.10.5django-redis: 4.9.0 Celery configuration in Django settings.py: BROKER_URL = 'redis://127.0.0.1:6379/1' CELERY_RESULT_BACKEND = 'django-db' # Using django_celery_results CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' Following is my code (API exposed by my system): class CustomerSerchFino(APIView): def post(self, request): request_dict = {# Request parameters} response = celery_search_customer_task.delay(request_dict) response = response.get() return Response(response) And the celery task in tasks.py: @app.task(bind=True) def celery_search_customer_task(self, req_data={}): api_obj = ApiCall(request=req_data) response = api_obj.search_customer() # this makes an API call to another system return response Apache Bench command: ab -p req_data.data -T application/x-www-form-urlencoded -l -r -n 10 -c 10 -k -H "Authorization: Token <my_token>" http://<my_host_name>/<api_end_point>/ Following is the result of ab: Without celery Async Task Concurrency Level: 10 Time taken for tests: 1.264 seconds Complete requests: 10 Failed requests: 0 Keep-Alive requests: 0 Total transferred: 3960 bytes Total body sent: 3200 HTML transferred: 1760 bytes Requests per second: 7.91 [#/sec] (mean) … -
Add element without defining a model Option Field
I have the following form in Django to use it in a filter class TeachersForm (forms.Form): teachers = forms.ModelChoiceField ( required = False, queryset = Teachers.objects.all (), label = "Teachers" ) I need an option to be able to filter the students who have not assigned any teacher, but the queryset returns me the teachers objects that exist. I need to say to show the students where assigned teacher is equal to "Unassigned". "Unassigned" must be a filter option that for Django returns None For example: Not assigned Pepito Fulano Sultano -
how to write custom filed for data like this in django
background:i have some data stored in mongodb,and i want to display them in django. now:i used djongo to connect django to mongodb,and i'm puzzling about how to design model for my json-like data.especially for this one: img_url:{ url1:result1(dict) url2:result2(dict) .... } because i'm new to django ,if there is any other ways to deal with it ,please tell me.. btw,python manage.py inspectdb doesn't work,it says: # Unable to inspect table 'scrapy_items' # The error was: 'NoneType' object is not subscriptable -
argument of type 'NoneType' is not iterable for django string " "
I am trying to split my query based on a space " ". example first_name last_name however if I try to check for spaces in my seach I get the error argument of type 'NoneType' is not iterable if ' ' in query: #This is where is the error is generated Trying to fix the above issue. Below is the entire code class QList(SelectRelatedMixin, ListView): model = Question def get_queryset(self): queryset = super(QList, self).get_queryset().order_by('-created_at') query = self.request.GET.get('r') if ' ' in query: query = query.split() queryset = queryset.filter( chain(User.objects.filter(first_name__icontains=query[0], last_name__icontains=query[1]), User.objects.filter(first_name__icontains=query[1], last_name__icontains=query[0]))) return queryset else: queryset = queryset.filter( Q(title__icontains=query) | Q(user__username__iexact=query) | Q(user__first_name__iexact=query) | Q(user__last_name__iexact=query) ) return queryset Can anyone suggest a workaround -
How to show chart of Annual Growth Rate using highcharts in django?
I'm trying to render annual growth rate using highcharts in Django. There is only one Branch model and in views, I'm trying to generate the queryset to group by year. As I have only one model, I'm getting specific Branch instance to that year only while I need to get all the branch instances for each year to visualize the data. models.py import datetime from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator def current_year(): return datetime.date.today().year def max_value_current_year(value): return MaxValueValidator(current_year())(value) class Branch(models.Model): branch_id = models.IntegerField() name = models.CharField(max_length=50) sales_amount = models.IntegerField() date = models.PositiveIntegerField( default=current_year(), validators=[MinValueValidator(1984), max_value_current_year]) views.py from django.db.models import Count, Q, Sum from django.shortcuts import render import json from .models import Branch def index(request): dataset = Branch.objects.values('date', 'sales_amount').annotate( sales=Count('sales_amount')) categories = list() sales = list() for entry in dataset: categories.append('Year %s' % entry['date']) sales.append(entry['sales_amount']) return render(request, 'index.html', { 'categories': json.dumps(categories), 'sales': json.dumps(sales), }) index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>HomePage</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="main.css"> <script src = "{% static 'js/jquery.min.js' %}"></script> </head> <body> <div id="container" ></div> <script src = "{% static 'highcharts/code/highcharts.js' %}"></script> <script> Highcharts.chart('container', { chart: { type: 'column' }, title: { text: … -
botocore.response.StreamingBody as django FileResponse
I'm implementing a download api which is a wrapper over boto3 get_object method which returns a StreamingBody of an object in AWS S3. While the download method is working as expected when I just django running but I get the below stacktrace when django webapp is configured with uWSGI. Any idea why this might be happening? def download(request): """ download. """ file_name = request.query_params.get("filename") file_obj = get_file_object(file_name) return FileResponse(file_object, as_attachment=True) The utility function def get_file_object(filename: str, key:str): """ Utility function ( wrapper over Boto's S3 get_object()) """ result = boto3.client("s3").get_object(Bucket=AWS_BUCKET, Key=key) return result["Body"] the below is the stacktrace... TypeError: argument must be an int, or have a fileno() method. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 152, in __call__ response = environ['wsgi.file_wrapper'](response.file_to_stream) SystemError: <built-in function uwsgi_sendfile> returned a result with an error set -
Django: how to arrange products according to categories in admin page
In the admin page, I have two models: Category and Product. When I open the Product model, I see the listing for individual products. How can I sort the products according to the categories? The "directory structure" of what I'm currently getting: Categories (Model Root) | ----Footwear ----Topwear Products (Model Root) | ----T-shirt ----Sneakers ----Jacket ----Boots The "directory structure" of what I want to get: Categories (Model Root) | ----Footwear ----Topwear Products (Model Root) | ----Footwear | ----Sneakers ----Boots ----Topwear | ----T-shirt ----Jacket -
Django Serializer for image array slows things down
I am currently making a Django app that recieves a POST request containing byte array that, given a width and height, is turned into a 2d numpy array. I have changed the names of my classes when posting here on Stackoverflow, everything compiles and runs ok, this is a timing issue. Normally it takes 0.02s to parse the incoming request when measured using timer. class APIViewEndPoint(APIView): def post(self, request): params = json.loads(request.body.decode('utf-8')) array = params.get("array") height = params.get("height") width = params.get("width") image = np.array(array, dtype=np.uint8).reshape(height, width) This is the serializer which is a much nicer pattern for handling incoming requests. class PostRequestSerializer(serializers.Serializer): width = serializers.IntegerField(required=True) height = serializers.IntegerField(required=True) array = serializers.ListField(required=True) Now, we use the serializer and the time takes 0.8s when measured using timer. class APIViewEndPoint(APIView): def post(self, request): params = json.loads(request.body.decode('utf-8')) serializer = LongitudinalSerializer(data=params) if(serializer.is_valid()): data = serializer.data image = np.array(data["array"], dtype=np.uint8).reshape((data["height"], data["width"])) Is there a faster way to serialize an array in Django? Ideally, it'd be great if the serializer could also handle the reshaping of the incoming array. Are there any thoughts on this? -
How can I send the values of variables in the templates script to url in django?
In django, I would like to process {% url%} by putting the value of any variable in the TAG value of templates. pp_001.html <script> $('#dataTables-wkgrid tbody').on( 'click', 'tr', function () { var data = table.row( this ).data(); if ( $(this).hasClass('selected') ) { $(this).removeClass('selected'); } else { table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); $.ajax({ type: "GET", url: "{% url 'pp_02_open' %}", data : { "cPp_no" : data.pp_no }, dataType: "json", cache: false, success: function(result){ console.log(result) ; var aTag = "" ; $.each(result.filelist,function(index){ cDocName = result.filelist[index].doc_name ; cFilename = result.filelist[index].file_name ; cid = result.filelist[index].id ; cpp_no = result.filelist[index].pp_no ; aTag += '<a href="{% url "pp_02_download" id=cid %}" class="list-group-item">' +'<i name="iText" class="fa fa-file-powerpoint-o fa-fw"></i>'+result.filelist[index].doc_name +'<i name="file_downloads" class="pull-right glyphicon glyphicon-cloud-download style="padding-left:10px">다운로드</i>' +'</span>' +'</a>' </script> urls.py path(r'^PP/download/<int:id>/$' , views_pp.download , name="pp_02_download"), ERROR.... Reverse for 'pp_02_download' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['crms/\^PP\/download\/(?P[0-9]+)\/\$$'] In other words, when the value of the variable of jsp script is {% url "pp_02_download id = cid%}, I wonder how it is possible to pass the value of cid. If you pass "10" randomly instead of cid in this way, it will execute normally. -
DRF - How to create a ListSerializer from an array of serializer
I have a serializer that I am populating using a function. So I am stacking a list of this particular serializer on an array. How do I transform this array of serializer into a ListSerializer per say? Here is my code: serializers.py class CourseSerializer(serializers.ModelSerializer): class Meta: model = models.Course fields = ( 'name', ) class ErrorSerializer(serializers.Serializer): error = serializers.CharField(max_length=100) class Meta: fields=( 'error', ) class EqSerializer(serializers.Serializer): course = CourseSerializer(many=False) error = ErrorSerializer(many=False) api.py ... for c in serializer.validated_data: course = models.Course.objects.filter(id=1)#simplifying if len(course)==0: error="No Courses Found" elif len(course)>1: error="Too many courses" else: x = serializers.CourseSerializer(course[0]) e = serializers.ErrorSerializer(data={'error':'none'} ) e.is_valid() equate = serializers.EquateOutSerializer(data={'course':x.data,'error':e.data}) ferr.append(equate) #ferr is my array of EquateOutSerializer resp = serializers.EquateOutSerializer(data=ferr,many=True)#problem is here How do I make this ferr into a serializers.EquateOutSerializer list -
How to send data from CBV form to a template CBV?
I'm trying to send the POST data from a CBV form to other CBV. I use the valid_form method to get the info by form.cleaned_data and then i apply in this method some custom methods. But I cant send the result to the other view. Also I tried put an action in the html sending to the other template and then grab the data but I cant. views.py from django.shortcuts import render from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from .forms import QuoteForm from .models import SmgQuotesTable from .quotes import Quotes class QuoteFormView(FormView): template_name = 'core/home.html' form_class = QuoteForm success_url = 'quotes' def form_valid(self, form): name = form.cleaned_data['name'] email = form.cleaned_data['email'] couple = form.cleaned_data['couple'] age = form.cleaned_data['age'] kids = form.cleaned_data['kids'] #query_filter = Quotes().planSelector(couple, kids, age) #obj = SmgQuotesTable.objects.filter(composite='Ind. Junior (H25)') return super(QuoteFormView, self).form_valid(form) class QuoteView(TemplateView, QuoteFormView): template_name = "core/quotes.html" def get_queryset(self): queryset = super(CLASS_NAME, self).get_queryset() queryset = queryset # TODO return queryset home.html {% block content %} <style>label{display:none}</style> <form method="post" action="{ url 'quote' }">{% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary btn-block py-2" value="Cotizar"> </form> {% endblock %} urls.py from django.urls import path from .views import QuoteFormView, QuoteView urlpatterns = [ path('', QuoteFormView.as_view(), name='home'), path('quotes/', QuoteView.as_view(), name='quotes'), … -
Django, having Q object filter by users full_name
I have a simple search box that searches for posts(filters post) by title, first_name, last_name, however no matter how hard I try I am not able to search by users full_name In my models I have User.full_name = property(lambda u: u"%s %s" % (u.first_name, u.last_name)) In my terminal Django Shell I get the below results >>> user.first_name 'Blake' >>> user.last_name 'Lively' >>> user.full_name 'Blake Lively' Now when I try searching with the users full_name I get the below error Related Field got invalid lookup: full_name Q(user__full_name__icontains=query) Below are my views class QList(SelectRelatedMixin, ListView): model = Question select_related = ('user', 'group') template_name = 'questions/all_questions.html' context_object_name = 'all_questions' paginate_by = 5 def get_queryset(self): queryset = super(QList, self).get_queryset().order_by('-created_at') query = self.request.GET.get('r') if query: queryset = queryset.filter( Q(title__icontains=query) | #This works Q(user__username__iexact=query) | #This works Q(user__first_name__iexact=query) | #This works Q(user__last_name__iexact=query) | #This works Q(user__full_name__icontains=query) #This Fails what am I doing worng ) return queryset -
How to make Date fields in models not required using in html input type=date
That's what I have: models.py class Comic(models.Model): title = models.CharField(max_length=255, blank=False) date_of_purchase = models.DateField(blank=True, null=True) views.py def add_to_my_collection(request): if request.method == 'POST': comic = Comic.objects.create( title = request.POST['title'].capitalize(), date_of_purchase = request.POST['date_of_purchase'] ) file.html <form class="create_edit" action="/add_to_my_collection" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="title">Title:</label> <input name="title" type="text" class="form-control" id="title" value="{{comic.title}}"> </div> <div class="form-group"> <label for="date_of_purchase">Date of purchase:</label> <input name="date_of_purchase" type="date" id="date_of_purchase" class="form-control"/> </div> <div class="sub_but"> <button type="submit" class="btn btn-primary btn-block">Submit</button> </div> </form> As you can see in models date field can be empty. But if I run it without filling the date field I get an error: django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."] How I can fix it? -
How to avoid stretching profile pictures in Django?
I made a signal that makes profile page of every single user once user is saved and in profile template the user can update their profile picture. Everything is okay but one thing, when the user upload his profile picture it looks like this: you can see profile picture is annoying it stretched itself from right and left. please help me solve it. this is the code of my template: <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> and views.py @login_required def profile(request): if request.method == "POST": prof_form = ProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile) user_form = UserUpdateForm( request.POST, instance=request.user) if prof_form.is_valid() and user_form.is_valid(): prof_form.save() user_form.save() messages.success( request, 'Your profile has been updated successfully!') return redirect('profile') else: prof_form = ProfileUpdateForm(instance=request.user) user_form = UserUpdateForm(instance=request.user) context = { 'prof_form': prof_form, 'user_form': user_form } return render(request, "users/profile.html", context) thanks in advance -
How to use into django Model a value from django Views's function?
I am facing a basic problem since few day ago so now I have decided to ask a question after tried to do many many example but stilled have the same issue with my model. I am using a function to get user ip address into my django model for me to determine the user country and more others and so far nothing seem to work, I have also used a Class but I stilled have the same problem. So I was trying to do any how to fix the issue but I couldn't. My main problem is that I want to get a function value from the Views to the Model, for example, from the register view I can get the the user ip address and use it into my register model to determine the the country. I just need to get the ip address from the register views to the register model. Please any help will be highly appreciate. this is my function views: #the variable ip for the beginning ip_address_one = '0.0.0.0' def take_ip(request): global ip_address_one x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] ip_address_one = ip else: ip = request.META.get('REMOTE_ADDR') ip_address_one = ip it's still have … -
Override list method in Django rest ViewSet
In a Django Rest Framework ViewSet I have an overrided list() class TicketViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): def_list(): make_my_checks() things_copied_from_parent() Since the list() has many lines of code and I must make checks in every ViewSet, how can I make this checks and return the overrided method? A thing like: def_list(): make_my_checks() super(list()) -
Database being overloaded by mysterious count query
Periodically we have been having downtime on our site and we can't explain it. It's pretty sporadic without any noticeable patterns, but in the past 24 hours, we've had 6 instances. When we have the downtime, it seems to be that the database is being overloaded by a particular query (see image): SELECT COUNT(*) FROM "cache" We've looked at all the code and workers and can't find anywhere in the code executing a count of this table. Does anyone have any ideas of how Django might be translating a query into a count, other than an explicit count() or len()? Or could this be the work of hackers? Any input would be greatly appreciated. -
Django multiple table join on using ORM
I am trying to join multiple table using django ORM .i have tried several different way but no luck. from django.db import models from compositefk.fields import CompositeForeignKey, CompositeOneToOneField class Company(models.Model): code = models.DecimalField(db_column='Code', max_digits=38, decimal_places=0) srccode = models.SmallIntegerField(db_column='SrcCode') est = models.DateTimeField(db_column='Est') rownum = models.BigIntegerField(db_column='RowNum') class Meta: manage = False unique_together = (('code', 'srccode'),) db_table = 'Company' class Floor(models.Model): code = models.DecimalField(db_column='Code', max_digits=38, decimal_places=0) srccode = models.SmallIntegerField(db_column='SrcCode') depcode = models.DecimalField(db_column='DepCode', max_digits=38, decimal_places=0) depsrccode = models.SmallIntegerField(db_column='Depsrccode') floorname = models.CharField(db_column='FloorName') rownum = models.BigIntegerField(db_column='RowNum') company = CompositeForeignKey(Company,on_delete=models.CASCADE,to_fields={'code':'code','srccode': 'srccode'}) department= CompositeOneToOneField(Department,on_delete=models.CASCADE,to_fields={'depcode':'depcode','depsrccode': 'depsrccode'}) class Meta: manage = False unique_together = (('depcode', 'depsrccode','floorname'),) db_table = 'floor' class SubCompany(models.Model): code = models.DecimalField(db_column='Code', max_digits=38, decimal_places=0) srccode = models.SmallIntegerField(db_column='SrcCode') subname = models.CharField(db_column='SubName') rownum = models.BigIntegerField(db_column='RowNum') location = models.CharField(db_column='Location') department = models.CharField(db_column='Department') company = CompositeForeignKey(Company,on_delete=models.CASCADE,to_fields={'code':'code','srccode': 'srccode'}) class Meta: manage = False unique_together = (('code', 'srccode','subname','rownum'),) db_table = 'SubCompany' basically i am trying to get data as per below row sql SELECT Location, Department, Subname, t.* from [Floor] t join [SubCompany] s on t.code = s.code and t.srccode = s.srccode;" what is the equilant Django Orm of above SQL query.? is there any alternative solution apart from raw sql in django.? Thanks -
Creating forms with multiple input types
I am trying to create an input form field which can take text, images or videos as we see in Twitter. I am trying the following: from django import forms from .models import Tweet class TweetModelForm(forms.ModelForm): content = forms.CharField(label='', widget=forms.Textarea( attrs={'placeholder': "Your message", "class": "form-control"} )) Which produces However, I am trying to use the same input box so that user can upload image, video, GIFs or just type text in the box. I am not sure how to modify the above form field.