Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SECURE_SSL_REDIRECT in Django forwarding traffic to localhost
I have introduced SSL in my website, and I need make redirection from HTTP to HTTPS. I have website on Django 1.4.5. I have installed djangosecure package using pip and added to settings.py MIDDLEWARE_CLASSES = ( ...., 'djangosecure.middleware.SecurityMiddleware', ) INSTALLED_APPS = ( .... 'djangosecure', ) SECURE_SSL_REDIRECT = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') ALLOWED_HOSTS = ['*'] but now when when I'm trying open website I have redirection to https://127.0.0.1:8756 instead of my domain with https. -
DRF view returns Invalid username/password with @permission_classes((AllowAny, ))
So I have this method-like api view with AllowAny as permisson class decorator: @api_view(['POST']) @permission_classes((AllowAny, )) But when I reach with the browser to the url it renders the DRF api template with a 403 HTTP 403 Forbidden Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Invalid username/password." } What I am missing? I dont need to specify a setting DEFAULT_PERMISSION_CLASSES if I am forcing one through the decorator right? -
Heroku Deployment Issue - Python version
I have been working on a Django project that I am trying to deploy to Heroku. I've followed a tutorial from Python Crash Course. When I enter git push heroku master, I get the following as a response: Counting objects: 73, done. Delta compression using up to 4 threads. Compressing objects: 100% (65/65), done. Writing objects: 100% (73/73), 26.20 KiB | 0 bytes/s, done. Total 73 (delta 8), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.2 (you are using Python-2.7.12, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.2). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing Python-2.7.12 remote: ! Requested runtime (Python-2.7.12) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to fathomless-scrubland-11916. remote: When I Python --version the cmd line returns 2.7.14 which is the most up-to-date version. I feel like this error is telling me I need to use Python3 but their site says that 2.7.14 is … -
Holoview chart won't appear in Django site
i know there is probably something simple i am doing wrong, but i don't know where else to get an answer. I created a django site and the following function returns holoview html: from django.shortcuts import render from django.http import HttpResponseRedirect from charts.models import Ord from IPython.display import display_html import pandas as pd import holoviews as hv hv.extension('bokeh') renderer = hv.renderer('bokeh') # Create your views here. def displayChart(request): df = pd.DataFrame(list(Ord.objects.using('DB').all().values('ordtyp')[:500])) df = df.groupby([df.ordtyp]).size().reset_index(name='counts') bars = hv.Bars(df, kdims=[('ordtyp', 'Order Type')], vdims=[('counts', 'Count of Orders')]) hv.Store.registry['bokeh'][hv.Bars] html = renderer.html(bars) return render(request, 'charts/charts.html', {'html': html}) i put a block in the charts.html file as: {{ html |safe }} and all i get is a blank page. i then took the raw html that the renderer is returning and tried to copy and paste it directly into my html file, and got the same thing. the html is below. Also, the chart does work in Jupyter Notebook... can you tell me what i am doing wrong? charts.html: > <!DOCTYPE html> > <html> > <head> > <title>Charts</title> > </head> > <body> > {{html|safe}} > </body> > </html> raw html that the renderer returned: <div style='display: table; margin: 0 auto;'> <div class="bk-root"> <div class="bk-plotdiv" id="0dd69ef6-4d30-48f5-a95a-1201437920de"></div> … -
Load Content automatically in Django app
I'm working on a Django (1.10 & Python3) project in which I need to implement a logic as: We have articles from various categories, the user needs to tag these articles, mean when user read articles then he needs to provide his feedback rather it's relevant or irrelevant to his situation. We have to provide user's a list of categories when user select a category then all of the articles from that particular category will be available one by one to the user, mean it will show the first article to the user, when he tagged this article it will load next article automatically and also keep the user's tagging info because it's not necessary to tag all articles at once, user can tag few at a time when he can start from where has was stopped again. In simple: Would it be possible to send the user straight from their choice of a Category to the "Article Tagging" page with the next article to be tagged automatically loaded up and ready to be tagged, and the system keeps track of what the next article is that needs to be tagged? How can I accomplish this bit of functionality in … -
django admin listfilter dropdown
I'm currently trying to implement dropdown list filters in my django app but somehow can't get it to work. Tried at first with the diy approach but decided to try the django-admin-list-filter-dropdown app but still no succes settings.py INSTALLED_APPS = [ ... 'django_admin_listfilter_dropdown', ... ] admin.py from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter @admin.register(models.Project) class ProjectAdmin(admin.ModelAdmin): list_display = ( "name", "entry_date", ) list_filter = ( ("name", DropdownFilter), "entry_date", ) Any suggestions? Thanks in advance -
Django Main Page Not Loading in IE
Recently discovered my Django site will not load in IE. It is only the index page. I can browse every other page without issue. Chrome and Firefox load the site without issue. When in IE, visiting the main page prompts a download with a random file name which contains the rendered html code. -
Django + Arduino
I am trying to build a project that involves Arduino, GSM module and Django. If someone texts the number of the sim in the GSM module, I want to see it in my local web app(Django) and be able to reply to the sender's number using the web app. Is there any way that my GSM module connected on Arduino can connect/communicate with my Django project? Any Advice or Suggestions will be greatly appreciated. -
Javascript go to Django URL without redirecting the user
i created a upvote button in my blog, that send the user to a url then redirect the user to the previous page but i want to know if i can do this without redirecting the user in javascript i mean without using the a tag but using 'onClick' the button: <a href="{% url 'upvote' Post.id %}"><button>upvote</button></a> my view: def upvote(request, post_id): post = Post.objects.get(id=post_id) post.votes += 1 post.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
How to detect if CloudinaryField in django model is empty in template
picture = CloudinaryField('image', blank = True, null = True) I have the above line in my django models file. And I am rendering the picture in my template with the cloudinary tag {% cloudinary "filename" %} But in cases where the model objects don't contain the picture, I want to forgo the template tag. Right now, my template renders a empty image if the model instance doesn't have a picture. How can I detect if the model instance contains a picture, so that I can render it selectively using the ` {% if condition %} -
setting Primary key in Django model
I have changed primary key in my model class lab(models.Model): IP = models.CharField(max_length=250 , primary_key = True) PingStatus = models.CharField(max_length=250) SSHConnectivity = models.CharField(max_length=250) SSHLogin = models.CharField(max_length=250) DeviceType = models.CharField(max_length=250) DeviceVersion = models.CharField(max_length=500) I am trying to make two entries by assigning two different "IP" values for lab object. But somehow only one object is there in model >>> a=lab(IP="1.2.3.4") >>> a=lab(PingStatus="1.2.3.4") >>> a=lab(SSHConnectivity="1.2.3.4") >>> a=lab(SSHLogin="1.2.3.4") >>> a=lab(DeviceType="1.2.3.4") >>> a=lab(DeviceVersion="1.2.3.4") >>> a.save() >>> lab.objects.all() <QuerySet [<lab: lab object>]> >>> a=lab(IP="1.2.3.5") >>> a=lab(PingStatus="1.2.3.4") >>> a=lab(SSHConnectivity="1.2.3.4") >>> a=lab(SSHLogin="1.2.3.4") >>> a=lab(DeviceType="1.2.3.4") >>> a=lab(DeviceVersion="1.2.3.4") >>> a.save() >>> lab.objects.all() <QuerySet [<lab: lab object>]> >>> b=lab(IP="1.2.3.5") >>> b=lab(PingStatus="1.2.3.4") >>> b=lab(SSHConnectivity="1.2.3.4") >>> >>> b=lab(SSHLogin="1.2.3.4") >>> b=lab(DeviceType="1.2.3.4") >>> b=lab(DeviceVersion="1.2.3.4") >>> b.save() >>> lab.objects.all() <QuerySet [<lab: lab object>]> >>> Can someone check ? Am I missing something here ? -
django - split project to two servers (due to Cloudflare) without duplicating code
I currently have a Django project running on a server behind Cloudflare. However, a number of the apps contain functionality that requires synchronizing data with certain web services. This is a security risk, because these web services may reveal the IP address of my server. Therefore I need a solution to prevent this. So far I came up two alternatives: using a proxy or splitting the project to two servers. One server responsible for responding to requests through Cloudflare and one server responsible for synchronizing data with other web services. The IP address of the latter server will be exposed to the public, however attacks on this server will not cause the website to be offline. I prefer the second solution, because this will also split the load between two servers. The problem is that I do not know how I should do this with Django without duplicating code. I know I can re-use apps, but for most of them counts that I, for instance, only need the models and the serializers and not the views etc. How should I solve this? What is the best approach to take? In addition, what is an appropriate naming for the two servers? … -
How to implement the Django's server to listen to POST requests from Webhook? I am using NGROK to expose my localhost to the Internet
I have already created a Webhook in my Github repository. I have set my payload URL to: localhost:4567/payload As I am using my localhost, I need to expose it to the Internet. For this purpose, I am using ngrok and I have also executed this command: ./ngrok http 4567 I am following all the steps written in this link to create a successful webhook for receiving notification whenever any action on commits is done in the repository. Link => https://developer.github.com/webhooks/configuring/ I am using Django framework to receive POST requests from the Webhook. However, in the tutorial given in above link, they have used Sinatra (to create web application in Ruby). I am not familiar with Ruby. I wish to continue working in Django, so could you please help me how can I use Django's server to listen to POST requests from Webhook? By far what I have done, I have got following error in my Webhook. Error in my Webhook -
How do I obtain user fields from Facebook login
I'm busy implementing Facebook login for my django site. I'm not sure if I'm on the right track or way off the ball at the moment. I have implemented the full code as seen in the FB doc example https://developers.facebook.com/docs/facebook-login/web. Basically inserted script on the template. I have the button and once logging in I have the "Welcome fetching your information" "successful login for Joshua Raphael" in my console.log. How do I now obtain the required email, username and profile pic? Is it a part of the response object? Also if I have email login, is it possible to obtain the response email and check my current database to see if the user is already registered? Prefer not to use pre-made django apps but if you highly recommend one I may try it.Thanks -
loose data in disabled form fields or template fields after raisevalidationerror
i have disabled fields in django forms. when the form gets raisevalidationerror these fields are emptied. i used template (html) fields instead of disabled form fields but they are also emptied... how can i solve it, how can i send data to template fields or disabled form fields after raisevalidationerror.... view.... else: # for GET ....form is intialized deneme_1 = obje.id deneme_2 = obje.demirbasadi deneme_3 = obje.proje form = HareketForm() form.fields["hidd_proje"].initial = obje.proje form.fields["dem_id"].initial = obje.id form.fields["dem_adi"].initial = obje.demirbasadi form.fields["dem_proj"].initial = obje.proje return render(request, 'giris/hareket_yarat.html', {'form': form, 'deneme_1': deneme_1, 'deneme_2': deneme_2, 'deneme_3': deneme_3}) form.... class HareketForm(forms.Form): dem_id = forms.IntegerField(label='Demirbaş id....:', disabled=True, required=False ) dem_adi = forms.CharField(label='Demirbaş adı....:', disabled=True, required=False) dem_proj = forms.CharField(label='Mevcut proje....:', ) har_tipi = forms.ChoiceField(label='Hareket tipi........:', widget=forms.Select, choices=TIPI,) sonraki_proj = forms.ModelChoiceField(label='Sonraki proje.......:', queryset=proje.objects.all()) aciklama = forms.CharField(label='Açıklama', widget=forms.Textarea(attrs={'cols': 50, 'rows': 8}),) hidd_proje = forms.CharField(required=False, widget=forms.HiddenInput()) def clean(self): cleaned_data = super(HareketForm, self).clean() cc_dem_id = self.cleaned_data.get("dem_id") cc_dem_adi = self.cleaned_data.get("dem_adi") cc_dem_proje = self.cleaned_data.get("dem_proje") cc_hidd_proje = self.cleaned_data.get("hidd_proje") cc_har_tipi = cleaned_data.get("har_tipi") cc_sonraki_proj = cleaned_data.get("sonraki_proj") cc_aciklama = cleaned_data.get("aciklama") a = str(cc_sonraki_proj) if (cc_hidd_proje == a): raise forms.ValidationError(" two projects can not be the same.... ", ) -
Django-rest-framework and unique_together
I am writing and API, and due to the fact that it is based on the microservice architecture, and components run asynchronously, I cannot return an object id when the client creates an object. Some time later the client may wish to update the object, however, they don't know the id/pk. That said, there are several fields with the unique_together constraint on them. My initial idea was to override the create method and compare these fields on the objects that I receive with the ones in my DB, and, if I find any, update them, if I don't — create the object. However, that fails because the validation is run before the create method, and the validation fails for the "update" objects, because they break the unique_together constraint. I can't use those unique fields as a compound primary key for the table, because Django does not support that. Is there a way I can get a validated serializer to do the logic I described above, or is there a better way? (I am also thinking of trying to create and updating in except, but so far it looks a but cumbersome. -
Django formsets... bound, request,... coding pattern?
I am currently going through the base django documentation as I am trying to come up with some basic edit view class for an old project of mine. For this I have to work with formsets. I am confused at the pattern of calls used within this example for producing an edit view. What is the exact reason why you have to instantiate the formset for the validation with the request.POST, and for errors you recreate the whole thing again with your initial instance... (Otherwise it won't show any data) def manage_books(request, author_id): author = Author.objects.get(pk=author_id) BookInlineFormSet = inlineformset_factory(Author, Book, fields=('title',)) if request.method == "POST": formset = BookInlineFormSet(request.POST, request.FILES, instance=author) if formset.is_valid(): formset.save() # Do something. Should generally end with a redirect. For example: return HttpResponseRedirect(author.get_absolute_url()) else: formset = BookInlineFormSet(instance=author) return render(request, 'manage_books.html', {'formset': formset}) -
Windows/Python Error WindowsError: [Error 3] The system cannot find the path specified
Hi I am new to python and i need some help. I trying to run a file on Windows 10 OS with python 2.7. import os import re import codecs import numpy as np import theano models_path = "./models" eval_path = "./evaluation" eval_temp = os.path.join(eval_path, "temp") eval_script = os.path.join(eval_path, "conlleval") def get_name(parameters): """ Generate a model name from its parameters. """ l = [] for k, v in parameters.items(): if type(v) is str and "/" in v: l.append((k, v[::-1][:v[::-1].index('/')][::-1])) else: l.append((k, v)) name = ",".join(["%s=%s" % (k, str(v).replace(',', '')) for k, v in l]) return "".join(i for i in name if i not in "\/:*?<>|") def set_values(name, param, pretrained): """ Initialize a network parameter with pretrained values. We check that sizes are compatible. """ param_value = param.get_value() if pretrained.size != param_value.size: raise Exception( "Size mismatch for parameter %s. Expected %i, found %i." % (name, param_value.size, pretrained.size) ) param.set_value(np.reshape( pretrained, param_value.shape ).astype(np.float32)) def shared(shape, name): """ Create a shared object of a numpy array. """ if len(shape) == 1: value = np.zeros(shape) # bias are initialized with zeros else: drange = np.sqrt(6. / (np.sum(shape))) value = drange * np.random.uniform(low=-1.0, high=1.0, size=shape) return theano.shared(value=value.astype(theano.config.floatX), name=name) def create_dico(item_list): """ Create a dictionary of … -
Is there any method to set default value form.charField()?
I have created a form to take input from an HTML page like given bellow: class In_Form(forms.Form): Input_peptide = forms.CharField(label='Start Year ', max_length=100) sites_to_be_muted = forms.CharField(label='End Year', max_length=100) Amino_acide = forms.CharField(label='End Year ', max_length=100,) Is there any method through which I can set a default value for html form. I have tried "initial" but its not working in my case: please help -
404 Not found error in suds request send - python - django
I'm setting up online payment portal to my website. I use below code: from suds.client import Client # Within a function: ZARINPAL_WEBSERVICE = 'https://www.zarinpal.com/pg/services/WebGate/wsdl' amount = 20000 MERCHANT_ID = 'blah-blah-blah' description = 'TEST DESCRIPTION' # Required email = form.cleaned_data.get('email') # Optional mobile = form.cleaned_data.get('phone') # Optional CallbackURL = 'http://127.0.0.1:8000/business/verify/' client = Client(ZARINPAL_WEBSERVICE) print("###########################################################") result = client.service.PaymentRequest(MERCHANT_ID, amount, description, email, mobile, CallbackURL) if result.Status == 100: return redirect('https://www.zarinpal.com/pg/StartPay/' + result.Authority) else: return HttpResponse('Error') But before it shows me payment gate, it generates an error: Exception at /business/upgrade/ (404, 'Not Found') Request Method: POST Request URL: http://localhost:8000/business/upgrade/ Django Version: 1.11.4 Exception Type: Exception Exception Value: (404, 'Not Found') and the error is for this line of code: result = client.service.PaymentRequest(MERCHANT_ID, amount, description, email, mobile, CallbackURL) What's the problem? and how can I solve that? thanks -
Many-to-many relationships with several fields in Django
I have the following model: class Trip(models.Model): driver = models.ForeignKey(User) trip_cost = models.IntegerField(blank=True, null=True) passenger = models.CharField(max_length=50, blank=True, null=True) shared_cost = models.IntegerField(default=0, blank=True, null=True) Each Trip can have a driver alone, or a driver with several passenger. For each passenger the driver can set the percentage of the trip_cost each passenger is going to pay. What I need is to have: the field passenger to be listing all Users several passenger + shared_cost for each Trip. I guess I should use Many-to-many but I cannot make it work. Also when I try to set the passenger to models.ForeignKey(User), I get an error. Any help or direction highly appreciated. -
How to use custom variables in serializers?
I want to create a serializer that uses the variables from my model and also counts how many data of the same id is found in the table. I have created this, but it doesn't work: class WebsiteSerializer(serializers.Serializer): item_nr = serializers.IntegerField() class Meta: model = URL fields = ( "id", "item", "status", "item_nr " ) def get_item_nr (self, obj): obj.item_nr = Items.objects.filter(item_id=self.context.get(id)).count() return obj.item_nr -
Django Authenticate returns None with correct username and password during Userlogin
My User login has some issue with the authentication process. this is my code repository user = authenticate(username=username, password=password) returns user as none This is how my Accounts/views.py looks for login def login_view(request): params = {} params.update(csrf(request)) if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') # First get the username and password supplied # username = request.POST.get('username', '') # password = request.POST.get('password', '') # Django's built-in authentication function: print(username, password) user = authenticate(username=username, password=password) print('after aunthenticate', user) # If we have a user if user: # Check it the account is active if user.is_active: # Log the user in. login(request, username) # Send the user back to some page. # In this case their homepage. # return HttpResponseRedirect(reverse('/user_login/')) return render_to_response('user_login.html', RequestContext(request, {})) else: # If account is not active: return HttpResponse("Your account is not active.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username, password)) return HttpResponse("Invalid login details supplied.") else: form = LoginForm() args = {'form': form} head_list.update(args) # Nothing has been provided for username or password. return render(request, 'login.html', head_list) the login.html page is shown below {% block content %} <section class="container"> <h1>LiquorApp Login Console</h1> <div … -
ImportError: cannot import name patterns in django application
I am trying to create a facebook extractor for my research. for the purpose I have tried many libraries, but could not find an example. lastly I have reached this repository, which I guess is what I was looking for. But the problem is when I ran the it, I cam e across the following error: Performing system checks... Unhandled exception in thread started by <function wrapper at 0x0000000004540518> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\lenovo-pc\Desktop\psa-allauth-master\example\urls.py", line 1, in <module> from django.conf.urls import patterns, include, url ImportError: … -
Django How do you information from another model in a view?
I think this question has been asked a few times already, however, the questions and their answers are not that clear. If you can make the headline question or the example below to be clearer. Please do. Example: I have an orchard, within my orchard I have fields of apple trees and these apple trees have apples. The question is using my models: how do I get the number of apples in a given field? total mass of all the apples produced in that given field? Model class Field(models.Model): size = models.PositiveIntergerField() max_tree_number = models.PositiveIntergerField() class Tree(models.Model): field = models.ForeignKey(Field) age = models.PositiveIntergerField() variety = models.CharField(max_length=200) class Apple(models.Model): tree = models.ForeignKey(Tree) mass = models.PositiveIntergerField() View class FieldView(generic.ListView): template = '[app_name]/index.html' def get_context_data(self, **kwargs): context = super(FieldView, self).get_context_data(**kwargs) context['tree_count'] = Field._meta.model_name context['mass'] = ??? context['apple_count'] = ??? Thank you for your time