Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Angularjs code not working with Django
I want to add simple angularjs code to django. For this I have taken the simple example: I have put the below code in my template: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; }); </script> <div ng-app="myApp" ng-controller="myCtrl"> First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> <br> Full name:{{firstName}} </div> </body> </html> My view.py is as follows: from django.shortcuts import render from django.http import HttpResponse from django.template import loader # Create your views here. def index(request): template = loader.get_template('warlist/index.html') return HttpResponse(template.render()) Now when I run it,it is taking the names in the text feild but It is not printing the full name. However same angularjs code is working fine without django. -
How to make many forms/formset with initial data django
I have two related models, and I need to chage second model in table-like form. I wrote this code: def add_offer(request): if request.method == 'POST': forms = OfferForm(request.POST, instance=Offer()) for form in forms: if forms.is_valid() form.save() HttpResponseRedirect('/offers/add') else: products = Product.objects.filter(company=request.user.company); forms = [] for i, p in enumerate(products): try: offers.append(Offer.objects.get(product = p) ) except Offer.DoesNotExist: offers.append(Offer(product = p)) return r(request,'deals/offers.html', { 'forms': forms }) Model: class Offer(models.Model): name = models.CharField(max_length = 255) product = models.ForeignKey(Product, on_delete = models.CASCADE) unit_price = models.DecimalField(max_digits = 19, decimal_places = 2) currency = models.CharField(max_length = 3, choices = CURRENCY_CHOICES, default = RUBLE) I want to change form, if offer have product existing, and add form if not -
How to change price for several products individually using a single script function?
Please take a look at my code here. The page is deployed here. I'm using an ID price to refer to the price of an item. A general jQuery function attempts to change the price of every item on a selection change (with respect to the size of the item), as below: jQuery(document).ready(function(){ jQuery(".variation_select").change(function(){ var price = $(".variation_select option:selected").attr("data-price"); var sale_price = $(".variation_select option:selected").attr("data-sale-price"); if (sale_price != "" && sale_price != "None" && sale_price != null ) { $("#price").html("<h4>" + "₹&nbsp;" + sale_price + " <small class='og-price'>" + "₹&nbsp;" + price + "</small></h4>"); } else { $("#price").html("₹&nbsp;" + price); } }); }); As the items and their data come from the backend and I have multiple items, the HTML understandably replicates and as a result, I have more than a single element with the same ID. The HTML that displays the item's price is as below: {% if object.variation_set.count > 1 %} <h4 id='price' style="text-align: center; display: block;">₹&nbsp;{{ object.variation_set.first.price }}</h4> <select name= 'item' class='form-control variation_select' style="margin: 0 auto; width: 30%; display: block;"> {% for vari_obj in object.variation_set.all %} <option data-sale-price="{{vari_obj.sale_price}}" data-price="{{ vari_obj.price }}" value="{{ vari_obj.id }}">{{ vari_obj }}</option> {% endfor %} </select> <br> {% else %} <input type="hidden" name='item' value='{{ … -
Storing multiple dates in django field
I want to store multiple dates without creating additional model. Is there MultipleDatesField in django? e.g. store as "2017-03-21, 2017-03-28, 2017-04-01" and use one datepicker in form for it. -
Chat Room in Django Channels
I have models "Project" and "Room". Every project has own chat room. I am tring to use Django Channels. Unfortunarly, I have error. What I miss and how to fix this error. ERROR: Traceback (most recent call last): File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\routing.py", line 73, in resolve_routing routing = getattr(importlib.import_module(module_name), variable_name) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'example_channels' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\management\commands\runserver.py", line 41, in inner_run self.channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER] File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\asgi.py", line 53, in __getitem__ self.backends[key] = self.make_backend(key) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\asgi.py", line 48, in make_backend routing=routing, File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\asgi.py", line 80, in __init__ self.router = Router(self.routing) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\routing.py", line 25, in __init__ self.root = Include(routing) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\routing.py", line 201, in __init__ self.routing = Router.resolve_routing(routing) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\routing.py", line 75, in resolve_routing raise ImproperlyConfigured("Cannot import channel routing %r: %s" % … -
CSRF issue with ajax and no form in the template
I am currently getting a permission denied when I try to use POST with ajax. I believe this is because of CSRF as my post works fine when I use the @csrf_exempt decorator on my view. I would appreciate it if someone could tell me what I might be doing wrong here.I tried this SO post however that does not help.I then attempted to follow the python documentation here regarding this issue however I am still getting the permission denied error. Here is my code In the view I am doing something like this @csrf_protect def showMgmt(request): cntxt = {} ..... ..... response = render(request, 'management.html', cntxt) return response @csrf_protect def AjaxDestination(request): return response("...") Now initially first the showMgmt function display the management.html which contains the following ajax request. This ajax request calls on the function AjaxDestination page:management.html <script> // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); … -
How to programmatically access {{ form.my_field.id_for_label }}?
My Django project uses Bootstrap v4. I iterate through all the fields to add the HTML attribute class="form-control". I also need to add an HTML attribute aria-describedby="{}Help" where {} is the id_for_label for the widget. In the template language I could print that value easily with {{ form.my_field.id_for_label }} but programmatically I don't know how to do it. I tried it with ModelForm().fields['…'].widget.id_for_label() but that method expects an argument. And by lookind at the Django source code, the return value is literally the argument. Any ideas? class AbonnentForm(ModelForm): class Meta: model = Abonnent fields = '__all__' def __init__(self, *args, **kwargs): super(AbonnentForm, self).__init__(*args, **kwargs) # Add Bootstrap class to all <input> elements. for key, value in self.fields.items(): value.widget.attrs.update({'class': 'form-control'}) if value.help_text: id_for_label = "{}Help".format(value.widget.id_for_label()) value.widget.attrs.update({'aria-describedby': id_for_label}) self.fields['erste_ausgabe'].widget.attrs.update({'placeholder':'MM/JJJJ'}) self.fields['letzte_ausgabe'].widget.attrs.update({'placeholder':'MM/JJJJ'}) -
How to integrate Speech Recognition and Speech synthesis into Django Chatbot buit using Chatterbot Library?
I have Built a chatbot application using Chatterbot Python Library. The application runs a Django Application. I have created a Chat interface where the communication is done using Text. I want to add Speech recognition and Synthesis capability for input and output respectively. Can anyone suggest a path how to do it? -
I can not use mulitprocessing in my django project.Why?
Here is my project folder: \prjname ---\appname ---\---\subappname1 ---\---\---\__init.py ---\---\subappname2 ---\---\---\__init.py ---\---\view.py ---\---\models.py ---\---\admin.py ---\---\__init__.py In models.py I defined some model like: class model1(models.Model) : name=models.CharField(primary_key=True, max_length=32) In subappname1.init.py I have some code like: from appname.models import model1 import multiprocessing class myclass(Object): def myfun(self): res = [] threadargs=[(arg1,arg2),(arg3,arg4)] pool = multiprocessing.Pool(processes=multiprocessing.cpu_count()) for arg in threadargs: res.append(pool.apply_async(self.mywork,arg)) pool.close() pool.join() for re in res: re = re.get() self.myrecord(re) def mywork(self,arg1,arg2): #do something pass def myrecord(self,re): #record the result pass I think it is easy to understand. I am trying to do some time-consuming work by multiprocess. However, when I run such code, I got error below: Process SpawnPoolWorker-2: Traceback (most recent call last): File "E:\programfile\python\lib\multiprocessing\process.py", line 249, in _bootstrap self.run() File "E:\programfile\python\lib\multiprocessing\process.py", line 93, in run self._target(*self._args, **self._kwargs) File "E:\programfile\python\lib\multiprocessing\pool.py", line 108, in worker task = get() File "E:\programfile\python\lib\multiprocessing\queues.py", line 345, in get return _ForkingPickler.loads(res) File "E:/suilong/workspace/myproject\myappname\subappname1\__init__.py", line 7, in <module> from myappname.models import models File "E:/suilong/workspace/myproject\myappname\models.py", line 10, in <module> class model1(models.Model): File "E:\programfile\python\lib\site-packages\django\db\models\base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "E:\programfile\python\lib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "E:\programfile\python\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here is my information: OS: windows7 python: … -
Need help saving action object using django-activity stream
I am trying to create a newsfeed using django activity stream. I am making a target stream but action object is not saved if it is a comment it does not save "id": 14, "actor": { "id": 1, "email": "zacmwangi94@gmail.com", "first_name": "", "last_name": "" }, "verb": "commented on", "action_object": null, "target": { "id": 6, "venue": { "id": 1, "name": "IMAX", "address": "NAIROBI", "city": "NAIROBI", "rating": "1.1" }, "thumbnail": null, "user": 1, "event_pic_url": null, "name": "A movie", "time": "2017-11-11T16:02:00Z", "description": "A description", "event_type": "Movie", "invite_only": true, "free": false, "age_restriction": true, "ticket_price": 1000.0, "created_at": "2017-03-19T10:35:41.723753Z" } } When the action object is a photo it is saved properly. This my comment model : class Comment(models.Model): user = models.ForeignKey(User) text = models.TextField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') and this is how I create an action after the comment is created: def comment_activity(sender, instance,created, **kwargs): if created: action.send(instance.user, verb='commented on', action_object=instance, target=instance.content_object) post_save.connect(comment_activity, sender=Comment, dispatch_uid=comment_activity) I have also tried saving it in the views using the action.send signals and Action.objects.create() but all these approaches have failed. def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): comment = Comment.objects.create(**serializer.validated_data) Action.objects.create(actor=comment.user,action_object=comment,verb="commented on",target=comment.content_object) # action.send(request.user,action_object=comment,verb="commented on",target=comment.content_object) return Response( serializer.data, status=status.HTTP_201_CREATED … -
How can I configure nginx with multiple uwsgi vassals (with websockets) in emperor mode?
I'm having issues running 2 vassals in emperor mode (for a main app + websocket) behind an nginx server. Everything seems to be running well, but all the websocket requests return error 502 bad gateway. The websocket app is running django-websocket-redis. Any ideas where I went wrong? Running from upstart exec /usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals/ --logto /var/log/uwsgi.log With /etc/uwsgi/vassals/dashdb_websocket.ini: # dashdb_websocket.ini file [uwsgi] umask = 002 home = /opt/dashdb/venv/dashdb-3.5 plugin = python35 chdir = /opt/dashdb master = true no-orphans = true die-on-term = true memory-report = true env = DJANGO_SETTINGS_MODULE=dashdb.settings.opener socket = /var/run/uwsgi/dashdb_ws.sock pythonpath = /opt/dashdb module = dashdb.wsgi_websocket threads = 1 processes = 1 http-websockets = true gevent = 1000 # Log file location daemonize = /var/log/uwsgi/dashdb_websocket.log With /etc/uwsgi/vassals/dashdb.ini: # dashdb.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /opt/%n # Django's wsgi file module = dashdb.wsgi # the virtualenv (full path) home = /opt/dashdb/venv/%n-3.5 plugin = python35 # settings location env = DJANGO_SETTINGS_MODULE=dashdb.settings.opener # Process-related settings # master master = true # maximum number of worker processes processes = 3 # the socket (use the full path to be safe) socket = /var/run/uwsgi/%n.sock # ... with appropriate permissions - may be needed chmod-socket = … -
django - queryset.last() not returning right order / last record
Writing code that is generating JSON. The last section of JSON has to be terminated by a ",", so in the code I have: -- Define a queryset to retrieve distinct values of the database field: databases_in_workload = DatabaseObjectsWorkload.objects.filter(workload=migration.workload_id).values_list('database_object__database', flat=True).distinct() -- Then I cycle over it: for database_wk in databases_in_workload: ... do something if not (database_wk == databases_in_workload.last()): job_json_string = job_json_string + '} ],' else: job_json_string = job_json_string + '} ]' I want the last record to be terminated by a square bracket, the preceding by a comma. But instead, the opposite is happening. I also looked at the database table content. The values I have for "database_wk" are user02 (for the records with a lower value of primary key) and user01 (for the records with the higher value of pk in the db). The order (if user01 is first or last) really doesn't matter, as long as the last record is correctly identified by last() - so if I have user02, user01 in the queryset iterations, I expect last() to return user01. However - this is not working correctly. What is strange is that if in the database (postgres) order is changed (first have user01, then user02 ordered by … -
Action object in django activity stream not saved when using target stream
I am trying to set up a target stream using django activity stream where the target is an event object. When the action object is a comment it does not save the comment and displays null like this: "id": 14, "actor": { "id": 1, "email": "zacmwangi94@gmail.com", "first_name": "", "last_name": "" }, "verb": "commented on", "action_object": null, "target": { "id": 6, "venue": { "id": 1, "name": "IMAX", "address": "NAIROBI", "city": "NAIROBI", "rating": "1.1" }, "thumbnail": null, "user": 1, "event_pic_url": null, "name": "A movie", "time": "2017-11-11T16:02:00Z", "description": "A description", "event_type": "Movie", "invite_only": true, "free": false, "age_restriction": true, "ticket_price": 1000.0, "created_at": "2017-03-19T10:35:41.723753Z" } } However when the action object is a photo it is saved properly. This is how my comment model looks like: class Comment(models.Model): user = models.ForeignKey(User) text = models.TextField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') and this is how I create an action after the comment is created: def comment_activity(sender, instance,created, **kwargs): if created: action.send(instance.user, verb='commented on', action_object=instance, target=instance.content_object) post_save.connect(comment_activity, sender=Comment, dispatch_uid=comment_activity) I have also tried saving it in the views using the action.send signals and Action.objects.create() but all these approaches have failed. def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): comment = … -
get instance from model to save to foreignkey field
i don't really understand what this instance was implying "Cannot assign "15": "Cart.Product_ID" must be a "Product" instance." "15" is the primary key of Model.Product and i want to insert it into Model.Cart views.py def post(self, request, *args, **kwargs): form = TempCart(request.POST) if form.is_valid(): VarProductId = Product.objecrs.get(PId="Product_ID") VarHowMany = request.POST.get('HowMany') VarDateSubmit = request.POST.get('DateSubmit') Cart_obj = Cart(Product_ID = VarProductId, HowMany = VarHowMany, DateSubmit = VarDateSubmit) Cart_obj.save() return HttpResponseRedirect('/Catalogue') models.py class Product(models.Model): PId = models.AutoField(primary_key=True) # and other fields class Cart(models.Model): Product_ID = models.ForeignKey(Product, on_delete=models.CASCADE) HowMany = models.PositiveIntegerField(default=0) DateSubmit = models.DateTimeField(default=datetime.now) html <form method="post" action="" id="CartInput"> {% csrf_token %} <div> <input name="Product_ID" type="hidden" value="{{ Product.pk }}" > <input name="HowMany" type="number" value="1" id="HowMany" > {{ CartForm.DateSubmit }} </div> <div> <input name="Cart{{ Product.PId }}" type="submit" value="Add to Cart"> </div> </form> am i missing something here? maybe i have to save the whole queryset for Product_ID(foreignkey)? Thanks in advance Cheers -
Django: Calling delete() method on only() raise exception DoesNotExist
Let's say I have following model: class Student(models.Model): name = models.CharField(max_length = 100) ... When I am trying to call delete() method on only() like: Student.object.filter(pk__in=[1, 5, 6]).only('id', 'name').delete() I get the following error: DoesNotExist: Student matching query does not exist My question is: can't we call delete() on only()? Note: We are using only() on Django admin's get_queryset() method for better performance. For your info, my admin looks like: class StudentAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(ShipmentAdmin, self).get_queryset(request) return qs.only('id', 'name', ...) When we are trying to delete objects from Admin, we get this error. -
HOw do i retrive the value from django model with foreign key constrain?
I have two models one is class NewsLikes(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") userId = models.ForeignKey(Users, db_column='userId', max_length=11, help_text="") newsId = models.ForeignKey(NewsMappings, db_column='newsMappingId', max_length=11, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text=" and the other model is class NewsMappings(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") newsId = models.ForeignKey(News, db_column='newsId', max_length=11, help_text="") boardId = models.ForeignKey(Boards, db_column='boardId', max_length=11, help_text="") isWallPost = models.BooleanField(db_column="isWallPost", default=False, help_text="") the model news like contains foreign key of news mapping. I am passing news mapping as a context in my django templates and i want to count how many news likes id are present with respect to news mapping and display it on the templates. -
Django JWT auth: How to get user data?
I'm trying to desperately understand how to use JWT auth with Django. This page explains how to get a token against username and password: http://getblimp.github.io/django-rest-framework-jwt/ $ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/ Now in order to access protected api urls you must include the Authorization: JWT <your_token> header. 1) How can I get the user details (id, email..) of the "logged in" user from the server? If I used the session based auth I would just serialize and return request.user if it's logged in. I don't understand how the server would know who is who if nothing auth-related is persisted. 2) I don't even understand how the procedure described in that page is safe. Why can't the attacker just hijack the token and do what he wants? As I understood I just get a token and then send the same token back in every request. Is this even real JWT? -
Django-Class based template HttpResponseRedirect does not redirect to desire page
I have the following code which will redirect to localhost:3000/ocr/result page, but it did not render the result page class UploadView(generic.TemplateView): template_name = 'ocr/upload.pug' def get(self, request, args, *kwargs): print 'Handling get request' response = TemplateResponse(request, self.template_name) return response #@ensure_csrf_cookie def post(self, request, args, *kwargs): print('Handling post request') #return HttpResponseRedirect('/ocr/result') return HttpResponseRedirect(reverse('result')) class ResultView(generic.TemplateView): template_name = 'ocr/result.pug' urls.py look like: # ex: /ocr/upload/ url(r'^upload/$', views.UploadView.as_view(), name='upload'), # ex: /ocr/result/ url(r'^result/$', views.ResultView.as_view(), name='result'), When I used return HttpResponseRedirect('/ocr/result') after processing post request, it did not render the result page as desire (localhost:3000/ocr/result), and still render upload page (localhost:3000/ocr/upload). I dont understand why? When I used return HttpResponseRedirect(reverse('result')) It still has error: NoReverseMatch: Reverse for 'result' with arguments '()' and keyword arguments '{}' not found. Could someone help me how to redirect to /ocr/result and reder result page? -
Can this result in a deadlock in django + postgres?
I have two simultaneous processes that run separate transactions that eventually gets to the same code path: object = X.Objects.get(filter=samplefilter) // Assume this gets a single row back object.SampleProperty = "Hello World" object.Save() One of the process keeps reporting a deadlock waiting for ShareLock at object.Save(). I assume the other one isn't reporting because it was the one that was not killed. If these processes ended up selecting the same row from X, can it result in a deadlock? I can't see how because .get() does not place a lock on "object", does it? -
How to set URL include to answer root level urls in django
I have these URL files: project/url: urlpatterns = [ url(r'^$', include(public)), <--- URL IN ERROR!!!! url(r'^member/', include(mviews)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) public/url: urlpatterns = [ url(r'^$', views.index), url(r'^login/', views.login) ] mviews/url: urlpatterns = [ url(r'^$', views.index), url(r'^api/', include(router.urls)), ] in the first URL file, the first URL where it says include(public) is erroring out. How do I set it so public is the "home" url group? Thanks. -
Django ImageField won't upload in function based view, but it does in the admin
I've been trying to add some user uploaded profile picture to my website. It works fine when I do it from the admin, the image is showed and all the engines seems to be working fine (image going to the correct upload location and so on). The problem is when I try to do the same thing from my view. I noticed that the print("upload_location") only appears when I do it from the admin. The weird thing is that all the other fields in my Profile model are working fine (like name "foo" is updated to "foobar") and not only in the admin, but in the view as well. The issue is only with the ImageField. I believe it could have something to do with the way I'm handling the form.is_valid(), but I've been playing around with that and nothing changed (I know it is working to some extend, since HttpResponseRedirect is working. Any ideas? views.py ... @login_required def profile_update(request, username=None): obj = get_object_or_404(User, username=username) user = obj.profile form = ProfileForm(request.POST or None, instance = user) context = { "form": form } if form.is_valid(): form.save() return HttpResponseRedirect('/profiles/{username}'.format(username=user.user)) template = 'profile_update.html' return render(request, template, context) forms.py from django import forms from … -
Error trying to access field of a form using form.cleaned_data
I need to test some things related to my models and forms, so I open the shell using python3 manage.py shell, and I import the model and the form correctly and take a random model and put it in a variable(c1) so I do: form = AvalForm(c1) after this: form.is_valid() When I run this at first time its return the error: AttributeError: 'Avaliacao' object has no attribute 'get' But when I run .is_valid again its ok, return True and I go to the next pass... I run form.fields and its return all fields of the form correctly, until here all seems ok... But when I try to take an specified field using form.cleaned_data['avaliador'] I have: > Traceback (most recent call last): File "<console>", line 1, in > <module> KeyError: 'avaliador' But the field appears when I type form.fields ... Well lets to codes: models.py from django.db import models from jsonfield import JSONField from site_.settings import MEDIA_ROOT from django.core.validators import MaxValueValidator class Criterio(models.Model): label = models.CharField(max_length=100) def __str__(self): return self.label class Candidato(models.Model): name = models.CharField(max_length=100) e_mail = models.EmailField(max_length=100, default = '') github = models.URLField(default = '') linkedin = models.URLField(max_length=100, default = '') cover_letter = models.TextField(default = '') Ensino_superior = models.BooleanField(default = … -
exposing container ports for django application
My django application works fine when I run it locally but it doesn't work when I run it on a container. Is it a port problem? When I run it as a local application (without docker) I point it to localhost:8000/polls and it works like a charm. But I get "The localhost page isn’t working localhost didn’t send any data. ERR_EMPTY_RESPONSE" when I run the container. The application is pretty much verbatim from the Django tutorial at https://docs.djangoproject.com/en/1.10/intro/tutorial01/ O/S Windows 10 Python 3.6 Docker 17.03.0-ce Dockerfile: FROM python:3.6 EXPOSE 8000 COPY ./ /usr/src/ RUN pip install -r /usr/src/requirements.txt RUN pip install /usr/src/django-polls/dist/django-polls-0.1.tar.gz CMD python /usr/src/toplevel/manage.py runserver Running the Container (no visible problems): C:\temp\djangopoc>docker run -p 8000:8000 -t django-polls Performing system checks... System check identified no issues (0 silenced). March 21, 2017 - 01:05:05 Django version 1.10.6, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Troubleshooting info? (notice the port says 0.0.0.0:8000) problem?: C:\temp\djangopoc>docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d28b7c336664 django-polls "/bin/sh -c 'pytho..." About an hour ago Up About an hour 0.0.0.0:8000->8000/tcp xenodochial_boyd In case it's helpful to diagnose, Build Instructions and output: C:\temp\djangopoc>docker build -t django-polls:latest . Sending build context … -
Django: Processing form data in views.py
I have this form for users to enter their zip code and the radius they would like to search: class DistanceFilter(forms.ModelForm): distance = forms.IntegerField() class Meta: model = Event fields = ['zipcode'] views.py: def event_list(request): advanced = EventFilter(request.GET, queryset=Event.objects.all()) distance = DistanceFilter(request.POST or None) results = [] if request.method == 'POST': form = DistanceFilter(request.POST) if form.is_valid(): distance = form.cleaned_data['distance'] zipcode = form.cleaned_data['zipcode'] for obj in Event.objects.all(): number = check_distance(zipcode, obj.latitude, obj.longitude) if number <= distance: results.append(obj.title) new = Event.objects.filter(title__in=results) Here is the check_distance function that is used on line 8: import requests from geopy.distance import vincenty #takes in the zip code and finds the latitude and longitude def find_coordinates(zipcode): url = "https://gist.githubusercontent.com/erichurst/7882666/raw/5bdc46db47d9515269ab12ed6fb2850377fd869e/US%2520Zip%2520Codes%2520from%25202013%2520Government%2520Data" r = requests.get(url, stream=True) for line in r.iter_lines(): if line[0:5] == str(zipcode): coords = { 'lat': line[6:15], 'lon': line[17:] } break return coords #takes in the zip code the user entered and compares it to each Event in the database def check_distance(user_zipcode, event_lat, event_long): coords = find_coordinates(user_zipcode) user_lat = coords['lat'] user_long = coords['lon'] user = (user_lat, user_long) event = (event_lat, event_long) return vincenty(user, event).miles I think that the issue is in the views.py file. I have tested check_distance() and it works fine, but when I try to use … -
Django: how can I put url() as a guaranteed last element of `urlpatterns` list?
I have a web app (django for backend, reactjs for frontend) with urlpatterns: urlpatterns = [ # API Notifications url(r'^api/notification/v0/', include(notification_router.urls)), url(r'^api/notification/v0/mark_all_as_read/$', mark_all_as_read), url(r'^api/notification/v0/unread_count/$', unread_count), # etc ] Next, because this is react app, I set url pattern to catch and redirect all request (exclude useful) to root template with react router: urlpatterns += url(r'', cache_page(settings.PAGE_CACHE_SECONDS)(RootView.as_view()), name='customer-root'), And on local server it pretty work. BUT, when I try to deploy this app, few another processes (collectstatic, for example) change urlpatterns and add new urls to the end of urlpatterns list (after customer-root url). So, instead static files (css / js / etc) client get html code of customer-root view template. Question is: how can I put my customer-root url pattern as a guaranteed last element of urlpatterns list? Even if another process will change urlpatterns at deploy time.