Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
most common words in array fileld postgres
I have a model with an array field in it. This field contains some words for each entity. Model is as follows : class Entity(models.Model): words = ArrayField( models.CharField(max_length=255, blank=True), null=True, blank=True ) I want to accumulate lists of all objects of this model and find 100 most common words occurred in these arrays. Is there any way to do this in Postgresql, or what is the efficient way to do this? -
Django how to sort Datefield by order of Day-month to show birthday list
I want to accept users birthday and have a page which shows everyone's birthday ignoring which year they were born in Heres my models.py for CustomUser: from datetime import datetime, date from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): # First/last name is not a global-friendly pattern name = models.CharField(blank=True, max_length=255) birth_date = models.DateField(("Birth Date"), default=date.today) def __str__(self): return self.email Here is my views.py logic: def birthdaylist(request): if(request.user.is_authenticated): users=CustomUser.objects.order_by('birth_date')[:] # ignore the line below # users= CustomUser.objects.extra(select={'birthmonth':'birth_date'},order_by=['birthmonth']) context={ 'users':users } return render(request,'dashboard/birthdaylist.html',context=context) else: return redirect('login') Here is my forms.py: import datetime from bootstrap_datepicker_plus import DatePickerInput from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser now = datetime.datetime.now() fields = ('username', 'email', 'gender', 'security_question', 'answer', 'birth_date', 'resume') widgets={ 'birth_date' :DatePickerInput( options={ 'maxDate':str(datetime.datetime.now()), #this needs width positioning } ) } I am using bootstrap datepicker plus widget to pick the date. Can someone help me on how do I get the desired result in my views .py? I feel something needs to be added in my order.py if u need me to add anything then comment. PS: I am using Django 2.0.6 version -
Django function based form not valid
I'm trying to make a function based form for taking input from the user to create a customer table. I'm using a function based form but when I use form.is_valid() it's returning false. def customer(request): form = customerForm(request.POST or None ) print(form) context = {'form':form} if form.is_valid(): mobile_no = form.cleaned_data["mobile_no"] print("mobile_no") object = Customer.objects.get(mobile_no=mobile_no) if(object is not None): invoice_no = Bill.objects.all().count() obj = Bill.objects.create(customer_info=object,invoice_no=invoice_no+1,shop_details=ShopDetail.objects.all()) return redirect(reverse('receipt:create-bill',kwargs = {'pk':obj.pk})) return HttpResponse("<h1>Form invalid</h1>")#redirect(reverse_lazy("home")) -
Filter data based on sum of two fields
I have following Django model class OfflineExamResult(models.Model): """ Model to store result of offline exam """ batch = models.CharField(max_length=40, null=True, blank=True) date = models.CharField(max_length=20, null=True, blank=True) full_marks = models.IntegerField(default=80) rank = models.CharField(max_length=5, null=True, blank=True) uid1 = models.CharField(max_length=10, null=True, blank=True) uid2 = models.CharField(max_length=10, null=True, blank=True) name = models.CharField(max_length=30, null=True, blank=True) marks = models.CharField(max_length=5, null=True, blank=True) The students in my class have been allotted a roll number which is sum (string sum) of uid1 and uid2. I want to create a search field so that students enter their roll number and get their result which will happen, only if I am able to filter objects after comparing roll number to sum of uid1 and uid2. -
Not able to serve static file using Apache server for Django Application
I was using Django to serve my static file and now i have deployed my site on Digitalocean and now I want to use Apache server to serve my static and media file. I am going somewhere wrong. Any help would be appreciated. I am attaching screenshot. In setting.py file I have changed DUBUG=True to DUBUG=False and my url.py still contain if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But as my DEBUG=False then it would not run and in my setting file, I have used STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media' I am using my static file as <img src="{% static 'images/canva-photo-editor (6).png' %}" alt="Temple1"> But when i was having DEBUG=True then as mentioned above in urls.py I was serving using Django and now i am using apache server so it is now not being served by Django. When i try to access any static and media file using Apache it is not showing any css, images etc. -
Run django test parallel with in memory sqlite3
Is it possible to run django test cases in parallel with in memory sqlite3 with new database for each test case? Docs says: "--parallel" Runs tests in separate parallel processes. Each process gets its own database. DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'} When I run my test in single process, all goes well. python.exe manage.py test order --settings=gbook.settings_test When i use --parallel param, DiscoverRunner.setup_databases called only one time. python.exe manage.py test --settings=gbook.settings_test --parallel=4 Please, help me to understand, what am i doing wrong. multiprocessing.cpu_count() = 4 Django version 1.11.10 Python 3.6.5 -
Django DRF: How to put two different fields together as one
Have searched many answers but could not find what I am looking for: I have two fields (one is foreign key) that would return something from the serializer that looks like this: [{"prodID":"SV1", "Amount":"10"}, {"prodID":"RV1", "Amount":"37"}, {"prodID":"GG2", "Amount":"22"}] What I would really want, (then I don't have to change my front-end) is: [{"SV1":"10"}, {"RV1":"37"}, {"GG2":"22"}] Would this be possible to do with django? -
How to store and search Resume's (CV's) on Django?
In Django, I have a process where a user can upload a resume, which gets stored on my fileserver. For each resume uploaded a member of staff creates a Database record (fills in a form which is saved to postgresql) My dilema is that the actual resume is either a microsoft word document or a pdf document. I want staff upon calling up the candidate profile which has a list of resumes that the candidate has sent in, I want staff to be able to open the resume and have a read of the docx or pdf file which the web page has a path to. How should i go about doing this. The other thing is, in phase 2, i want staff to be able to search the resumes for certain skill sets, so i am not sure if the staff should: make a summary of skills and store under the candidate record for searching later or maybe the staff should convert all pdf and docx documents to text strings and store in a field under the candidate record. or maybe i should keep the files as pdf and docx and somehow (i dont know how) i should create … -
large file uploads in PHP, Python, Django
Any methods to upload large files (not readable by the system, for example AFP, ZIP or PS, PGP files) consistently and accurately? The files can be individual or folder; sizes ranging from MB to multiple of GBs. I've seen many struggling with this. Any direction or method is appreciated. Thank you. -
Django, Get the count of records added/not added to the database [succesfull, with a warning, error]
I am adding data to the database and I need to get the count of successfully added records, records added with a warning and the count of records not added at all. For now we are using class ModelPersistence(object): def __init__(self): self.WARN = 0 self.ERRORS = 0 self.SUCCESS = 0 def save(self, model=None): # pass the model object to be saved if model is not None: try: model.save() self.SUCCESS = self.SUCCESS + 1 except Exception as exception: self.ERRORS = self.ERRORS + 1 with warnings.catch_warnings(record=True) as warning: self.WARN = self.WARN + 1 def get_result(self): return self.SUCCESS, self.WARN, self.ERRORS def clear(self): self.WARN = 0 self.ERRORS = 0 self.SUCCESS = 0 Is there a better method than this? Thank you. -
Password Reset in django
how do i reset user password using security question method. I take security question and answer at the time of sign up. I want to redirect the user to security question page when he clicks on Forget Password link and then send him to password reset page if he answers the question correctly. -
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
My DecimalFields are giving error when trying to load the site. Can anyone help me with this ? models.py from django.db import models from opinionatedstore.persons.models import Person class Order(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) products_str = models.TextField(blank=True) order_date = models.DateField(auto_now_add=True) item_total = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True) shipping_fee = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True) profit = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True) shipping = models.IntegerField(choices=Person.SHIPPING_CHOICES, blank=True, null=True) payment = models.IntegerField(choices=Person.PAYMENT_CHOICES, blank=True, null=True) -
Receive POST data from Trumbowyg URL image upload
I'm using Trumbowyg, a WYSIWYG JavaScript editor which has a feature of rendering images from URLs pasted in. It also has an upload plugin which enables custom handling of the images. The documentation for this plugin gives a serverPath variable which is supposed to represent The URL to the server which catch the upload request. I've tried to do that with the following: $('#id_content').trumbowyg({ btnsDef: { // Create a new dropdown image: { dropdown: ['insertImage', 'upload'], ico: 'insertImage' } }, // Redefine the button pane btns: [ ['strong', 'em', 'del'], ['superscript', 'subscript'], ['link'], ['image'], // Our fresh created dropdown ], plugins: { // Add imagur parameters to upload plugin for demo purposes upload: { serverPath: '/upload_image/', fileFieldName: 'image', urlPropertyName: 'data.link' } } }); by adding /upload_image/ as my serverPath. This is supposed to target my upload_image() function in my Django views however it does not def upload_image(request): print('SUCCESS') #does not print so I don't think I am doing this right. What value do I put in serverPath to receive the inputted image URL in my Django views? -
Zappa django response time
When deploying a bare-bones Django application using Zappa, I'm finding my TTFB (Time To First Byte) times are between 280-800ms however generally around 700ms. Which is far too long for a website. Other people seem to be getting much better response times such as "125ms to 500ms ... (probably averaged about 175ms)" (https://www.reddit.com/r/django/comments/44r55j/announcing_djangozappa_serverless_django_on_aws/). To reproduce my issue: pip3 install django-admin mkdir test cd test virtualenv .env source .env/bin/activate pip3 install django zappa django-admin startproject zaptest zappa init (and choose all defaults) zappa deploy dev And go to the URL supplied. Any advice on how to speed this up would be much appreciated. -
using Case in django
I am trying to display the value A,B,C or D as per the total of a blogger. But I am getting the error - Cannot resolve keyword 'total' into field.Can someone suggest the correct way of doing it. Thanks models.py class Blog(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blogs') likes = models.ManyToManyField(User, blank=True, related_name='blog_likes') title = models.CharField(max_length=100) @property def total(self): return count(self.author.title) + count(self.author.likes) views.py def get_queryset(self): return (Blog.objects.filter(date__lte=timezone.now()) .order_by('date') .annotate( name=Case( When(total__gt=0,total__lte=11, then=Value('B')), When(total__gt=10,total__lte=21, then=Value('C')), When(total__gt=20,total__lte=31, then=Value('D')), default=Value('A'), output_field=CharField(), ), ).values_list('name') ) -
Django: where to store functions common to all apps
I am new to django I have some functions, which will be used by all the apps in the project, I don't know where to store those files and how to call them. Is there a recommended way for storing those files in the project. -
Django Error: Cannot use ImageField because Pillow is not installed
I'm currently learning how to use Django to develop a web service. As I go through an online course on Udemy, I ran into a problem using ImageField in models.py. My problem is that, when I excute the runserver command, Django shows the following error although I am pretty sure the library Pillow is installed. In models.py, I have the following code: from django.db import models from django.contrib.auth.models import User class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) portfolio = models.URLField(blank=True) picture = models.ImageField(upload_to="profile_pics") def __str__(self): return user.self.username When I runserver, I get the following error: python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors<locals>.wrapper at 0x10407b6a8> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/core/management/base.py", line 410, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: first_app.UserProfileInfo.picture: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". System check identified 1 issue (0 silenced). So, by following the message I checked the installed modules by using the method introduced here: How can I get a list of locally installed … -
How can i push to heroku
I try to deploy my aplication to Heroku. At the end, when I execute "git push heroku master --force" occurs the error "Could not find a version that satisfies the requirement anaconda-client==1.6.14". I´ve already installed anaconda "conda install -c anaconda anaconda-client", but nothing happen. -
Testing manual transactions inside Django unittests
How do you test code that disables autocommit and uses savepoints, inside a Django unittest? The default Django unittest class wraps all tests inside an @atomic decorator, which is usually exactly what you want, to ensure the sqlite database gets reset between tests. However, any code that touches transaction.set_autocommit() from a test throws the error: TransactionManagementError: This is forbidden when an 'atomic' block is active. even if it works fine outside the unittest. How do you temporarily disable the transaction autocommit in a unittest, so you can test manual commits? -
Django allauth - can I disable redirects after Social logins?
I would like to disable redirects after Social logins in django allauth, i.e. if a user is on page 'X' (and not logged in), then chooses to log in (via ajax request), they should remain on page 'X' (no reload/redirect etc.). This functionality would be similar to the normal Account setting, i.e. 'ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False' As far as I know there isn't a 'SOCIALACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS' setting available. -
Django Model relationships with foreign keys
I'm attempting to replicate the data scheme for the data seen here. Each launch has a location with a single pad, my model is currently defined as shown below: class Location(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255, blank=True, default="") country_code = models.CharField(max_length=255, blank=True, default="") def __unicode__(self): return self.name class Meta: verbose_name = 'Location' verbose_name_plural = 'Locations' class Pad(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255, blank=True, default="") info_url = models.URLField(blank=True, null=True) wiki_url = models.URLField(blank=True, null=True) map_url = models.URLField(blank=True, null=True) location = models.ManyToOneRel(Location, related_name="pads", blank=True, on_delete=models.CASCADE) def __unicode__(self): return self.name class Meta: verbose_name = 'Pad' verbose_name_plural = 'Pads' If I query the launch from a Django shell it only has the single correct pad. However once I serialize (seen here) the launch with Django Restframework it pulls all pads with the location - example: "location": { "id": 16, "name": "Cape Canaveral, FL, USA", "country_code": "USA", "pads": [ { "id": 62, "name": "Space Launch Complex 37B, Cape Canaveral, FL", "info_url": null, "wiki_url": "https://en.wikipedia.org/wiki/Cape_Canaveral_Air_Force_Station_Space_Launch_Complex_37", "map_url": "http://maps.google.com/maps?q=28.531700,-80.564950" }, { "id": 84, "name": "Space Launch Complex 40, Cape Canaveral, FL", "info_url": "", "wiki_url": "https://en.wikipedia.org/wiki/Cape_Canaveral_Air_Force_Station_Space_Launch_Complex_40", "map_url": "http://maps.google.com/maps?q=28.56194122,-80.57735736" } ] -
Using JSON to implement User Defined Fields for a Document Management System
We are developing a document management system. The user approaches our system and creates his own document. So, there is a need to implement custom fields i.e, user-defined-fields. Basically, each document has different fields with different datatypes. Is using JSON Field in mysql the best way to implement this? If so, how? Else, what would you suggest? I am looking for performance. -
How to use Jquery ajax to add Django's dynamic field and crsf token
I am trying to implement an ajax call to update a watchlist from my django app. I was able to produce the 'looks' of it. however on element inspection i saw that my form input data was not correct. Please have a look at the image to see what my issue is. enter image description here Selected Jquery Code $.ajax({ url: actionEndpoint, method: httpMethod, data: wlformData, success(data){ console.log(data) $('.append-ajax').append(` <form class="form-blog-ajax" action="{% url 'watchlist:add' %}" method="post" enctype="multipart/form-data"> <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}"> <input type="hidden" name="watchlist_id" value="{{ watchlist_item.id }}"> <input type="hidden" name="object_id" value="{{ blog.id }}"> <button class="btn btn-outline-secondary waves-effect col-9" type="submit"> <span class="submit-span"></span>` + data.new_watch_list + ` <span class="count badge badge-primary badge-pill ml-2">` + data.count + `</span> </button> <br><br> </form> `) }, HTML i wish to append the new form into <ul class="list-group mx-4 text-center append-ajax"> {% for watchlist_item in watchlist %} <form class="form-blog-ajax" action="{% url 'watchlist:add' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="watchlist_id" value="{{ watchlist_item.id }}"> <input type="hidden" name="object_id" value="{{ blog.id }}"> <button class="btn btn-outline-secondary waves-effect col-9" type="submit"> <span class="submit-span"></span>{{ watchlist_item.name }} <span class="count badge badge-primary badge-pill ml-2">{{ watchlist_item.blogs.count }}</span> </button> <br><br> </form> {% endfor %} </ul> -
How can I add choices to a timefield in a Django form?
In one of my models I have the following: time = models.TimeField() In a modelform based on this model I want time to be a dropdown with a few choices, so I tried this: time = forms.TimeField(label="time", choices=[(datetime.time(0, 0), "Midnight"), (datetime.time(12, 0), "Noon")]) I get the following error: TypeError: __init__() got an unexpected keyword argument 'choices' Do I have to put choices in my model's timefield or is there a way to be define it in the form ? -
Django add prefix to AutoField
Is there a way to create an AutoField in Django that always begins with a certain prefix? I would like to create an AutoField that always begin with the number 1, where the first 15 saved records would have the values 11, 12, 13, 14, ..., 19, 110, 111, 112, 113, 114, 115.