Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
hello, i hv small questions of my searching in django
i am making a function of search something from my database. i am not sure about the way of returning results. my view is rendering, i can see "entered" on my cmd this is my form class SearchForm(forms.ModelForm): class Meta: model = MyUser fields = ('Mother_language','Nationality') this is my view def index(request): print "entered" form = SearchForm(request.POST or None) if request.method == "POST" and form.is_valid(): Mother_language = form.cleaned_data['Mother_language'] Nationality = form.cleaned_data['Nationality'] return HttpResponseRedirect('/thanks/') return render_to_response("LanguageExchange/index.html", { "form": form, }) this is my index.html <form id="form" method="get" action="{% url 'index' %}"enctype="multipart/form-data"> {% csrf_token %} {{form.as_table}} <input type="submit" value="submit" /> <br> -
while web frameworks implemented security measures, is it necessary to install WAF on webserver?
while modern web frameworks such as Yii (PHP), Laravel (PHP), Django (python) and etc have implemented security measures against attacks on web application such as XSS, SQL injection, RFI and etc, is it necessary to install a WAF on webserver? i deployed a project with django and nginx, i want to know is that necessary or not? -
django-dynamic-formset js plugin does not read parameters from forms.py
im using the plugin django-dynamic-formset and works perfectly. But now I realize that does not read the parameters from inlineformset_factory for example, I set up max_num=5 but the plugin keep adding more than 5 fields, same happens with min_num. Any idea of how to fix it or i'm wrong? Thanks -
Keeping passwords out of code but with gunicorn self-restartable?
I am currently writing my fabric deploy script for my gunicorn/django app which is managed by supervisord. I have certain passwords that are required to be in the environment of the app when gunicorn runs. It seems the standard way of doing things is to add environment variables to the [program:app] of /etc/supervisord/app.conf, but this means I will have plaintext passwords in my repo unless I kept the app.conf outside of the repo (which doesn't seem clean). I can't hash the passwords because they are used by the app to access third party services. Also even if I kept app.conf outside of the repo, I still have plaintext passwords in app.conf which doesn't seem ideal. Is there some way to let supervisord do its thing (restarting gunicorn on its own) without storing plaintext passwords? -
Getting foreign key error on deletion
I have the following models in django: class ItemInstance(models.Model): item_type = models.ForeignKey('ItemContentType', related_name='item_type') name = models.CharField(max_length=256) class TerritoryPricing(models.Model): item = models.ForeignKey(ItemInstance, null=True) territory = models.CharField(max_length=256) However, when I delete an ItemInstance, I always get an IntegrityError. Here is an example error: >>> ItemInstance.objects.filter(pk=123).delete() IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (avails.main_territorypricing, CONSTRAINT main_territorypricing_ibfk_1 FOREIGN KEY (item_id) REFERENCES main_iteminstance (id))') This just started happening recently, so perhaps there is some cached information in my django app or django db. How can I go about fixing this? For now, what I have to do (which is quite annoying) is: >>> TerritoryPricing.objects.filter(item__pk=123) >>> ItemInstance.objects.filter(pk=123) -
Django query returning no results
I'm working on a Django proyect and at some point I need to execute a query to return results from the DB. Then I have to apply a filter to get the relevant results (IE: Only the results linked to a given Category) if category: articles = articles.filter(categories__category__name=category) When there are matches it works fine, it will just return the results and I display them. But when the filter doesn't match any category of the articles, and I expect it just to return an empty collection (so then I can just show a message like "No results to match") I get this issue: It seems to me that Python (or Django) doesn't like when there are no results, or it has problems returning just an empty array. I want it to just return an empty object/array/collection or just None/Null when the filter doesn't match any element. -
oAuth2Client Forgets I'm logged in
I'm trying to write a small service to query Google Analytics data from Slack. I use oAuth2client to login, exchange the code for a token and everything works perfectly. Then I added the Slack Button to get the slack code, I get redirected to my app where I use: def connect_slack(request): if request.method == 'GET': if 'code' in request.GET: auth_code = request.GET['code'] else: return HttpResponse('Sorry, code not in request!') # Exchange code for token sc = SlackClient("") auth_response = sc.api_call("oauth.access", client_id = '1566197632728390', client_secret ='9ff6154627382233ffd9c05c6d', code=auth_code, ) slack_credentials = auth_response To again exchange the Slack code for the token, also this works fine. The problem is that at this point Django somehow forgot who the user was, and can not save the token or anything for the current user as it's anonymous. In other words: Access app --> Anonymous user Login with GA --> Redirect to Google Analytics redirect back to my app Success Page ---> User is signed in and I can access his data Connect Slack ---> User is still signed in, here he clicks on the slack button Slack oAuth Page ---> Slack asks the user to grant permissions Exchange Slack Code Page ---> Django has no … -
'int' object has no attribute 'encode' in django-excel
I'm using django-excel to setup an export tool to excel but I'm having trouble with Attribute error 'int' object has no attribute 'encode' My form for converting to excel, can someone explain me why am I getting this error, here is a link for the complete traceback. from django.http import HttpResponseBadRequest from django.http import HttpResponseForbidden from django.views.generic import FormView from django import forms import django_excel as excel class UploadFileForm(forms.Form): file = forms.FileField() ignore_first_columns = forms.IntegerField() class ExportMailXls(FormView): template_name = 'vinclucms_sales/export_email/export_sales_email_xls.html' form_class = UploadFileForm def get(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if request.user.is_staff: return self.render_to_response( self.get_context_data(form=form, can_submit=True,)) else: return HttpResponseForbidden() def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if request.user.is_staff: if form.is_valid(): column_ignore_index = form.cleaned_data['ignore_first_columns'] if not column_ignore_index: column_ignore_index = 0 filehandle = request.FILES['file'] xls_book = filehandle.get_book() for sheet in xls_book: for k1, v1 in enumerate(sheet.rows()): if k1 > 0: for k2, v2 in enumerate(v1): if k2 >= column_ignore_index: uni_str_escaped = v2.encode("unicode-escape") \ .replace('\\x','\\u00') \ .replace('\\\\u','\\u') sheet[k1, k2] = uni_str_escaped return excel.make_response(xls_book, "xls", file_name="converted") else: return HttpResponseBadRequest() else: return HttpResponseForbidden() the traceback: Traceback: File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 22. return view_func(request, *args, **kwargs) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/views/generic/base.py" … -
Overriding the Clean method in my Django ModelForm
The system I am currently working on needs users to enter two emergency contact numbers on registration. I want to implement a check that will ensure that the user is entering a valid number, I've determined this to be a string that begins with either a 0 or a +. To do this, I've tried to override the clean method in the form but it isn't quite working. This is my forms.py code for the relevant method: class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('emergcon1', 'emergcon2') labels = { 'emergcon1': ('Emergency Contact Number'), 'emergcon2': ('Emergency Contact Number 2') } def clean(self): if emergcon1[:1] != '0' or '+': raise ValidationError( _('%(emergcon1)s is not a valid phone number'), params={'emergcon1': emergcon1}, ) if emergcon2[:1] != '0' or '+': raise ValidationError( _('%(emergcon2)s is not a valid phone number'), params={'emergcon2': emergcon2}, ) It doesn't produce any errors, it just doesn't seem to use the method, I can still enter an invalid number. Any ideas on how to make it work? If you need to see any other code let me know. -
Sorl-thumbnail bugs 502 with large image
There is an error 502 Bad Gateway when I try to show in template large image (more that 2000x2000px) with Sorl-Thumbnail. No mistake if load page without thumbnail just picture and if less then 20000x2000px Already tried to change nginx config like this...: server { proxy_connect_timeout 1500; proxy_send_timeout 1500; proxy_read_timeout 1500; send_timeout 1500; location / { fastcgi_read_timeout 1500; } } Use regular code in template like {% thumbnail ph.image "500x500" crop="center" format="PNG" as im %} <img src="{{ im.url }}"/> {% endthumbnail %} Any advise pls? Just for google search Django Python Sorl-Thumbnail Thumbnail 502 Bad Gateway large image -
Apache2 host, url not served with mod_wsgi
Just stated to host a website with Django, the problem is like this. I put an html file for testing under /usr/local/django/virenv/Personal/mysite.com/, which is also the Document root in 000-default.conf, that page can be access via mysite.com Then I started a django project and an app, in the app/view.py I put from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, a django view.") In the app/urls.py I put from django.conf.urls import url from . import views urlpatterns = [ url(r'^index$', views.index, name = 'index'), ] added the following to project/urls.py urlpattrens = [ url(r'^home/', include('app.urls')), # below is admin url created with startproject url(r'^admin/', admin.site.urls)), ] lastly I turn DEBUT=False in project/settings.py, and added ip to ALLOWED_HOSTS After python manage.py runserver ip:8080 , ip:8080/home/index, and ip:8080/admin are all available. Next I tried restart apache2, went to mysite.com/admin and mysite.com/home/index both got 404 Not Found The requested URL /admin was not found on this server. I guess the mod_wsgi is not working. The httpd.conf looks like LoadModule wsgi_module modules/mod_wsgi.so WSGIScriptAlias / /usr/local/django/virenv/Personal/mysite.com/project/wsgi.py process-group=mysite.com WSGIPythonHome /usr/local/django/virenv WSGIDaemonProcess mysite.com python-home=/usr/local/django/virenv python-path=/usr/local/django/virenv/Personal/mysite.com WSGIProcessGroup mysite.com WSGIApplicationGroup %{GLOBAL} <Directory /usr/local/django/virenv/Personal/mysite.com/project> <Files wsgi.py> Order allow,deny Allow from all Require all granted </Files> </Directory> <Directory … -
maximum recursion depth exceeded - Django
This is the error I am getting while creating an object in django. I know there is a mistake in defining the unicode for that particular model. But, I don't know how to define one for ManyToManyField in django. Here are the revelant screenshots ' -
The model of google forms like web application in django
I try to create a clone of google forms in django, but I cannot see how to implement Models in django because a form can have many fields of arbitrary types. Where the models of forms could be? -
Is it possible to get realtime updation of web app deployed on pythonanywhere
Is there a way so that I edit my code on local machine and push it onto GitHub and simultaneously my python anywhere web application gets updated. I am having a free account on pythonanywhere so this way is not possible (Blog) -
Django - render to string fails to load CSS
I am trying to use Django render_to_string to convert html to pdf with management command instead of using View/request. The following code is able to convert the template to pdf. But it fails to load CSS into the template. def html_to_pdf(): ... context = {'some_key': 'some_value'} html = render_to_string('my_app/sample.html', context) file.write(html) ... sample.html {% load static %} <link href="{% static 'my_app/css/sample.css' %}" rel="stylesheet" type="text/css"/> Also I have static defined in the setting file. In my Django project, there is another View function which is able to load the template with CSS when the url get called. So I believe the issue has something to do with render_to_string. Anyone can help it out? -
Atomic transactions in Django
In a Django web app I maintain, I have a Redis powered sorted set that contains all registered usernames. Moreover, I also save said usernames in a postgresql DB (as backup). Specifically, when a user registers, I save their username both in the DB and in Redis, like so: def save(self, commit=True): user = super(CreateAccountForm, self).save(commit=False) password = self.cleaned_data["password"] user.set_password(password) if commit: user.save() #saving in Postgresql DB insert_username(self.cleaned_data.get("username")) #inserting into Redis return user The lines after if commit: are where the action takes place. How do I ensure saving in DB and Redis happens atomically, so that in cases where it fails, I'm not left with data integrity issues? An illustrative example would be great. -
How to fill through model instances using forms or formsets
I have the following models : class criterion(models.Model): quantity = '0' quality = '1' ascending = '0' descending = '1' three = '3' five = '5' seven = '7' ten = '10' type_choices = ( (quantity,'Ποσοτικό'), (quality,'Ποιοτικό'), ) monotonicity_choices = ( (ascending,'Αύξον'), (descending,'Φθίνον'), ) a_choices = ( (three,'Τριβάθμια'), (five,'Πενταβάθμια'), (seven,'Εφταβάθμια'), (ten,'Δεκαβάθμια'), ) criterion_research = models.ForeignKey('research', on_delete=models.CASCADE,null=True) criterion_name = models.CharField(max_length = 200,verbose_name='Όνομα Κριτηρίου') criterion_type = models.CharField(max_length = 15,choices = type_choices , default = quantity,verbose_name='Τύπος') criterion_monotonicity = models.CharField(max_length = 15,choices = monotonicity_choices , default = ascending,verbose_name='Μονοτονία') criterion_a = models.CharField(max_length = 30,choices = a_choices , default = five,verbose_name='Κλίμακα',help_text='Επιλέξτε μία από τις 4 κλίμακες που θα μετρηθεί το κριτήριο.') criterion_worst = models.FloatField(default=' ',verbose_name='Χειρότερη Τιμή',help_text='Επιλέξτε τη χειρότερη τιμή την οποία μπορεί να πάρει το κριτήριο.',blank=True) criterion_best = models.FloatField(default=' ',verbose_name='Καλύτερη Τιμή',help_text='Επιλέξτε τη καλύτερη τιμή την οποία μπορεί να πάρει το κριτήριο.',blank=True) def __str__(self): return self.criterion_name class alternative(models.Model): name = models.CharField(max_length = 200,verbose_name='Όνομα Εναλλακτικής') ranking = models.IntegerField(default='1') alternative_research = models.ForeignKey('research', on_delete=models.CASCADE) criteria = models.ManyToManyField('criterion', through='criterionvalue',blank=True) def __str__(self): return self.name class criterionvalue(models.Model): value = models.IntegerField(default='0') alt = models.ForeignKey('alternative',on_delete=models.CASCADE) crit = models.ForeignKey('criterion',on_delete=models.CASCADE) I have made a view that populates the criterion instances and the alternative instances(except the manytomany field). I want to query for all the possibles criterion and … -
Kombu causing varied Django ImportErrors when running PyCharm debugger
When I attempt to Run or Debug my code in PyCharm, I get ImportErrors. When I run with Kombu 3.0.23, as per our requirements, I get: ImportError: Could not import settings 'appname.settings' (Is it on sys.path?): cannot import name _uuid_generate_random There are SO articles that explain that this bug was fixed Kombu 3.0.30. However, when attempting to Run/Debug with that version, the following ImportError is thrown: ImportError: DLL load failed: The specified module could not be found. SO articles about this error mostly suggest updating the C++ build tools for Python and/or reinstalling Python, which I have done to no avail. The same error occurs for all Kombu versions >= 3.0.30 and < 4.0 When attempting with Kombu 4.0+, the following ImportError is thrown: ImportError: Could not import settings 'appname.settings' (Is it on sys.path?): cannot import name OrderedDict So it seems none of the Kombu packages will not allow me to Run or debug my code. The project is running Python 2.7.12 with these additional requirements: BeautifulSoup==3.2.1 Django==1.5.5 Pillow==2.6.1 PyPDF2==1.23 amqp==1.4.6 azure==0.8.4 beautifulsoup4==4.3.2 celery==3.1.16 decorator==4.0.2 deform==2.0a2 django-admin-sortable==1.8.4 django-celery==3.1.16 django-pyodbc-azure==1.0.13 djangorestframework==3.1.1 google-api-python-client==1.4.1 gspread==0.2.2 html5lib==0.999 httplib2==0.9 ipython==2.4.1 iso8601==0.1.10 kombu==3.0.23 librabbitmq==1.5.2 mechanize==0.2.5 networkx==1.10 oauth2==1.5.211 oauth2client==1.4.11 pbr==0.10.0 peppercorn==0.5 pika==0.9.14 pisa==3.0.33 psycopg2==2.5.4 pyasn1==0.1.7 pyasn1-modules==0.0.5 pyipptool==0.4.9 … -
Find date control in python/django platform
I have an application developed hosted in Digital Ocean. There is an app that makes a search in this platform to check a date, to know if it is valid or not. I want to block some dates. How to find the file that contains this control? -
How can I exorcise ghost Model from project?
I had a Model called Media; it was since renamed to "PetImage" and further revised. Now ack doesn't find the string "Media" in any of my Python source files, .pyc files, my templates, or my SQLite3 database. So far as I can tell from re-examining source (and restarting Gunicorn), the string "Media" shouldn't be anywhere to be found anywhere in my project apart from e.g. stuff under CKeditor's root. I've also made and executed migrations. But I'm still getting http://dpaste.com/0FX74SJ - Django is erroring out on a reported failure to load "Media": Exception Value: 'module' object has no attribute 'Media' What can I do so that Django doesn't expect the 'module' object (my models.py, I think) to provide a Media? The function that appears to be getting the complaint is the fourth line, with the for loop, in: def one_pet(request, pet_id): pet = models.Pet.objects.get(id = pet_id) media = [] for item in models.PetImage.objects.all(): if item.url.startswith('https://youtu.be/'): media.append('') else: media.append('') return render(request, 'one_pet.html', { 'pet': pet, 'site_name': settings.SITE_NAME, }) Is there additional bookkeeping to do if a model is renamed? What should I be doing if I want my now PetImage to be treated as the successor to Media and all further … -
Django- How to use two UserPassesTestMixin
Using Multiple UserPassesTestMixin Works for other views but not for the ProfileCreateView There seems to be a logic error which i am not able to figure out! views.py class CurrentUser(UserPassesTestMixin): def test_func(self): x = self.request.user.slug print (x) y = self.kwargs['slug'] print (y) if x == y: return True else: if self.request.user.is_authenticated(): def get_absolute_url(self): return reverse('profile:view_profile', kwargs={ "slug": self.slug }) class ProfileCreate(CurrentUser, UserPassesTestMixin, LoginRequiredMixin, UpdateView): model = User form_class = ProfileForm template_name="profile/profile_new.html" def test_func(self): x = self.get_object().full_name print (x) y = '' if x == y: return True else: def get_absolute_url(self): return reverse('profile:view_profile', kwargs={ "slug": self.slug }) The class CurrentUser checks if the user has the permission to edit a profile. A user will only be able to edit the profile if he is the author of the profile. Both the x and y is this class prints different values x prints the slug value of the loggedin user whereas y prints the slug from the url how can this be true? The test_func in the ProfileCreate class checks if the user has already created a profile ie., if the full_name is an empty string, then it allows the user to create profile. else redirects to other view. The CurrentUser class … -
PayPal Adaptive Payments vs Braintree Merchants
Which is better considering this situation - using PayPal adaptive payments for parallel payment processing and integration, or using a Braintree merchants account for payment processing and syncing with a 3rd-party for payment integration? Can PayPal adaptive payments do it all? Suppose you have a business called Sewing Bliss & Co. It has two founders. One founder lives in NYC and creates baby clothing, the other founder lives in CA and creates quilts. They both sell their products through their ecommerce web app called www.sewingbliss.co. But, they want their income to be organized into two separate streams - whenever a visitor purchases a baby item it goes into the NYC founder's PayPal account. And whenever a quilt is purchased it goes to the CA founder's PayPal account. If a customer purchases both a baby item and a quilt in one transaction, the transaction goes through and is divided up respectively. To the customer, the transaction appears seamless. I am a web developer (mostly Python/Django). I am curious how this would best be implemented. Any insights? -
Find all the objects that does not have any reverse lookup m2m values
I have a list of contacts and each Contact can belong to many ContactList. What I need to do is find all contacts that does not belong to any ContactList (ie. orphan contacts). class ContactList(models.Model): name = models.CharField() contacts = models.ManyToManyField(Contact) class Contact(models.Model): name = models.CharField() I tried the following but it doesn't work, because contactlist_set is a reverse lookup field and not a model field. Contact.objects.filter(contactlist_set=None) Can some give me some direction to proceed? Thanks -
java.sql.SQLExceptionPyRaisable on the second attempt connecting to Athena using Django
I am using the python module called PyAthenaJDBC in order to query Athena using the provided JDBC driver. Here is the link : https://pypi.python.org/pypi/PyAthenaJDBC/ I highly recommend this module for the python users who want to connect to AWS Athena. Nevertheless, I have been facing some persistent issue. I keep getting this java error whenever I use the Athena connection twice in a row. As a matter of fact, I was able to connect to Athena, show databases, create new tables and even query the content. I am building an application using Django and running its server to use Athena However, I am obliged to re-run the server in order for the Athena connection to work once again, Here is a glimpse of the class I have built import os import configparser import pyathenajdbc #Get aws credentials for the moment aws_config_file = '~/.aws/config' Config = configparser.ConfigParser() Config.read(os.path.expanduser(aws_config_file)) access_key_id = Config['default']['aws_access_key_id'] secret_key_id = Config['default']['aws_secret_access_key'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) athena_jdbc_driver_path = BASE_DIR + "/lib/static/AthenaJDBC.jar" log_path = BASE_DIR + "/lib/static/queries.log" class PyAthenaLoader(): def __init__(self): pyathenajdbc.ATHENA_JAR = athena_jdbc_driver_path def connecti(self): self.conn = pyathenajdbc.connect( s3_staging_dir="s3://aws-athena-query-results--us-west-2", access_key=access_key_id, secret_key=secret_key_id, #profile_name = "default", #credential_file = aws_config_file, region_name="us-west-2", log_path=log_path, driver_path=athena_jdbc_driver_path ) def databases(self): dbs = self.query("show databases;") return dbs def … -
Django ValueError: could not convert string to float
Even though I put this line in my settings.py : DECIMAL_SEPARATOR = ',' As specified here : https://docs.djangoproject.com/en/1.10/ref/settings/#decimal-separator Django still won't recognize the comma as decimal separator Actual error : ValueError: could not convert string to float: '123,123' The field is just a default FloatField, I'm not using forms. What could be causing it to not recognize the comma?