Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
urllib HTTPError not being caught in Python/Django
I am trying to handle an HTTPError with urllib. My settings are python3 in an anaconda virtualenv using Django 1.10. When the code gets the try, it doesn't go into except and crashes my page with Django telling me there's an HTTP error. Here is the code: from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError try: req = Request(api.lists.members.get(LIST_ID, client_email)) response = urlopen(req) except HTTPError as e: print('Error code: ', e.code) else: print('everything is fine') TRACEBACK: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/homepage/ Django Version: 1.10 Python Version: 3.6.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website'] Installed 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'] Traceback: File "/Users/plfiras/anaconda/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Users/plfiras/anaconda/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/plfiras/anaconda/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/plfiras/vinhood/vinhood-website/website/views.py" in homepage 52. conn = http.client.HTTPConnection(api.lists.members.get(LIST_ID, client_email)) File "/Users/plfiras/anaconda/lib/python3.6/site-packages/mailchimp3/entities/listmembers.py" in get 116. return self._mc_client._get(url=self._build_path(list_id, 'members', subscriber_hash), **queryparams) File "/Users/plfiras/anaconda/lib/python3.6/site-packages/mailchimp3/mailchimpclient.py" in wrapper 25. return fn(self, *args, **kwargs) File "/Users/plfiras/anaconda/lib/python3.6/site-packages/mailchimp3/mailchimpclient.py" in _get 100. r.raise_for_status() File "/Users/plfiras/anaconda/lib/python3.6/site-packages/requests/models.py" in raise_for_status 928. raise HTTPError(http_error_msg, response=self) Exception Type: HTTPError at /homepage/ Exception Value: 404 Client Error: Not Found for url: https://us13.api.mailchimp.com/3.0/lists/7bdb42e5c9/members/d071e758df3554f0fe89679212ef95e8 -
Geodjango distance query not retrieving correct results
I am trying to retrieve some posts depending on their proximity geographicaly. As you can see in the code i am using Geodjango and the code is executed within a view. The issue is that the distance filter seems to be completely disregaded when i check the distances on the queryset i get the expected distances (1m and 18km) but the 18km post should not have been retrieved. def get(self, request, format=None): latlon=request.query_params pnt = GEOSGeometry('SRID=28992;POINT(%s %s)'%(latlon['lat'],latlon['lon'])) posts = Post.objects.filter(point__distance_lte=(pnt, D(km=1))) serialized = PostSerializer(posts, many=True) for post in posts: distance = pnt.distance(post.point) print("Km distance:",distance * 100) return JsonResponse(serialized.data, safe=False) Result: Km distance: 0.00015231546206626192 Km distance: 18.317378752081577 [18/Jul/2017 13:24:35] "GET /api/posts/?lon=5.8372264&lat=51.8125626 HTTP/1.1" 200 144 -
CommandError: No fixture named 'myapp' found
I created a json file myapp/fixtures/initial_data.json , which has the data to be loaded. But when I run python manage.py loaddata myapp Getting below error CommandError: No fixture named 'myapp' found. What could be reason for the error? -
Auto-generate the models for my mongodb database
i know this question was asked previously on stackoverflow but i am not able to find an answer :( i have a few databases in MongoDB that I want to create models for dynamically, since there are many databases and I cannot do it manually. so how to autogenerate models for my mongodb database? Does inspectdb work with mongodb databases? -
CodesWholeSale API in Django
I want to make an e-shop with digital game codes. I want to use CodesWholeSale as distributor. Can I do it in Django somehow ? Thank you guys. -
Django how to implement backoffice users
I am developing a website for a small company that allows the management of reservation of cars by users. I created a first application that manages user accounts. During registration to the site the user must load pdf documents These documents will then be verified by a member of the company. If the uploaded documents are good, this member sends to the user in question a contract to be signed electronically After registration and login the user will be redirected to his dashboard With each new registration the user must wait for the confirmation of the loaded documents so that he can have access on the information presented in his dashboard Can you please show me how to implement this PS: I am a beginner in django and web development !! -
Django temporary merge other DB results with ORM
This question seems to be very weird, but I'm very courious in how to solve this kind of issues. The matter is that I have two diferent web platforms, lets say: Platform A Local network application (Java based) with a dedicated OracleSQL db server. Platform B Django with postgres SQL All the systems are in local network. So in platform B, there is some django views that requiere aggregated data from system A, but this data is only needed per request basis. I mean, the system A is a ERP software that have only the information about princing of the products, and the platform B (django) have the product list itself. So I need to create a view in django that lists the products, ordered by price. How this can be done? I was thinking on quering django for the products, load the product list in a RAM storage, then ask to Platform A for the prices sending the product id array list, and then making a merge in RAM memory in order to generate a queryset ordered by price. Could be REDIS any good for this purpose? We have direct access to the OracleDB and also a specific endpoint … -
Django accessing non-static files from static files
I have a javascript static file within which I would like to specify a source url to a non-static json file. The below doesn't seem to work: source: {url: "users/username1/nonstatic.json"} It works if I explicitly (and non-ideally) specify an absolute static json url: source: {url: "static/default_GCMS.json"} Am wondering what's the correct way of calling a non-static file from a static one (.js in this case). -
After importing variable from view.py into. No dropdown appearing in forms
I am using Django forms in in forms I need a variable from views.py named 'layer_id'. So I get it like self.form = labelModelForm(layer_id=self.layer.id) and used in forms.py like class labelModelForm(forms.ModelForm): model = Labels_tool_ def __init__(self, *args , **kwargs): layer_id = kwargs['layer_id'] apn= forms.ModelChoiceField(queryset=Field.objects.values_list('name', flat=True) ,empty_label="(Choose field)") So now when I run program no dropdown list appear. Where I am wrong ? As layer_id I am getting is correct in form in view.py My View.py file is self.form = labelModelForm(layer_id=self.layer.id) if self.request.method == 'POST': self.layer = Layer.objects.filter(id=urlItems[i + 1],map=self.map.id).first() layerid= self.layer.id labmapid=self.map.id And template file is <form action="" method="post" id="label_form">{% csrf_token %} <div id="field1"><p id="apn_text">APN: </p> {{ form.apn}}</div> Models are like class pdftabel_tool_(models.Model): apn = models.CharField(null=True, blank=False, max_length=255) Now where I am making mistake that value from view.py is correct but not dropdown showing ? -
Website builder in django
I am tasked with creating website builder in django. I googled but didn't got any idea from where and how do I start. Can someone please throw some light on this? -
Passing user auth status in view
I am using Django Cookiecutter as template. And by default in urls.py there is following url: url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), and because i need to pass some additional parameters in it i wanted to use it as: url(r'^about/$', index, name='about'), Where index is from my views, but when i use the view, my system does not recognise that user is logged in, should i somehow pass user in my index too or what am i doing wrong? What i am doing in my view: def index(request): return render_to_response('pages/about.html', { 'categories': Category.objects.all(), 'posts': Post.objects.all()[:5] }) -
Django Apache2 Logging and REST Problems
I have deployed a Django app using Apache2 and it works fine. However when I add either REST framework or logging the app doesn't respond properly. To note is that all works fine using 'manage.py runserver'. I just fails running under Apache2. The problems are REST The service doesn't recognize JSON input and accepts anything typed in the web interface input box despite having JSON selected as the input. Whatever is typed just gives back a 201 response despite having a working serialiser in place. Logging The whole application doesn't boot when logging is in the settings.py file. If I comment it out it boots fine. Again it works in the demo server setup. Apache2 Config <VirtualHost *:80> WSGIScriptAlias / /home/user/portal_interface/portal/wsgi.py Alias /static /home/user/portal_interface/interface/static <Directory /home/user/portal_interface/interface/static> Require all granted </Directory> <Directory /home/user/portal_interface/portal> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess portal python-path=/home/user/portal_interface:/var/www/sampleapp/env/lib/python2.7/site-packages WSGIProcessGroup portal </VirtualHost> Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'debug.log'), } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, } } } -
Django group by field
Surprising that I could not find a way to make a group by query. I have a query set qs and I am trying to group by some_prop.val, considering qs is excluding entries where some_prop is None. Let's say the values are [1, 2, 3], then I would be after a result like this: {1: entries1, 2: entries2, 3: entries3} Does the Django ORM provide any feature to group results like this? -
Django get_or_create multipleobjectsreturned
I have defined a django model with multiple Charfields that when I populate the model remain empty. I have a pandas.dataframe that iterate over the rows to populate my model. The problem is that if I let's say want to create an object with foo1 as only field because all rest are empty (see below), Django gets all objects that fulfill that condition foo1=value but not a single object with field foo1=value and the rest of the field being null. Am I approaching this in the wrong way? What is the way to use get_or_create for this purpose? fields_dict ={ 'foo1': df.ix[index, 7], 'foo2': df.ix[index, 8], 'foo3': df.ix[index, 9], 'foo4': df.ix[index, 10] } my_object, created_boolean = MyModel.objects.get_or_create( **fields_dict, ) # If fields_dict = {'foo1' = 'bla'} and there are more objects with these conditions it grabs all of them. I want to create one object with only this field and the rest being null. All fields are charfield in the model models.py class ClinicalStudy(models.Model): foo1 = models.CharField(max_length=255) foo2 = models.CharField(max_length=255) foo3 = models.CharField(max_length=255) foo4 = models.CharField(max_length=255) -
Add view to Django Admin
I want to add in my Admin interface a read-only view which shows a list of items. I've looked at the docs but lacked good examples. Could anyone provide a basic skeleton to better understand how to do it? -
Jquery Django Add fields (or hide and show) with the value of a field
So i am programming in Django and i want that with the value of a Choice field a new field appear. so i have this in my template in Html <script type="text/javascript"> $( document ).ready(function() { if( $('#{{clinic_details.parity}}' == 'AtleastOne' ) ){ $('#paritefield').show(); }else{ $('#paritefield').hide(); } }); </script> <div class="form-group"> <div id="require"> {% csrf_token %} {{ clinic_details.as_p}} {{ ClinicForm.}} </div> </div> <div class="form-group"> <div id="paritefield"> {{ parityfield.as_p }} </div> </div> And in forms.py i have class ClinicForm(forms.Form): SELECT_ETHNICITY = (('1','Europe and North Africa'),('2','East-Asian'),) origin = forms.ChoiceField(widget=forms.Select, choices=SELECT_ETHNICITY, label ="Origin") SELECT_DIABETE = (('1','None'),('2','Not documented'),) diabete = forms.ChoiceField(widget=forms.Select, choices=SELECT_DIABETE, label ="Diabetes") SELECT_PARITY = (('None','None'),('AtleastOne','At least One'),) parity = forms.ChoiceField(widget=forms.Select, choices=SELECT_PARITY, label ="Parity") fields = ['origin', 'diabete',] class ParityfieldForm(forms.Form): SELECT_PARITYFIELD = (('1','None'),('2','Not documented'),) parityfield= forms.ChoiceField(widget=forms.Select, choices=SELECT_DIABETE, label ="Parity field") and finally in view.py i have def form_view(request): clinic_details = ClinicForm(request.POST or None) parityfield = ParityfieldForm(request.POST or None) title="Form" if clinic_details.is_valid(): fsv = clinic_details.save(commit=False) return render(request,"template.html",{"clinic_details":clinic_details, "parityfield":parityfield, "title": title}) So I want that when the value of the Choice field parity is 'AtleastOne' it shows another field but without refreshing the page, Thanks to Jquery. -
In django python, delete a cookie which is basically a session ID
In django I want to delete a cookie or set it to null what is the method to do that in views. -
AWS ElasticBeanstalk: JWT token not being validated after configuration change
Using AWS console, I changed configuration setting of api key for a third-party service. Then all of a sudden, the following error is popping up on my live server. {"detail":"Authentication credentials were not provided."} It seems JWT token is not being validated(or passed). After hours of googling, I found that the error is caused by EB apache setting Apparently, by setting, container_commands: 01_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' in *.config, the problem should go away. I did exactly the same, with the code in wgsi_enabled_pass.config created within .ebextensions but it is still not working. Please help the newbie pros! Thanks in advance! -
Make fast query on foreign keys, django
I have a performance issue on the following szenario: My models: class Journey(models.Models): #... class Station(models.Model): #... class Connection(models.Model): station1 = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='station1') station2 = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='station2') Now I arranged a list via a* that contains adjacent stations_ids on a journey (from a to b) and I need to get the matching connections. Ive used those 2 possibilites, but the both need the same time which can be more than 10 seconds for longer journeys: for i in range(0, len(journey)-1): try: connection = Connection.objects.get(station1_id=journey[i], station2_id=journey[i+1]) except Connection.DoesNotExist: try: connection = Connection.objects.get(station1_id=journey[i+1], station2_id=journey[i]) except Connection.DoesNotExist: pass journey.connections.add(connection) for i in range(0, len(journey)-1): s1 = Station.objects.get(id = journey[i]) s2 = Station.objects.get(id= journey[i+1]) if (Connection.objects.filter(station1=s1, station2=s2).exists()): connection = Connection.objects.get(station1=s1, station2=s2) elif (Connection.objects.filter(station1=s2, station2=s1).exists()): connection = Connection.objects.get(station1=s2, station2=s1) journey.connections.add(connection) How can i make it faster? -
How to convert a string containing image data back
So at the moment i have converted image data into a string so it would be JASON serializable. however now i am not sure on how to convert the string back into the original image data. def FileView(request): form = FileForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): image = base64.encodebytes(request.FILES.get('image').read()) request.session['image_file'] = json.dumps(str(image)) return redirect('View') def View(request): img = request.session.get('image_file') -
Running Django Python Server in AWS
I have a django running in AWS Ubuntu machine. Through SSH, I start the server at 8000 port. But when i close the ssh window, server stops and I can't access it through URL. What I want is to run the server all the time once it is started. How to go about it? Thanks. -
Django aggregation and annotation behavior comparison
I was trying to use an annotated value to filter a query set using an F expression, but it turns out it it does not behave the way I am expecting. I am trying to filter objects from a query set qs whose property some_prop is the maximum of that query set. For example: set(qs.values_list('some_prop', flat=True)) would output: set([1, 3, 5, 7, 9]) And I am aiming to filter qs by the value 9, which is the maximum. I can easily achieve that using an aggregation: max_prop = qs.aggregate(max_prop=Max('some_prop'))['max_prop'] qs.filter(some_prop=max_prop) But I wanted to condense this behavior in a single query, so I used an annotation instead of an aggregation: qs.annotate(max_prop=Max('some_prop')).filter(some_prop=F('max_prop')) However this does not show the same behavior. This is actually just filtering by all some_prop values rather than the maximum. What am I missing? There must be something I am misunderstanding from the annotation and aggregation features. -
Ajax access django ManyToManyField by id
My models: class Topping(models.Model): name=models.CharField(max_length=24) class Pizza(models.Model): toppings=models.ManyToManyField(Topping) My views: def get_pizza(request): if request.is_ajax(): pizza_list=[] pizza_list=Pizza.objects.all() pizza_list_json = serializers.serialize('json', pizza_list) return JsonResponse({'result': 'OK', 'data': { 'pizza_list': pizza_list_json, }}) My Javascript: function get_pizza() { $.ajax({type: 'POST', url: '/path/get_pizza/', data: { }, success: function (lista) { if (lista.result === 'OK') { var pizza_list_json=lista.data.pizza_list; pizza_list = JSON.parse(pizza_list_json); make_pizza(pizza_list); }; } }); }; function make_pizza() { for (i=i; i<pizza_list.length; i++) { var myfield=toppings; var list_elem=pizza_list[i].fields[myfield]; }; }; The problem is that list_elem=[1, 4] contains the id of the objects while I need the names list_elem=[tomato, peperoni]. With a foreign key I can use the to_field=name option in the model but with a ManyToManyField I can't. I tried myfield__name but doesn't work (it give myfield__name is not defined error). So, what can I do? I have to define the pizza_list in a different way in my view? Which is an efficient way to handle this? Thank you -
Return image in HTTP response
After compute the scatter plot with plt.scatter(...) I can preview the graph with plt.show() However, I wish to save the plot with some sort of function like savefig() which store the image in a variable instead of a file, then return the variable in http response as content/png in django web framework -
Template Does not exist error while deploying on pythonanywhere
I was trying to create a blog in my domain using django 1.9 and python 3.5 with virtual environment. So while deploying on pythonanywhere. I am able to render the html. Here is the traceback. Request Method: GET Request URL: http://www.example.com/` Django Version: 1.9 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog']`` Installed 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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/contrib/admin/templates/blog/templates/blog/post/list.html(Source does not exist) * django.template.loaders.app_directories.Loader:/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/contrib/auth/templates/blog/templates/blog/post/list.html(Source does not exist) * django.template.loaders.app_directories.Loader:/home/pdlsaroj22/myblog/mysite/blog/templates/blog/templates/blog/post/li`st.html (Source does not exist) Using engine django: * django.template.loaders.app_directories.Loader: /home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/contrib/admin/templates/blog/post_list.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/contrib/auth/templates/blog/post_list.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/pdlsaroj22/myblog/mysite/blog/templates/blog/post_list.html (Sourcedoes not exist) `Traceback: File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 174. response =self.process_exception_by_middleware(e, request) File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 172. response = response.render() File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/response.py" in render 160. self.content = self.rendered_content File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/response.py" in rendered_content 135. template = self._resolve_template(self.template_name) File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/response.py" in _resolve_template 90. new_template = self.resolve_template(template) File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/response.py" in resolve_template 80. return select_template(template, using=self.using) File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/loader.py" in select_template 74. raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) Exception Type: TemplateDoesNotExist at / Exception Value: blog/templates/blog/post/list.html, blog/post_list.html ` My views.py looks like this: class PostListView(ListView): queryset = Post.published.all() context_object_name = …