Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error| E0602 local variable 'send_mail' (defined in enclosing scope on line 17) referenced before assignment [pyflakes]
I am trying to send a fax, and the way to do that is to send a mail with the function send_mail @staff_member_required @require_http_methods(['POST']) def fax_contract(request, pk=None): if request.is_ajax() and pk: print("Sending contract for request {}".format(pk)) try: contract = Contract.objects.get(pk=pk) except Contract.DoesNotExist: return HttpResponseNotFound(_('Contract not found')) now = datetime.datetime.now() last_faxed = contract.request.last_faxed_at if last_faxed and (now - last_faxed) < settings.LOANWOLF_FAX_GRACE_TIME: return JsonResponse({ 'error': True, 'reload': False, 'message': _('Please wait at least %(minutes)d minutes to resend the contracts') % { 'minutes': settings.LOANWOLF_FAX_GRACE_TIME.seconds // 60}, }) else: contract.request.last_faxed_at = datetime.datetime.now() contract.request.save() subject, msg = ('', '') try: send_mail = send_mail(subject, msg, settings.LOANWOLF_FAX_EMAIL_FROM, settings.LOANWOLF_FAX_EMAIL_TO.format(contract.request.customerprofile.fax), fail_silently=False) return send_mail, JsonResponse({'success': True, 'reload': True}) except Exception as e: return JsonResponse({'error': True, 'message': str(e)}) Here is the html code where I where the previous method : <div class="alert top white-text {{ object.state|request_state_color }}"> <i class="material-icons">info</i> <a href="{% url "contracts:fax" pk=object.contract.pk %}" class="btn pull-right {{ object.state|request_state_color }} darken-2 btn-process-request" data-turbolinks="false">{%trans "Fax contract" %}</a> {% if object.contract.pk %} <a href="{% url "contracts:as-pdf" pk=object.contract.pk %}" class="btn pull-right {{ object.state|request_state_color }} darken-2 workflow-bar-btn-spacer" data-turbolinks="false">{%trans "View contract" %}</a> {% endif %} <strong>{% trans "Once the signature is added to the request documents and approved, the deposit will be scheduled." %}</strong> </div> Here … -
How to create nested form in django?
In a django project, I have a book form class and an author form class. from django import forms class BookForm(forms.Form): name = forms.CharField(max_length=100) isbn_no = forms.IntegerField(max_value=9999999999999) publish_date = forms.DateField() class AuthorForm(forms.Form): name = forms.CharField(max_length=100) birth_date = forms.DateField() As a writer may have more than one book, I want to create an array of BookForm and add it to AuthorForm as BookList. How can I do that? NB: These forms are not model form. -
Telegram image scraper
Hi, I have trouble with Telegram images scraper (I don't know how to call it). It's a feature that puts an image in chat via URL. (Screenshot below). But when I am trying to serv static files by Django or Flask Telegram really can't scrap that image. (Screenshot below) Also, I've tried NGINX server but seems similar. Did anybody know how that feature works or somebody tried to do that on their own? Maby I should register the domain? http://95.213.204.252/static/img_server/img/test.jpg -
Group level permissions in django
I have a list of custom permissions in the Permission model, a User model and a Group model. I have different set of permissions(from the Permission model) defined for each group. Each user belongs to a particular group. I want to include a permission check in my website such that whenever a user logs in and tries to go to a view, the back-end checks if the user has the permission to enter the particular view. How to implement this in my website? Note: I am not using django REST framework. -
override template_name in listview subclass
I have a BookListView which displays all the books in my library. I have also a subclass of BookListView called BookSearchListView. I am trying to override the template by using the template_name variable. But this produces no effect. views.py class BookListView(generic.ListView): model=Book paginate_by=15 class BookSearchListView(BookListView): paginate_by=10 template_name='booksearch_list.html' def get_queryset(self): pass urls.py url(r'^ksiazki/', views.BookListView.as_view(), name='books'), url(r'^szukaj/', views.BookSearchListView.as_view(), name='search-list-view'), I tried to override the template_name in views and in urls but in both cases it keeps book_list.html which is default template for BookListViews and not booksearch_list.html. -
How to make the chart display current year with month in Highchart x-Axis?
Chart looks like this: In the x-axis where the months are I also wanted it to show current year. Tried different variations with no luck so hopefully you can see where i went wrong. Really appreciate your help! Django version: 1.10 Python version: 3.6 chartViewHigh.html {% block main %} <h1 align="center">Analysis</h1> {% block content %} <div id="container3" style="width:50%; height:400px;"></div> {% endblock %} {% block extrajs %} <script> var endpoint = '/api/chart/data/'; var labels01 = []; var defaultData01 = []; var labels02 = []; var defaultData02 = []; var labels03 = []; var defaultData03 = []; ... $.ajax({ method: "GET", url: endpoint, success: function (data) { labels01 = data.labels01; defaultData01 = data.default01; labels02 = data.labels02; defaultData02 = data.default02; labels03 = data.labels03; defaultData03 = data.default03; labels04 = data.labels04; ... setChart() }, error: function (error_data) { console.log("error"); console.log(error_data) } }); $(function () { $('#container3').highcharts({ chart: { type: 'column' }, title: { text: 'Total Monthly Registration' }, xAxis: { categories: [ 'Group' ] }, yAxis: { tickInterval: 1, minRange: 1, title: { text: 'Data' } }, tooltip: { useHTML: true }, plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }, series: [{ name: labels01 , data: defaultData01 },{ name: labels02, data: defaultData02 },{ … -
IOError: [Errno 2] when I want to create a file
I'm working on my django app, and I have problem with one line of my code: open(os.path.join(settings.BASE_DIR, 'templates', 'generated', 'calendar', month.strftime('%Y-%m.html')), 'w').write(html) Should works fine, because when I printed this line of code I got full path to file. No I got an error: IOError: [Errno 2] No such file or directory -
How to keep python server running
I need a bit of help here. I am new to python and django. For my project i am developing an system which deals with api fetching and insertions. I need this system to be online 24 * 7. so i need to the server to be running all the time. Using the traditional method of: python manage.py runserver runs perfectly. I even tried : nohup python manage.py & but when i access my project with the url. Its showing that it project is not online. How do i fix this? -
Django template renders {% trans %} strings in strange order
I'm working on supporting Arabic in a Django web database, and I'm encountering some very strange rendering behavior. Specifically I'm trying to reorder the words on the page from right to left, all of them being individually gathered strings in the template (either from a context variable or a trans tag). Hopefully these images will illustrate the problem clearly. English is the project default. Django version is 1.6. In English, everything is fine yields However in Arabic, the same markup results in this, with the cultural period block rendered at the end. But if I take that first trans tag out and replace it with a string like this the order is correct Now here's where it gets very strange. If I add some characters after the first trans tag (cp in this case), it renders correctly yields But if I add a character before the trans tag (a colon in this case), it gets split up in a very bizarre way yields I'm really hoping that there are some underlying rules that Django uses while translating that can explain this. I'm really hoping that it's not (as I'm theorizing) caused by a tiny lag in the time that translation … -
Django: Create and save a model using JSON data
Im building an app using Django 1.10 as backend and Angular 2 4.0 for frontend. Is it possible to create and save a model instance from a JSON data object? Example: This model: class PartOne(models.Model): gender = models.SmallIntegerField(choices=[(1, "Male"), (2, "Female")]) gender_na = models.BooleanField(default=False) height = models.SmallIntegerField() height_na = models.BooleanField(default=False) JSON: json = { 'gender': 1, 'gender_na':False, 'height':195, 'height_na':False } I dont want to manually create the model: PartOne.objects.create(gender=json['gender'], gender_na=json['gender_na'], height=json['height'], height_na=json['height_na] Im looking for an automated solution, like this: PartOne.objects.create_from_json(json) -
validators = [MinValueValidator] does not work in Django
I want to set the minimum value for FloatField in Django so that the form field does not accept negative value. In case of Integers I changed the datatype to PositiveIntegerField but minimum value is not working in case of float field. from django.core.validators import MaxValueValidator, MinValueValidator max_discount = models.FloatField( verbose_name=u'Maximum Discount', validators = [MinValueValidator(0.0)]) -
DRF Serializer - OrderDict instead of JSON
I am new to Django1.9, models.py:- class MyUser(models.Model): UserId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) UserFirstName = models.CharField(max_length=1000) UserLastName = models.CharField(max_length=1000) UserEmail = models.EmailField(max_length=1000,blank=False,null=True) UserContactNumber = models.CharField(max_length=1000) UserPassword = models.CharField(max_length=1000) IsActive = models.BooleanField(default=False) Role = ArrayField(models.CharField(max_length=1000), blank=True,null=True) class Meta: ordering =('IsActive',) serializers.py:- class MyUserSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = '__all__' Shell output :- >>> from projectmanagement.serializers import MyUserSerializer >>> users = MyUser.objects.all() >>> users [<MyUser: MyUser object>, <MyUser: MyUser object>] >>> serializer = MyUserSerializer(users,many=True) >>> serializer MyUserSerializer([<MyUser: MyUser object>, <MyUser: MyUser object>], many=True): UserId = UUIDField(label='UserId', read_only=True) UserFirstName = CharField(label='UserFirstName', max_length=1000) UserLastName = CharField(label='UserLastName', max_length=1000) UserEmail = EmailField(allow_null=True, label='UserEmail', max_length=1000, required=False) UserContactNumber = CharField(label='UserContactNumber', max_length=1000) UserPassword = CharField(label='UserPassword', max_length=1000) IsActive = BooleanField(label='IsActive', required=False) Role = ListField(allow_null=True, child=CharField(label='Role', max_length=1000), required=False) >>> serializer.data [OrderedDict([('UserId', 'fd5df8d3-a578-4fe7-95ea-172ad2399ff8'), ('UserFirstName', u''), ('UserLastName', u''), ('UserEmail', None), ('UserContactNumber', u''), ('UserPassword', u''), ('IsActive', False), ('Role', None)]), OrderedDict([('UserId', '8301e1b6-a031-443f-957a-df98025e5e9f'), ('UserFirstName', u'Piyush'), ('UserLastName', u'Wanare'), ('UserEmail', u'piyush@uniserved.com'), ('UserContactNumber', u'992053268236'), ('UserPassword', u'Piyush@1234'), ('IsActive', True), ('Role', [u'Vendor Cordinator'])])] Why I am not getting JSON data instead of OrderedDict? How can I get data in JSON format? -
Django Create Account ends in 550
on a Django application (geonode 2.4) I´m trying to register a new user: me@gmail.com. This ends in ERROR SMTPRecipientsRefused sombody@yahoo.com (550, unknown User). The same Setup works on a local vm (with same SMTP server)! SETUP Ubuntu 14.04 Django 1.6.11 Accounts App: geonode-user-accounts (Forked from pinax-django-user-accounts) SMTP local_settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_USE_SSL = True EMAIL_HOST = 'mail.example.com' EMAIL_HOST_USER = 'user@mail.example.com' EMAIL_HOST_PASSWORD = 'pass' EMAIL_PORT = 25 ## tested telnet to 587 but it seems only 25 is open DEFAULT_FROM_EMAIL = EMAIL_HOST_USER THEME_ACCOUNT_CONTACT_EMAIL = 'admin@example.com' QUESTION What I do not understand why does Django complain about sombody@yahoo.com when I try to register me@gmail.com? – It should not care about already registered users. How can I debug this? -
Django / Python - Date joined check [duplicate]
This question already has an answer here: Can't subtract offset-naive and offset-aware datetimes 9 answers I have the following code: currentUser = request.user date_joined = currentUser.date_joined if date_joined < datetime.datetime.now()-datetime.timedelta(seconds=20): DO SOME STUFF However, I get the following error: "can't compare offset-naive and offset-aware datetimes" I do have "USE_TZ = True" in my settings. Is there a quick dirty why of tweaking my if statement to check if the date someone joined is less than 20 seconds? -
Did anyone integrated Sage One with django framework?
I wanted to integrate Sage One with my django application. But, from https://developers.sageone.com/ I got to know that it supports only C#, Java, PHP and Ruby. Did anyone integrated "Sage One" with django framework? Any suggestions? -
Uploading pdf file from Django Admin so that Public users can download from frontend
I am trying to upload a pdf file from django Admin side so that users can download it from frontend after registering on website is there any way to do that or any third party package for this task. note: I am new to django -
How do you get daterangepicker input passed into django form?
I am almost completely new to Django and web development so please help me out. I pretty much just want to create a form on Django that takes in two dates(a start and end date) and a text input. I have tried everything to get daterangepicker into my program but I either get the daterangepicker to show up but unable to pass the html input back into the form or I can't get the daterangepicker to show up. Basically, I just want to allow the users to pick the two dates using a calendar instead so I guess I don't need to implement daterangepicker if it is not necessary. Here is what I have so far: views.py from .forms import HyugaRequestForm def create_req(request): name = request.user.username form = HyugaRequestForm(request.POST or None) if form.is_valid(): instance = form.save(commit = False) instance.name = name instance.s_date = form.cleaned_data.get('Start_Date') instance.e_date = form.cleaned_data.get('End_Date') instance.save() context = {'form':form,} return render(request,'timeline/hyuga_requests_form.html', context) forms.py from django import forms from .models import Hyuga_Requests from django.forms import ModelForm from django.forms.extras import SelectDateWidget class HyugaRequestForm(forms.ModelForm): Start_Date = forms.DateField(widget=SelectDateWidget) End_Date = forms.DateField(widget=SelectDateWidget) class Meta: model = Hyuga_Requests fields = ['reason'] models.py from __future__ import unicode_literals from django.db import models class Hyuga_Requests(models.Model): name = … -
How to set django current_timezone as system time zone
I have template which displays the time sent from the view. views.py contains following code from datetime import datetime from django.utils import timezone def func(request): now=datetime.utcnow() timezone.activate('Asia/Kolkata') return render(request,'time.html',{'time':now}) This will display the time in time zone 'Asia/Kolkata'. Now the time zone is set by me. I want to set the current timezone to my laptop's timezone. That is i want the timezone to change with my laptop's timezone. I have tried to read system timezone but all method give the django's current timezone set by activate ( Here 'Asia/Kolkata' ). Will you please help me? -
Make runserver python to use multiple cores & know when code changes
I am using python manage.py runserver to run my django app. But I figured out that it, by default uses just one system core. In Gunicorn/Uwsgi I usually specify workers and threads but they take time to restart as workers are first killed and new ones are spawned after that. How can I do that directly in runserver? Assume I have to use runserver for my staging environment, I want it to use more resources and handle load. Or is there any other way to restart/reload the code without downtime? Or a way I can run Django via Gunicorn or UWSGI and make the restarts happen really quickly. If I change my code, while runserver is running, will it automatically know the code has changed? -
How can I handle the exception in Django 1.8.7
When I run the development server in Django, exception occurs as follows. ?: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. Here is my settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] On the browser, there is an error message as follows. ImproperlyConfigured at / app_dirs must not be set when loaders is defined. Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.8.7 Exception Type: ImproperlyConfigured Exception Value: app_dirs must not be set when loaders is defined. Exception Location: /usr/lib/python2.7/dist-packages/django/template/engine.py in init, line 36 Would you tell me the reason why this exception has occurred and how can I handle it? -
Load JavaScript module for single page
I'm using Webpack with my Django project, i have entry file inside assets/js/index.js which requires all the other app js files. all gets bundles and included in base.html. in notes app i have a file/module that crashes if loaded in different page, because some element selection fails. how do i load that module only on specific page. index.js: require('./set-up-jquery'); require('../../notes/static/js/note.js'); notes.js: var note = document.querySelector('.note'); // fails! note not found on page -
How to get element | value from list object in django (jinja) in the html? I know how get first value, but how about second, third
I'm a new in the world of django! Please help me! I can get all values in the list, but I need exactly, for example third value or element in the list? How to filter it? -
django-python3-ldap authentication Issue on Admin Page
I am trying to get ldap authentication to work on the Django Admin Page. I am using the below configuration AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', ) # The URL of the LDAP server. LDAP_AUTH_URL = "ldap://dc.prod.company.com" LDAP_AUTH_CONNECTION_USERNAME = "username@americas.corp.local" LDAP_AUTH_CONNECTION_PASSWORD = "Password1" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "AMERICAS" LDAP_AUTH_SEARCH_BASE = "ou=unix,ou=accounts,ou=inetgpo,dc=americas,dc=corp,dc=local" LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "DEBUG", }, }, } But I keep getting the same error, even after running: ./manage.py ldap_promote username Error: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. I know that the authentication is working because when i put in an incorrect username/password I get the following: [17/May/2017 08:23:10] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1650 LDAP connect failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - 80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece - bindResponse - None [17/May/2017 08:23:20] "POST /admin/login/?next=/admin/ HTTP/1.1" 200 1812 When the correct username & password is entered I just get: [17/May/2017 08:24:34] "POST /admin/login/?next=/admin/ HTTP/1.1" 200 1812 But still this error on the front end: Please enter the correct username and password for a … -
Load CSV values then search for matches in mysql database and then apply insertion?
I am using python Django and I have a CSV file which contains 4 fields name, abbreviation, address and type of school. I have 3 database table named university, type of university and university-type mapping.I am having a csv list which has name of university I want to compare it with university table present in database and want to find out id corresponding to that name and same process with type of university and find out its id.And then i want to insert those values into university-type mapping. I am able to read data from CVS using this method but stuck on database search for match: here is what i am using to read the search: import csv path = '/home/abi/Downloads' file=open( path +"university.CSV", "r") reader = csv.reader(file) for line in reader: t=line[1],line[2] print(t) -
My modelformset_factory is not saving the images in the Class based views, but it can be saved on the Admin side
I have a challenge of not saving the image when creating a new product. The form is rendered well and the image is uploaded but never saved until I use the Admin to upload and save it, thats when it becomes visible on my created product. I think I'm missing something in my class ProductCreateView() in the views.py, especially in the def post() . Help me to figure it out. models.py class ProductImages(models.Model): product = models.ForeignKey(Product) title = models.CharField(max_length=120) media = models.ImageField(upload_to=product_download, width_field='max_width', height_field='max_height', null=True, blank=True) max_width = models.CharField(max_length=100, null=True, blank=True) max_height = models.CharField(max_length=100, null=True, blank=True) featured_image = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return unicode(self.media) views.py` the form is saving its information well, but formset is not saving the images from .forms import ProductModelForm, ProductImagesForm, ImagesFormset class ProductCreateView(CreateView): def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form, formset=formset)) def form_valid(self, form, formset): return HttpResponseRedirect(self.get_success_url()) def get(self, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = ImagesFormset(queryset=ProductImages.objects.none()) return self.render_to_response(self.get_context_data(form=form, formset=formset)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = ImagesFormset(self.request.POST, self.request.FILES) form_valid = form.is_valid() formset_valid = formset.is_valid() if form_valid and formset_valid: user = self.request.user form.instance.user = user …