Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a Semantic UI div inside a handlebars template
I'm trying to put a Semantic UI component inside a handlebars template like this: {% verbatim myblock %} <script id="texts_template" type="x-tmpl-mustache"> {{#each loaded_texts}} <div class="ui accordion"> <div class="title"> <i class="dropdown icon"></i> {{this.[0]}} </div> <div class="content"> <p class="transition hidden">{{this.[1]}}</p> </div> </div> {{/each}} </script> {% endverbatim myblock %} So for each loaded_texts (an array sent from Django), I want to create a Semantic accordion containing some information about it. The accordion shows up and has {{this.[0]}} as its title, but nothing happens when I click it. If i put the accordion in my main html file, it works as intended (but of course I can't access the variables from loaded_texts). Anyone know a solution to this? -
heroku django channel app runs perfectly fine for sometime and then keeps giving 503 error
I am following this article - https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django Has it something to do with the fact that I have only one worker running (free tier) heroku ps:scale web=1:free worker=1:free as suggested in the article ? So now it is up again..and I guess it will go down again.. -
Custom Validation Error Message using Django Rest Framework
Default validation error message given by DRF is a list of key and message. What would be the best way customise this format to a text format. For Example. This is the default format. { "message": { "phone": [ "customer with this phone already exists." ], "email": [ "customer with this email already exists." ], "tenant_id": [ "customer with this tenant id already exists." ] }, "success": false, "error": 1 } This is something what I want. { "message": "customer with this phone already exists, customer with this email already exists, customer with this tenant id already exists" "success": false, "error": 1 } -
Regular Expression on Django doesn't work
I'm relatively new to Django so I am doing this tutorial, but I encountered a problem with regular expressions: For this view def viewArticle(request, month, year): text = "Displaying articles of : %s/%s"%(year, month) return HttpResponse(text) I am supposed to create a url like that url(r'^articles/(\d{2})/(\d{4})', 'viewArticles', name='articles') and it works perfectly, for example when I enter http://.../articles/12/2014 I get "Displaying articles of: 12 / 2014", as I should. However, later (on page 27 of the PDF) I am advised to change the url to this: url(r'^articles/(?P\d{2})/(?P\d{4})', 'viewArticles', name='articles'), and now it doesn't work anymore. Why could that be and how can I change my code? Thanks for any suggestions! -
Django: sort by fields and properties at the same time
I need to order a list of instances of a particular model in a very specific way using three different model fields and a property: field1 > field2 > property > field3. If they were just fields I could just do the usual: queryset.order_by('field1', 'field2', 'field3') But since I am introducing a property, I just cannot use it in order_by. So what I need to do to enforce that order is ordering and grouping by each attribute and appending to the resulting list in a very ugly way: lst = list(queryset) sorted_list = [] # sort and group by field1 sorted_by_field1 = sorted(lst, key=attrgetter('field1')) for field1, field1_grp in groupby(sorted_by_field1, key=attrgetter('field1')): # sort and group by field 2 sorted_by_field2 = sorted(list(field1_grp), key=attrgetter('field2')) for field2, field2_grp in groupby(sorted_by_field2, key=attrgetter('field2')): # sort and group by property sorted_by_prop = sorted(list(field2_grp), key=attrgetter('property')) for prop, prop_grp in groupby(sorted_by_prop, key=attrgetter('property')): # final step: sort by the last involved attribute and extend the result list sorted_list.extend(sorted(list(prop_grp), key=attrgetter('field3'))) As you can see this is a really obtuse of ordering the original list, but I just cannot see an alternative. Is there any clean way I could do this? -
ContentFile not saved in Django model FileField
I have a problem when saving Strings as file in my Django models, as whenever I try to get the data back, it gives me a ValueError ("attribute has no file associated"). Here's the details: MODEL: class GeojsonData(models.Model): dname = models.CharField(max_length=200, unique=True) gdata = models.FileField(upload_to='data') def __str__(self): return self.dname CODE THAT SAVES THE DATA: cf = ContentFile(stringToBeSaved) gj = GeojsonDatua(dname = namevar, data = cf) gj.save() CODE THAT TRIES TO READ THE DATA: def readGeo(data): f = GeojsonData.objects.all().get(id=data.id).gdata f.open(mode ='rb') geo = f.read() return geo TRACEBACK: File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python\Python36-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "C:\app\views.py" in mapa 80. geostr = app.readGeo.readGeo(d) File "C:\app\readGeo.py" in readGeo 6. f.open(mode ='rb') File "C:\Python\Python36-32\lib\site-packages\django\db\models\fields\files.py" in open 80. self._require_file() File "C:Python\Python36-32\lib\site-packages\django\db\models\fields\files.py" in _require_file 46. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) Exception Type: ValueError at /app/map/1 Exception Value: The 'gdata' attribute has no file associated with it. -
How to bind Dafne on a unix socket?
So far, I've used Gunicorn, with this configuration file systemd: [Unit] Description=gunicorn daemon After=network.target [Service] EnvironmentFile=/var/www/user/.envvars User=user Group=www-data WorkingDirectory=/var/www/user ExecStart=/var/www/venv/bin/gunicorn --workers 3 --bind unix:/var/www/user/user.sock config.wsgi:application --env DJANGO_SETTINGS_MODULE='config.settings.production' [Install] WantedBy=multi-user.target And Nginx proxy requests for this unix socket. Trying Daphne, I realized that I can not specify --env DJANGO_SETTINGS_MODULE='config.settings.production' But I specify this variable in asgi.py, on it all is normal. As soon as I ran the gunicorn service, he socket itself was instantly created on which requests from nginx. When I try to do the same trick with Daphne, I get an error: Jun 26 11:48:32 p435061.kvmvps daphne[8447]: ValueError: invalid literal for int() with base 8: '/var/www/user/user.sock' But I can not figure out how to use the unix.sock when I try to run Daphne and create my systemd file -
Display picture in my HTML file with Django Media
I would like to import picture from my Django media folder to my HTML file but it doesn't seems to work up to now. My settings.py file looks like : MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join('/Users/terii/Desktop/Django/Project A', 'Photos_Identifications/') In my HTML file, I have : {% if object.Image %} Methode 1 : <img src="http://localhost:8000/media/pictures/test.jpg"/> #It works <br></br> Methode 2 : <img src="/Users/terii/Desktop/Django/Project A/Photos_Identifications/pictures/test.jpg"/> #It works <br></br> Methode 3 : <img src="{{ MEDIA_URL}}{{object.Image}}"/> #It doesn't work {% endif %} I don't why my Method 3 doesn't work and I would like to know if you had any idea ? I don't want to write the entire path, because it should be dynamic. Thank you :) -
There is a 2006 error( server gone away) continously in my django, why is it?
I don't set the variable CONN_MAX_AGE in my config, it is said it will be 0 as default, which means every request will reopen a new connection.But In my program it continuously shows the error (2006, server gone away) as every query starts.I don't know why. -
Volley set CSRF token in POST header request
I am using django as backend for my android app. I have to make some post request for which i need CSRF token. First I made a get request to backend to get CSRF token, then in next POST request I am using csrf obtained in previous request. I did this by overriding getHeaders method of JSON request. I am still getting csrf verification failed at backend. Is this method wrong? Is there any other way to do it? -
How to integrate python/django project with a webservice that provides api only for php?
I work on a django website. Currently, I need to integrate it with a third-party API that provides only PHP endpoints and some shitty documentation that instructs how to build PHP requests. The API provider introduces a PHP client containing a class that handles requests to PHP API webservice via SOAP. First, is it possible to build python client that will interact with PHP endpoints without knowing server-side trickery of the API provider? Should I dive deeper into PHP client source code and try to rewrite it in python? Second, should I create intermediary PHP webservice that will integrate third-party PHP API and provide a precise API to interact with python client. Is there any better option? P.S. Please, note that I'm new to PHP and SOAP. -
Python LDAP ValueError: option error when using set_option(ldap. OPT_X_TLS_CACERTDIR)
I'm using the django authentication backend django-auth-ldap to authenticate against an LDAP service. When attempting to set the path to the directory containing the ssl certificate; ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs') I get a ValueError exception: File "/Users/liz/web_application/work/ldap_settings.py", line 5, in <module> ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs') File "/Users/liz/.envs/dev/lib/python3.6/site-packages/ldap/functions.py", line 139, in set_option return _ldap_function_call(None,_ldap.set_option,option,invalue) File "/Users/liz/.envs/dev/lib/python3.6/site-packages/ldap/functions.py", line 66, in _ldap_function_call result = func(*args,**kwargs) ValueError: option error I've tried the accepted answer from this previous SO post that suggests uninstalling python-ldap (though I'm using pyldap, a fork of python-ldap) and re-installing using a brew-installed openldap by running: LDFLAGS="-L/usr/local/brew/opt/openldap/lib" CPPFLAGS="-I/usr/local/brew/opt/openldap/include" pip install python-ldap This seemed to have no effect. I also followed this guide, to locally build a version of pyldap with the newer version of openldap (via brew), but I still see the same error. I'm not sure if there's some way I can verify my local build does use the newer openldap library, or if there's something I'm missing here? Any suggestions are much appreciated! Other existing questions on SO The answer to this question has no effect for me; setting AUTH_LDAP_GLOBAL_OPTIONS instead of set_option results in the same ValueError AUTH_LDAP_GLOBAL_OPTIONS = {ldap.OPT_X_TLS_CACERTDIR: '/etc/ssl/certs'} -
How to print log to file under Django Python
I am new to python and Django, so if you can provide a solution with more details and explanation that would be great. I am using python 2.7.9, Django <1, 11, 2, u'final', 0> I started a Django project by VS2015. I want to print log to file. I added the following code to settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level':'DEBUG', 'class':'logging.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': "./logfile", 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'MYAPP': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, } } I added the following code to views.py: import logging logger = logging.getLogger(__name__) def hello_world(request): logger.error('Testing error log') return render(request, 'hello_world.html', { 'current_time': str(datetime.now()), }) The problem is that a file named logfile is generated but there is nothing inside the file. -
In my project I execute python manager.py runserver cause socket.error [Errno 2] No such file or directory in Django1.7
there is my manager.py enter image description here I use MacOS I did't find the same question when I use Ubuntu there is the Exception information enter image description here I tried to use dos2unix to fix this problem but it didn't work also I tried to modified the #! hash-bang to #!/usr/bin/python but it didn't work neither -
retrieve values from dynamically generated form fields using jquery on django framework
I am currently developing a site that helps families purchase and install renewable energy with little professional advice. The idea is to get the list of devices and kw ratings of all appliances in there homes. i want the user to be able to click on an add field button and add more devices if the device is not already in my site.. i have this jquery script script on my template <script> $(document).ready(function() { var max_fields = 10; var wrapper = $(".container1"); var add_button = $(".add_form_field"); var x = 1; $(add_button).click(function(){ if(x < max_fields){ x++; $(wrapper).append('<div><input type="number" name="mytext"/><a href="#" class="delete">Delete</a></div>'); //add input box } else { alert('You Reached the limits') } }); $(wrapper).on("click",".delete", function(e){ e.preventDefault(); $(this).parent('div').remove(); x--; }) }); {% block body %} <body> <form method="POST" action="{% url 'submit' %}"> {% csrf_token %} <div class="container1"> <button class="add_form_field" type="button">Add New Field &nbsp; <span style="font-size:16px; font-weight:bold;">+ </span></button> <div><input type="number" name="mytext"></div> </div> <input type="submit" value="submit" /> </form> {% for ayu in allser %} {{ayu}} {% endfor %} {% endblock %} this is my view code which as i thought should return and display values contained in the dynamically generated form fields.. def results(request): if request.POST: return render(request, 'music/solar_calc.html', {'allser': request.POST['mytext']}) else: return … -
After change class function doesn't work
After cut function about comments from ContentDetailView to IndexView I can't run my server and it doesn't work. class IndexView(AllAdsViewMixin, ListView): model = UserContent template_name = 'user_content/list.html' context_object_name = 'usercontent' def get_queryset(self): """Return the last all five published contents""" return UserContent.objects.filter(state='1').order_by('-published')[:5] def get_context_data(self, **kwargs): content_type = self.object.get_content_type initial_data = { 'content_type': content_type, 'object_id': self.object.id, } comment_form = CommentForm(initial=initial_data) comments = Comment.objects.filter( content_type=content_type, object_id=self.object.id ) context = super(IndexView, self).get_context_data(**kwargs) context['comments'] = comments context['comment_form'] = comment_form return context def post(self, request, **kwargs): self.object = self.get_object() content_type = self.object.get_content_type comment_form = CommentForm(request.POST) if comment_form.is_valid(): content_data = comment_form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(parent__id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=self.object.id, content=content_data, parent=parent_obj ) return self.get(request, **kwargs) Error: 'IndexView' object has no attribute 'object' Can someone help me? When function was in class ContentDetailView it works. ContentDetailView class has the same model, template_name and context_object_name. -
Django : Display image with Pisa library
I'm looking for add Pictures in my PDF generated by html2pdf library. Up to now, I don't find a way to do that. My function looks like : @login_required def Generate_PDF(request, id) : personne = get_object_or_404(Individu, pk=id) data = {"personne" :personne} template = get_template('RawFile.html') html = template.render(Context(data)) path = Global_variables.Individu_path.path + filename file = open(path, "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.close() In my RawFile.html, I add : <body> <img class="logo" src="{% get_static_prefix %}{{ mytheme }}/images/logo.jpeg" /> <h2 align="center"> <font size="6"> Fiche d'Identification - INDIVIDU</font></align> </h2> <br></br> <br></br> {% block content %} {% if personne.Image %} <img src='./19312STRASBOURG-855525.jpg'/> {% endif %} <h3 align="left"> N° Identification {{personne.NumeroIdentification}} </align> </h3> <h3 align="left"> Au nom de {{personne.Prenom}} {{personne.Nom}}</align> </h3> ... </body> How I can add my logo and another picture in my PDF ? I searched different way to do that. None is working. Thank you -
Django Logger vs Logging Middleware
I want to log every request sent to Django. There are some posts online about logging middleware. The Django documentation talks about logger configuration and it seems that I can set it up to log everything without writing middleware. Can I log everything without middleware? What can middleware give me that a well-tuned Django logging config cannot? Can I log INFO level messages, with DEBUG = False and no middleware? How much extra load does logging everything add to my app? -
TypeError: f0() takes 1 positional argument but 9 were given
Suppose i have a list: a=['hello.com','ok.com'] i have two function: def f0(id): try: model.objects.get(links=id) except: model(modelfield=id).save() def f1(request): for i in a: t1=thread.Thread(target=f0,args=(i)) t1.start() While i try to run this on my server , its giving me error . TypeError: f0() takes 1 positional argument but 9 were given Kindly tell me whats the problem . -
Which JS framework has good integration with Django(python)/Django-Rest-Framework
I'm a backend developer in Python/Django. I work in a small company, so I gave out a full-stack project. Jquery is not enough (too much code will come out).Found that I need a bunch of DRF (django-rest-framework) + Js framework. My task is to make the board as in screen below and in other section CRM like ADMIN LTE(The wishes of the boss do this in one web application) Which js framework is good for this work (preferably popular), and at the same time works well with the django-rest-framework? -
Django server with heavy data model
I'm trying to figure out how best to implement a calculation heavy data model on a server. Requests need to be handled quickly, and processing should continue on server after the request is answered for the more heavy stuff so users aren't constantly waiting. Should I remain with a pure Django Model for this, or is it better to implement something in C as a daemon, and socket to it? I just need some thread to start from - what's faster, what's considered better to practice, when would you prefer pure Django and when you would need another daemon. Maybe writing a C library with Python interface for a django model? I've been reading on this for a while and have no concrete conclusions on what should I prefer. -
Django PDF Upload Form with django-bootstrap-dynamic-formsets
I'm trying to implement a small django form which gives the user the possibility to upload a PDF file. I just can't figure out what I'm doing wrong. The request.FILES in my view keeps staying empty. My Code looks like this: views.py def traveler_request_edit(request, request_id): context = {} if not Request.objects.filter(id=request_id).exists(): return HttpResponse(status=400) traveler = Traveler.objects.filter(request_id=request_id).values() extra = 0 if len(traveler) else 1 TravelerFormSet = inlineformset_factory(Request, Traveler, forms.TravelerEditForm, extra=extra, can_delete=True) if request.method == 'POST': traveler_formset = TravelerFormSet(request.POST, request.FILES, prefix='traveler', instance=Request.objects.get(id=request_id)) if all([form.is_valid() for form in [traveler_formset]]): for traveler_form in traveler_formset: # Doing special check for possibly empty forms if not traveler_form.cleaned_data: continue traveler = traveler_form.save(commit=False) traveler.request_id = request_id if request.FILES: handle_hotel_confirmation_file(request.FILES['hotel_confirmation']) if not traveler_form.cleaned_data['DELETE']: traveler.save() else: traveler.delete() return HttpResponse("Successfully saved", status=202) else: traveler_formset = TravelerFormSet(prefix='traveler', instance=Request.objects.get(id=request_id)) context['formset'] = traveler_formset context['form_title'] = "Traveler" context['url'] = reverse(traveler_request_edit, args=[request_id]) return render(request, 'travel/form_edit.html', context) forms.py class CustomModelForm(autocomplete_light.ModelForm): def __init__(self, *args, **kwargs): super(CustomModelForm, self).__init__(*args, **kwargs) for field in self.fields.values(): if hasattr(field, "widget"): field.widget.attrs['data-toggle'] = 'tooltip' field.widget.attrs['data-placement'] = 'top' if field.required: field.label += ' *' class TravelerEditForm(CustomModelForm): class Meta: model = Traveler exclude = ['request'] widgets = { 'birthdate': forms.DateInput(attrs={'class': 'birthdate-datepicker', 'placeholder': 'Birthdate'}), 'frequent_traveler': forms.TextInput(attrs={'placeholder': 'Miles&More Card Nr or similar'}), } form_edit.html {% load bootstrap3 %} … -
Take a url pattern as input in django
say i have a variable : a=['https://www.google.com','https://www.go.com','https://www.ogle.com'] i have a Template dome.html: {%for i in a %} <a href=/link/{{a}}>Click</a><br/> {%endfor%} I have views.py as bellow: def someview(request,id): do something with input (id) Now i want to configure my urls.py so that it will communicate with my views.py which take {{a}} as input (id). Kindly help -
How to get Facebook uid on tempate using Social-Auth?
I have been trying to access facebook uid on a django template.Here is my code: <p>Hello {{request.user.social_auth.values_list}} !</p> Which return right result as: (1, 1, 'facebook', '115213032581753666', {'expires': 5099607, 'access_token': 'EAADfh6DasASDASDasdaoAnc6AqKISXmdcZCGasASDASTWyJASD6KHTfArsZBGKASDSAdrasdEiQmRDCtxHalVGf1o0YBeHbII27AwkcyGPuPciWoKLANdhAFQ9UE9ocyEmYG5jYJQx7wf7duwZDZD', 'id': '11521303258175366', 'token_type': None, 'auth_time': 1498449829, 'denied_scopes': None, 'granted_scopes': ['public_profile']}) But I can't parse id parameter from it. How to access id field on template? -
How do we run below celery commands in production server?
celery -A app worker -Q priority_high -B -l debug --purge -n priority_high_worker celery -A app worker -Q default -B -l debug --purge -n default_worker celery -A app beat -l info As of now we are running the three commands in screens. What is more production way of running these commands?