Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap datetimepicker $(...).datetimepicker is not a function, even after putting script in correct order
I am using django-bootstrap4-datetimepicker. Below is the order in which I am including the needed javascript files. Even after that it is giving - Uncaught TypeError: $(...).datetimepicker is not a function {% extends 'base.html' %} {% load static %} {% block extra_head %} <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css"> <link rel="stylesheet" href="{% static 'css/timeline.css' %}"> {{ form.media }} </head> {% endblock %} <div class="middle"> {% block content %} {% endblock %} </div> </html> Here is how I am using it in the HTML file. $(document).ready(function () { if (sessionStorage.scrollTop != "undefined") { $(window).scrollTop(sessionStorage.scrollTop); } $('#act_time').datetimepicker({ format: 'MM/DD/YYYY HH:mm', maxDate: new Date(), minDate: new Date("{{ min_date.isoformat }}"), }); }); Any hints/help would be highly appreciated. -
Django get date from user, process it offline to send CSV to user
I may not be able to provide you anything regarding code I tried. But none of searches or research could get me a working result. What I am trying to do? I have a form where user submit a CSV file. This file is processed in backend to retrieve data from DB. Data recovered from DB is again written in CSV and mailed to user. This processing takes around 5-10 minutes. So I want to show a message to user that your work is under process and you will bet CSV file once it is completed. My code as of now. def bulkserachpro(request): with request.FILES['searchnum'] as csvfile: spamreader = csv.reader(csvfile,dialect=excel) next(spamreader) a = [] b = [] for row in spamreader: a.append((row[0]).upper()) data_list = nummodel.objects.filter(number__in=a) csvfile = StringIO.StringIO() csvwriter = csv.writer(csvfile) csvwriter.writerow(['a','b']) for data in data_list: csvwriter.writerow([data.a,data.b]) message = EmailMessage("Hello","Your report","email@gmail.com",["emailto@gmail.com"]) message.attach('invoice.csv', csvfile.getvalue(), 'text/csv') message.send() return render(request,'bulkpro.html',messages.add_message(request, messages.SUCCESS,'File uploaded Succesfully.')) This code does its job. But as user cannot wait for 5-10 minutes, he will get timeout error message. What should I change here so that user gets following message and once processing is done he receives email with attachment. Your file is received, it will be processed and sent … -
How to filter queryset with complex calculation?
I want to filter a list of objects based on some complex calculation, but I am not sure how to do it. For example: M2MObject(Model): a = IntegerField() b = IntegerField() MyObject(Model): values = ManyToManyField(M2MObject) I want to filter MyObject instances based on a complex calculation (it has multiple steps, and things like combining variable a and b from each instance with some parameters). For example, I would like to do something like this: # Just some random calculation def complexCalc(a1, b1, a2, b2): x1 = a1 * (a2 + b2) x2 = a2 * (a1 + b1) return x1 * x2 objs = MyObject.objects.filter(complexCalc(F("values.a"), F("values.b"), 12, 22) > 0) F() being the function to access fields of each MyObject in the query. (NOTE: F("values.a") do not work, but it would help me a lot if something similar exists) -
PostgreSQL on RDS suddenly eating all the storage available on the disc
One of the query is causing my Postgres to freeze and it also results in some weird behaviour such as increased read/write IOPS and db eating all the space on the device. Here's some graphs which demonstrate the same. Before deleting the query After deleting the query Any idea why is this happening? -
When creating a model, how do you know when to seperate and break it apart vs keep it all under one?
I want to create a simple blog for my translations. I am following this tutorial by djangogirls (https://tutorial.djangogirls.org/en/django_models/). I have a basic layout already made on html: Screenshot of blog page This is the model that I have came up with. Post ---------------- title text author created_date published_date tag image category translated news original article original article source related articles I am having trouble figuring out when/where I should break up the properties. I don't remember where I read it, but someone has said that you should keep it small. Like one ice cream flavor and not group 100s of flavors into one object. Am I doing more than I can chew? Or am I just overthinking things. For the simple blog I want to create, am I proceeding in the correct way? -
Django Custom Querysets
Using the usual Django model as an example, I'm trying to view with a table of authors where I can sort by their number of books. Creating the book count as a model method (as below) works fine for the display, but that rules out sorting by that 'field' in the queryset: class Author(models.Model): first_name = models.CharField() last_name = models.CharField() def book_count(self): return Book.objects.filter(author=self).count() class Book(models.Model): title = models.CharField() author = models.ForeignKey(Author) I know I could post-queryset sorting, but I'm also applying Django pagination, so retrieving all the records would presumably have a performance hit.. I think adding Manager Methods is the answer, but I'm struggling to make it work: class AuthorManager(models.Manager): def book_count(self): return Books.objects.filter(author=self).count() class Author(models.Model): title = models.CharField() author = models.ForeignKey(Author) objects = AuthorManager() My django template is not returning anything. Is the problem the construction of the manager above, or how to call it in the template? I've assumed it would just be (this works for my model method above, but not for a manager method): {% for author in authors %} {{ author.book_count }} {% endif %} Many thanks! -
Django dev server on VPS: no external connection on port 8000
I'm trying to deploy my Django app and followed this DO tutorial rather closely (except for putting rather sensitive info to env variables). The server is pretty fresh and I just installed ufw and opened port 8000: To Action From -- ------ ---- 22 ALLOW Anywhere 8000 ALLOW Anywhere 22 (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) Doing python manage.py runserver 0.0.0.0:8000 with ALLOWED_HOSTS='*' I couldn't connect via ip_address:8000 from my local web browser (same ip_address I use for ssh). The request simply times out. I also cannot ping the server IP. But ssh works nicely. I'm not sure if it's a server/firewall issue. I'm really a newbie to server architecture, so any help would be appreciated! It seems odd that ssh can connect on port 22, but the browser can't on port 8000... This is the output of netstat -vatn: (website_env) nilsnolde@localhost:~/www/geophox_mainsite$ netstat -vatn Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN tcp 0 0 127.0.1.1:5432 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN tcp 0 0 server_ip:22 88.73.67.116:35240 ESTABLISHED tcp 0 0 server_ip:22 88.73.67.116:34344 ESTABLISHED tcp6 0 0 … -
What are serializers in django
I have been trying to understand about serializers in django i got an overview that they are used for converting models into different forms. Can anyone please explain how really are they used. -
Django: How to automatically reset a boolean field to it's default after some time (eg. 6 months) to make full access for a page expire
I am fairly new to django and I have the problem of creating full access for a site. The user has to give some additional information to get full access after signing up. I want the full access to automatically expire after 6 months. I defined a custom user model with the extra condition: models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): full_name = models.CharField(blank=True, max_length=255) has_full_access = models.BooleanField(default=False) #some other stuff After typing in some data for getting full access, the user gets redirected to this view which sets the boolean to true: views.py def data_gathered_done(request): current_user = CustomUser.objects.get(id=request.user.id) current_user.has_full_access = True current_user.save() #some other stuff I want this boolean field to automatically reset to it's default (False) 6 months after the full access has been granted. How can I do that? -
Django - change Form properties while in view
I have this Form: class CategoryForm(forms.Form): def __init__(self, *args, **kwargs): super(CategoryForm,self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' category = forms.ModelChoiceField(queryset =Categories.objects.all() ,empty_label= None,required=True) and i have this view: def testview(request): if request.method == "POST": form = CategoryForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Category successfully added") else: form = CategoryForm() return render (request, 'appform/test.html', {'form':form}) Is there any way i can set widget=forms.Select(attrs={'onchange': 'actionform.submit();'})) for the ChoiceField inside my view? Something like this ( i know it's a poor example but it may express my intent more clearly) def testview(request): if request.method == "POST": form = CategoryForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Category successfully added") else: form = AddCategoryForm() form.category['widget'] = forms.Select(attrs={'onchange': 'form.submit();'}) return render (request, 'appform/test.html', {'form':form}) The reason for which i need this is because i want to reuse the same form, once for deleting- where i use a delete button and the second time for viewing, where i need onchange = form.submit. -
How to add required extra fields to Django registration form
I found some similar question but no one never asked how to make it required fields! I have created a registration form with some extra fields, but I need to force the user to use those fields, and to raise a required error if he leaves it empty here are my files : forms.py class SignUpForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name','email', 'password1', 'password2', ) labels = { 'username': 'إسم المستخدم', 'first_name': 'إسمك الحقيقى(سيظهر كأسم البائع)', 'email': 'البربد الإلكترونى Email', 'password1': 'كلمة المرور', 'password2': 'تأكيد كلمة المرور' views.py def signup(request): current_user = request.user all_dress = Item.objects.all() all_dress_s = Item.objects.all().filter(dress_special=True) if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() context = { 'form': form, 'all_dress': all_dress, 'all_dress_s': all_dress_s, } return render(request, 'fostania/signup.html',context) signup.html <form method="post" align="right"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit" class="btn btn-success">تسجيــل</button><br> بالضغط على تسجيل انت توافق على شروط الإستخدام الخاصة بموقعنا ! </form> Now I need … -
Retrieving user's email from Twitter with Django Social
I am trying to implement Twitter Login using Django social. However, after following the steps below, I'm still not capable of retrieving the user's email. Created a privacy and terms & conditions page and update my app's settings Requested permission to access user's email and got my app whitelisted Regenerated my access tokens Included the following lines in the settings.py file: SOCIAL_AUTH_TWITTER_KEY = os.environ['SOCIAL_AUTH_TWITTER_KEY'] SOCIAL_AUTH_TWITTER_SECRET = os.environ['SOCIAL_AUTH_TWITTER_SECRET'] SOCIAL_AUTH_TWITTER_SCOPE = ['email'] SOCIAL_AUTH_TWITTER_PROFILE_EXTRA_PARAMS = { 'fields': 'email', } TWITTER_EXTENDED_PERMISSIONS = ['email'] TWITTER_EXTRA_DATA = ['email'] Tried to access the user e-mail like that, by still no lack (getting only the username): <script> $(document).ready( function() { var user_email = "{{ user.email }}"; var user = "{{ user }}"; console.log(user) console.log("Email: " + user_email); if(user_email) { $("#email").val(user_email); $("#email").hide(); } } ); </script> When I try to login with Twitter the authorization window pops-up to give access to my e-mail. Also, in my Apps settings in my profile the app is listed as having access to my e-mail. What else should I change or what is wrong with the existing code? -
django get data from foreign key relation child parent child
first, i'am sorry for the title, i don't have idea what title should be. i have database scheme like this models.py class Employee(models.Model): name = models.CharField(max_length=255) class Attendance(models.Model): date = models.DateField() employee = models.ForeignKey(Employee, related_name='attendance') class Salary(models.Model): salary = models.DecimalField(max_digits=20, decimal_places=0) employee = models.ForeignKey(Employee, related_name='salary') and I have detailview for salary. views.py class Salary(DetailView): context_object_name = 'salary_detail' model = models.Salary template_name = 'system/salary_detail.html' on my template.html I use salary_detail.name to show the data. However I also need to show attendance list that used to generate the salary on salary_template.html how to do it?... -
unable to debug django haystack in visual studio
i debugging the django code in viewset(whatever) in the middle i have the results = SearchQuerySet(using='book').filter(text__startswith=search_text.lower()).order_by('book_name') for everything debugging working fine but when it comes haystack code it correct results like 50 or something. whenever i hover the move on this results query: <haystack.backends.elasticsearch_backend.ElasticsearchSearchQuery object at 0x7f038553d490> [0]:<SearchResult> [1]:<SearchResult> again when i hover on first [0] object editor show nothing data inside first object but when i results into serialisezer the output is fine , so why 0th or 1st object is empty when i am debugging -
Django ORM. Filter multiple times many to many
I have the following models: class Item(models.Model): name = models.CharField(max_length=255) attributes = models.ManyToManyField(ItemAttribute) class ItemAttribute(models.Model): attribute = models.CharField(max_length=255) string_value = models.CharField(max_length=255) int_value = models.IntegerField() I also have an Item which has 2 attributes, 'color': 'red', and 'size': 3. If I do any of this queries: Item.objects.filter(attributes__string_value='red') Item.objects.filter(attributes__int_value=3) I will get my Item returned, which is great, because it works as I expected. However, if I try to do a multiple query, for instance, this one Item.objects.filter(attributes__string_value='red', attributes__int_value=3) The output will be: <QuerySet []> Why? How can I build such query that my Item is returned, because it has the attribute red and the attribute 3? -
virtualenv doesn't work on network drive on other computers
I set up virtualenv on network drive using virtualenv python module. It generated me few folders: Include, Lib, Scripts, share, tcl. Inside the folder with these folders i created new one called scr and then pasted there a django app called vistool. Now i created two batch scripts, to allow other users of network drive to run this app: run.bat (main file): cd /d "Z:\xx\Tools\New\Widget - Graphs" cd visual\Scripts start server.bat timeout 30 start http://127.0.0.1:8000/graphtool/ This one seems to work, as it does everything it should. The other one that is called inside run.bat is server.bat, which i placed in Scripts(the same folder where activate.bat is. server.bat (for calling activate.bat and django built-in server): call activate.bat cd.. cd src/vistool call python manage.py runserver Now, these two scripts are working fine for me and they do what they want - open a tab with a django project in the browser. But on other computers in my company this doens't work and I have no idea why. Activate.bat from virtualenv package takes the set "VIRTUAL_ENV=Z:\xxx\Tools\New\Widget - Graphs\visual" Which should be ok, since everyone has got mapped this network disc the same. The errors that they get are: "Could not find django". Even … -
Make a nested reference in one Model class Table
I'd like to make a table with such a structure 1. urls 2. views 3. models 4. templates 4.1 html 4.2 format 4.3 test html, format and test live in the same level with others but reference to 4. templates I could start from the simple easy model as: class Topic(models.Model): """A topic the user is learning about.""" title = models.CharField(max_length=200) sub_tile = models.CharField(max_length=200) How to reference 'sub_title' to 'title' -
Use extends or block tag witha variable in Django Template
In Django templates we can use with the include tag the with tag to add a variable {% include "name_snippet.html" with person="Jane" greeting="Hello" %} I need the same thing but with extends or with a block tag. So, I want to pass to extends or block a variable. If this variable exist the base template/block will do an if and load something different. I want to do this, because I have groups of repeatable situations (and blocks created in child includes don't work) Is this possible ? -
Django ImportError at /admin/ cannot import name 'Session'
I get this message in Django after running runserver: ImportError at /admin/login/ cannot import name 'Session' Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 2.0.5 Exception Type: ImportError Exception Value: cannot import name 'Session' Exception Location: C:\HOMEWARE\Anaconda3-Windows-x86_64\lib\site-packages\django\contrib\sessions\backends\db.py in get_model_class, line 23 Python Executable: C:\HOMEWARE\Anaconda3-Windows-x86_64\python.exe Python Version: 3.6.4 This is part of my code in settings.py: # Application definition INSTALLED_APPS = [ 'AppFinal.apps.AppfinalConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #'AppFinal' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ProjetFinal.urls' I've checked everything, but it seems alright, does anyone knows how to handle this kind of error? thanks -
Creating a Ordered Cart in Django
My goal is to create a shopping cart for the customer which includes customer's name, and the list of items and item quantities that (s)he orders. The front end should look similar to this: I have been trying to find any solution to make this work but to no avail. Tried the example of using Django formset function as shown here and here, but received the following error: TypeError: inlineformset_factory() got multiple values for keyword argument 'form' Does anyone know how to solve this? Any solution works, and it does not have to use formset. This is the code so far: models.py from django.db import models class Model_Customer(models.Model): customer_name = models.CharField(max_length = 100, null = False, blank = False, unique = True) ... ... def __unicode__(self): return self.customer_name class Model_Item(models.Model): item_name = models.CharField(max_length = 100, null = False, blank = False, unique = True) ... ... def __unicode__(self): return self.item_name class Model_Cart(models.Model): customer_name = models.ForeignKey(Model_Customer) item_name = models.ForeignKey(Model_Item) item_orderquantity = models.FloatField(null = True, blank = True) def __unicode__(self): return str(self.id) forms.py from django import forms from .models import( Model_Customer, Model_Item, Model_Cart ) class Form_Cart(forms.ModelForm): class Meta: model = Model_Cart fields = [ "customer_name", "item_name", "item_orderquantity", ] Formset_Cart = forms.inlineformset_factory( Model_Customer, … -
Django1.11 + Python3.6 + Nginx 1.12 + uWSGI 2.0 deployment with error ImportError: No module named XXX...unable to load app 0 (mountpoint='')
My deploy enviroment is "Django 1.11.13 + Python3.6.5(with virtualenv) + uWSGI 2.0 + Nginx 1.12". Here is my project: (ncms) [ncms@localhost ncms]$ pwd /home/ncms/ncms (ncms) [ncms@localhost ncms]$ ll 总用量 36 drwxrwxr-x 12 ncms ncms 157 5月 17 13:48 apps -rwxrwxr-x 1 ncms ncms 16384 5月 14 18:49 celerybeat-schedule drwxrwxr-x 2 ncms ncms 66 5月 17 10:40 db_tools drwxrwxr-x 4 ncms ncms 41 5月 17 10:40 extra_apps drwxrwxr-x 5 ncms ncms 233 5月 17 10:40 libs drwxrwxr-x 2 ncms ncms 152 5月 17 10:40 logfiles -rwxrwxr-x 1 ncms ncms 855 5月 6 22:23 manage.py drwxrwxr-x 3 ncms ncms 201 5月 21 14:19 ncms -rwxrwxr-x 1 ncms ncms 351 5月 15 18:25 ncms.conf -rwxrwxr-x 1 ncms ncms 2766 5月 17 13:43 notes.md -rwxrwxr-x 1 ncms ncms 518 5月 14 15:52 requirements.txt drwxrwxr-x 3 ncms ncms 23 5月 18 16:09 static drwxrwxr-x 10 ncms ncms 120 5月 18 16:05 static_files drwxrwxr-x 11 ncms ncms 4096 5月 17 15:38 templates my virtualenv path and name: (ncms) [ncms@localhost ncms]$ pwd /home/ncms/.virtualenvs/ncms (ncms) [ncms@localhost ncms]$ ll 总用量 8 drwxrwxr-x 3 ncms ncms 4096 5月 21 13:46 bin drwxrwxr-x 2 ncms ncms 24 5月 15 11:49 include drwxrwxr-x 3 ncms ncms 23 5月 15 11:49 lib -rw-rw-r-- … -
Convert date object in normal format
When I am using python object then getting 2018-05-18 08:38:58+00:00 this . this is wrong as per data We need to convert this data format in python split + from 2018-05-18 08:38:58 How to convert this in python/Django -
Context Processors are not working with Jinja2 in Django
Context Processors are not working with Jinja2(Ver 2.10) in Django(Ver 2.0.5). This is what i have done. Created a context processor as follows: def test_con_proc(request): return { 'test_con_proc': "Testing Context Processors", } And, called it in my template using this: {{ test_con_proc }} Also, added this to settings.py file like this: 'dashboard.context_processors.test_con_proc', So, What't the proper solution for resolving using context processors with Jinja2 in Django? -
DRF ModelSerializer CharField with a source does not appear in validated_data
I have a model like this: class AppUser(models.Model): user = models.OneToOneField(User, related_name='app_user') And I have a serializer for this class: class AppUserSerializer(serializers.ModelSerializer): first_name = serializers.CharField(source='user.first_name') class Meta: model = AppUser fields = ('first_name',) def create(self, validated_data): first_name = validated_data.pop('first_name') user = User.objects.create_user(username='test', first_name=first_name, last_name='test') app_user = AppUser.objects.create(**validated_data, user=user) return app_user But when I try to create a user with this serializer, although I send a parameter called first_name I get this error: KeyError: 'first_name' And when I run the program in debug mode I can see that validated_data is empty! Another point is that when I add write_only to the field it appears in validated_data, but I don't want the field to be write_only! It seems that something is making this field read_only, How can I change that? -
Django log info as well as error logs on production
I am trying to log INFO as well as ERROR log on production. But I am not sure how to mention both log levels for the same project. LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['console', ], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'sns': { 'level': 'ERROR', 'class': 'project.abc.snshandler.SNSHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console', ], 'propagate': False, }, 'django.security.DisallowedHost': { 'level': 'ERROR', 'handlers': ['console', ], 'propagate': False, }, 'project': { 'level': 'ERROR', 'handlers': ['console', 'sns'], 'propagate': False, }, }, } At project level i want to log INFO logs as well.