Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Crispy form error with foreign-key, which I get from queryset.
This is an issue I am having while using Django crispy form. Following is the model field (showing only the necessary codes)" class Product(models.Model): name=models.CharField(max_length =200) unit = models.ForeignKey(Unit,related_name='product_master_master_unit') manufacturer=models.ForeignKey(Manufacturer,related_name='product_master_master_manufacturer') tenant=models.ForeignKey(Tenant,related_name='product_master_user_tenant') objects = TenantManager() Now, this is my form which I've used before using crispy-form. I've to query only those fields, which are specific to current tenant. That is done according to the following: class ProductForm(forms.ModelForm): def __init__(self,*args,**kwargs): self.tenant=kwargs.pop('tenant',None) super (ProductForm,self ).__init__(*args,**kwargs) # populates the post self.fields['unit'].queryset = Unit.objects.for_tenant(self.tenant).all() self.fields['manufacturer'].queryset = Manufacturer.objects.for_tenant(self.tenant).all() class Meta: model=Product exclude =('slug', 'tenant') This works fine if I don't use crispy form. However, on using crispy form the error I get is that the foreign-key field, related to Unit and Manufacturer (which are being queried for specific tenant) is not showing any option in the crispy form. Is there any way I can actually show that in crispy form, or do I have to abandon this crispy form altogether? Just for helping you out, I'm doing in my form what one could do with django's "ForeignKey.limit_choices_to" , if it allowed dynamic selection. Any help would be greatly appreciated. -
django-extensions graph_models returns "no such option"
Django 1.7 django-extensions installed and configured pygraphviz installed When attempting to run graph_models it always fails with manage.py: error: no such option: Example: python manage.py graph_models -a -g -o django_schema.png Usage: manage.py graph_models [options] Creates a GraphViz dot file for the specified app names. You can pass multiple app names and they will all be combined into a single model. Output is usually directed to a dot file. manage.py: error: no such option: -a -
How to add tags to the multiple models using Django-taggit
I want to add same tags to the multiple models (such as Article, Product, supplier, etc.) using Django-taggit. There is a similar question ask in following google group but no solution yet. https://groups.google.com/forum/#!topic/django-taggit/bQ0-7Q53oII The idea is to access all the related objects (such as Article, Product, supplier, etc.) for a given tag. Please, can someone provide an elegant solution to this problem? -
AttributeError: '__proxy__' object has no attribute 'regex'
My urls.py looks like this; can anyone explain where the error (AttributeError: 'proxy' object has not attribute 'regex') is coming from? Because the error message isn't giving me any place where the error is coming from, so I'm really confused. Thanks! from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.core.urlresolvers import reverse_lazy #from django.views.generic.simple import direct_to_template from django.views.generic import TemplateView from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r"^$", TemplateView.as_view(template_name = "homepage.html")), reverse_lazy("homepage.html"), url(r'^grappelli/', include('grappelli.urls')), # grappelli URLS url(r"^admin/", include(admin.site.urls)), url(r"^account/", include("account.urls")), # url(r"^search/", include("haystack.urls")), # WIBO URLs url(r'^cards/', include('cards.urls')), url(r'^contacts/', include('contacts.urls')), url(r'^invoice/', include('invoice.urls')), url(r'^employee/',include('employee.urls')), url(r'^sapub/request/$', 'wibo.views.sapub_request', name='jobrequeseturl'), url(r'^wibo/logout-all-users/$', 'wibo.views.logout_all_users', name='logoutallurl'), url(r'^wibo/cardmigrationextra00091/$', 'wibo.views.cards_migration_extras_0009_1', name='cardsmigrationextra0009url'), url(r'^wibo/cardmigrationextra00092/$', 'wibo.views.cards_migration_extras_0009_2', name='cardsmigrationextra0009url'), url(r'^wibo/cardmigrationextra00093/$', 'wibo.views.cards_migration_extras_0009_3', name='cardsmigrationextra0009url'), url(r"^reports/", include('reports.urls')), #url(r"^printsmart/$",direct_to_template,{"template":"printsmart_request.html"}, name="printsmarturl"), url(r"^printsmart/$", TemplateView.as_view(template_name="printsmart_request.html")), url(r'^select2/', include('django_select2.urls')), ) urlpatterns += staticfiles_urlpatterns() #reverse(urlpatterns) -
The filename, directory name, or volume label syntax is incorrect error while creating virtual environment
Why am I getting "The filename, directory name, or volume label syntax is incorrect." error on windows 7 while creating the virtual environment using mkvirtualenv.To be more specific am using following command from command prompt. mkvirtualenv "D:\Folder_A\Folder_B\Folder_C\My_VE" I have tried following also mkvirtualenv "D:\\Folder_A\Folder_B\Folder_C\My_VE" -
How do i include the csrf_token to dropzone Post request (Django)
So im getting a 403 Forbidden when submitting the POST request through dropzone.js to django.Django displayed the message saying that I didnt include the CSRF token, but I don't know how to actually include it if im not using a form in the HTML. document_form.html {% extends 'base.html' %} {% load staticfiles %} {% block title %}Add files{% endblock %} {% block files %} <div class="container-fluid" id="container-dropzone"> <div id="actions" class="row"> <div class="col-lg-7"> <span class="btn btn-success file-input-button"> <i class="glyphicon glyphicon-plus"></i> <span>Add files...</span> </span> <button type="submit" class="btn btn-primary start"> <i class="glyphicon glyphicon-upload"></i> <span>Start upload</span> </button> <button type="reset" class="btn btn-warning cancel"> <i class="glyphicon glyphicon-ban-circle"></i> <span>Cancel upload</span> </button> </div> <div class="col-lg-5"> <!-- file processing state --> <span class="fileupload-process"> <div id="total-progress" class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"> <div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div> </div> </span> </div> </div> <div class="table table-striped files" id="previews"> <div id="template" class="file-row"> <div> <span class="preview"><img data-dz-thumbnail></span> </div> <div> <p class="name" data-dz-name></p> <strong class="error text-danger" data-dz-errormessage></strong> </div> <div> <p class="size" data-dz-size></p> <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"> <div class="progress-bar progress-bar-success" style="width:0%" data-dz-uploadprogress> </div> </div> </div> <div> <button class="btn btn-primary start"> <i class="glyphicon glyphicon-upload"></i> <span>Start</span> </button> <button data-dz-remove class="btn btn-warning cancel"> <i class="glyphicon glyphicon-ban-circle"></i> <span>Cancel</span> </button> <button data-dz-remove class="btn btn-danger delete"> <i … -
Should I use geodjango over Django?
My goal: build a web application that provides map visualization of large data, entirely in Python. I have little experience in web frameworks, but I'm decent on the data side of things. I have seen a lot of rep for Django and it looks great. Geodjango seems promising, however my current backend is Apache Solr. I have seen haystack which supposedly provides the interface between geodjango and solr (I think). However when I looked at it, it seemed it was just building queries for me to relay to solr. I can do that just fine with other libraries. My question is, if I would like to manually handle my own Solr interface, is GeoDjango going to do anything for me that Django cant? I haven't started working on the application and want to make sure I know what my tools are going to do for me before hand. I'm open to suggestions as well as long as my constrains are met (Python/Solr). -
How to get groups list for slack user with Slacker Python library
Hello I'm trying to get Instant messages history from slack chanel so I cant get team user JSON list by this: def verifyToken(request): print 'verifyToken' body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) token = body_data['token'] slack = Slacker(token) response = slack.users.list() data = {'token':response.body['members']} return JsonResponse(data) But this method doesn't work groups list so then I'm doing this: def getChannelHistory(request): print 'verifyToken' body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) token = body_data['token'] slack = Slacker(token) response = slack.groups.list() data = {"res":response.body['groups']} return JsonResponse(data) I'm getting this error: Error: missing_scope But due to Slack api this should be 'groups' key here the library I'm using : https://github.com/os/slacker -
SMTP connection timeout in Sentry
I'm using Sentry to monitor a Django app. I copied the following (correct and tested) email settings from the Django app to my Sentry config file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_HOST_USER = 'info@ookmijnbedrijf.nl' EMAIL_HOST_PASSWORD = '***' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_USE_TLS = False SERVER_EMAIL = EMAIL_HOST_USER Everything looks right on the SMTP Settings page, but when I try to send a test email I get this: Connection unexpectedly closed: timed out My Django app is sending emails correctly with these exact settings. What am I doing wrong? -
Get checkbox value in django
I have passed a python list (list_exp) in my html template and now i would like to get the result of my multiple checkbox in view.py with a dictionary. {list_exp[0] : True/False, list_exp[1] : True/False.....} <form action="" method="post"> {% for name in list_exp%} <input type="checkbox" name="{{name}}"><label> Experiment : {{name}}</label> <br> {% endfor %} <input type="submit" value="Submit"> </div> </form> -
django not getting the online parameter when submitting a form
I submit a form with two inputs to search a table. My code doesn't get the value of 'namequery' instead of displaying all data in table. What did I do wrong here? Thanks for any help! The url is http://..../chinook/search/?namequery=rand&affquery= search.html <h3 class="labs-background-title">Search results for <em id="search-name">{{ namequery }}</em>:</h3> {% if object_list %} {% for obj in object_list %} {{ obj.lname }} <br /> {{ obj.clustering }} <br /> {% endfor %} {% else %} <h3>No matches found.</h3> {% endif %} views.py class SearchView(generic.ListView): model = Pitable template_name = 'chinook/search.html' def get_queryset(self): try: namequery = self.kwargs['namequery'] except: namequery = '' if (namequery != ''): object_list = self.model.objects.filter(lname = namequery) else: object_list = self.model.objects.all() return object_list The return page display all data, shows the {{namequery}} is empty. Thanks! -
How to make two django projects share the same database
I need to make two separate Django projects share the same database. In project_1 I have models creating objects that I need to use in project_2 (mostly images). The tree structure of project_1_2 is: project_1/ manage.py settings.py project_1_app1/ ... ... project_2/ manage.py settings.py project_2_app1/ ... ... Which is the best approach? -
A django-leaflet map in a form is not shown
I try to add my form into an admin panel. I already have django-leaflet and it works normal via LeafletGeoAdmin. But I need to add my form without a model. I define a form: from leaflet.forms.fields import PointField as PointFieldLL from django import forms class MarkerPostForm(forms.Form): user_from = forms.CharField(label="User, marker's owner") content = PointFieldLL() A view: @csrf_exempt @alt_login_required def post_marker_from_admin(request, v=None, user=None): if user.is_staff is False: return response_message('You are not admin', 403) if request.method == 'POST': form = MarkerPostForm(request.POST) if form.is_valid(): content = form.cleaned_data['content'] user_from = form.cleaned_data['user_from'] data = { "us_from": user_from, "marker": content} return response_json(data, 200) else: form = MarkerPostForm(initial={'user_from': 'spont'}) return render(request, 'send_message_from_admin.html', {'form': form}) An extension of admin template: {% extends "admin/base_site.html" %} {% load i18n admin_static %} {% load static %} {% load leaflet_tags %} {% block title %}Post marker{% endblock %} {% block extrahead %} {% leaflet_js plugins="ALL" %} {% leaflet_css plugins="ALL" %} {% endblock %} {% block content %} <!-- <body> --> <form action="{% url 'manage_app.views_manage_app.post_marker_from_admin' v='v1.0' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Post marker" /> </form> <!-- </body> --> {% endblock %} <!-- </html> --> Result: I see my form, but leaflet map is not shown. Could you tell … -
Django __str__ function on many to one field is not returning the correct output
I'm trying to define str function for models A and D for the purpose having human readable text in the admin site. The problem is in model D's str function where str will return a many_to_one related field and it does not return the format as intented. class A(models.Model): b = models.CharField(max_length = 32) c = models.CharField(max_length = 32) def __str__(self): return '%s %s' % (self.a, self.b) class D(models.Model): e = models.ForeignKey(A) def __str_(self): return '%s %s' % (self.e.b, self.e.c) -
'module' object has no attribute 'Form'
I'm getting an error when I run this code that states: "AttributeError: 'module' object has no attribute 'Form'. This error is specifically talking about the Form mentioned in 'class GetJobSearchForm(forms.Form). from django import forms from django_select2 import * from django.db.models import Q from cards.models import JobCard from contacts.models import Contact from django.core.exceptions import ValidationError def validate_fail_always(value): raise ValidationError(u'%s not valid. Infact nothing is valid!' % value) ########### Forms ############## class GetJobSearchForm(forms.Form): jobs = ModelSelect2MultipleField(queryset=JobCard.objects, required=False, label='By Job') class GetClientSearchForm(forms.Form): clients = ModelSelect2MultipleField(queryset=Contact.objects, required=False, label='By Contact') class GetInvSearchForm(forms.Form): inv = ModelSelect2MultipleField(queryset=Contact.objects, required=False, label='By Inv No') I already tried changing it to forms.ModelForm, but the error just changed to say that there was no attribute 'ModelForm' Thanks for your help! -
Django PermissionError, during upload file
I have a model: class Provider(models.Model): name = models.CharField(max_length=256, verbose_name=_("Name")) favicon = models.ImageField(upload_to="providers/", null=True, blank=True) And in settings: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "../media") And in apache config I have: #rest of code... Alias /media/ /home/sever/ap/media/ <Directory /home/server/ap/media> Require all granted </Directory> But when I 'm trying add record to this model by admin pag, when I add an images I get the error: PermissionError at /admin/ap/provider/add/ [Errno 13] Permission denied: '/home/server/ap/media/providers/Samsung.png' -
Export a django model in .xls
How can I export a whole model filled with data (around 15 columns and 2500 rows) into an excel file to download it directly with a button in a html page? This is my model: class Cleartobill(models.Model): soss = models.CharField(max_length=60) soss_line = models.CharField(max_length=70) build_date = models.CharField(max_length=80) ctb_Status = models.CharField(max_length=60) ctb_comment = models.CharField(max_length=50) comments = models.CharField(max_length=200) sjz_status = models.CharField(max_length=60) production_result_Code = models.CharField(max_length=70) bu = models.CharField(max_length=50) pf = models.CharField(max_length=50) current_fcd = models.DateField(null=True, blank=True) tan = models.CharField(max_length=50) eta = models.CharField(max_length=60, null=True, blank=True) tied = models.CharField(max_length=30) otm_status = models.CharField(max_length=30) bucket_aged = models.CharField(max_length=60) ead = models.DateField(null=True, blank=True) -
Redirect to existing view when getting error (404, 500, etc) django
When my cookie session expires it gives 500 error and I would like to redirect it to the login. I've added the url to override 500 handler. myapp/urls.py handler500 = 'myapp.login.views.signin' But this alone doesn't work. So I tried adding the function server_error: myapp/urls.py handler500 = 'myapp.login.views.server_error' myapp/login/views.py def server_error(request, template_name='templatename.html'): try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseServerError('<h1>Server Error (500)</h1>') return http.HttpResponseServerError(template.render(Context({}))) myapp/login/templates templatename.html Why doesn't it work? -
Django register token for apns
I am beginner in Django and I am using this for device management. https://github.com/jleclanche/django-push-notifications But it doesn't explain how can I post device token. How can I post if user hasn't login or already login? I saw url for that but I don't know how to use. ^ ^device/apns/$ [name='apnsdevice-list'] ^ ^device/apns\.(?P<format>[a-z0-9]+)/?$ [name='apnsdevice-list'] ^ ^device/apns/(?P<registration_id>[^/.]+)/$ [name='apnsdevice-detail'] ^ ^device/apns/(?P<registration_id>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='apnsdevice-detail'] ^ ^device/apns/$ [name='apnsdevice-list'] ^ ^device/apns\.(?P<format>[a-z0-9]+)/?$ [name='apnsdevice-list'] ^ ^device/apns/(?P<registration_id>[^/.]+)/$ [name='apnsdevice-detail'] ^ ^device/apns/(?P<registration_id>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='apnsdevice-detail'] ^device/apns/?$ [name='create_apns_device'] -
Generate pdf files with Weasyprint, save in zip file, send that zip file to client and present it for download
Let me break down my requirement. Here's what I'm doing right now. 1. Generate PDF files from HTML for this I'm using Weasyprint as following: lstFileNames = [] for i, content in enumerate(lstHtmlContent): repName = 'report'+ str(uuid.uuid4()) + '.pdf' lstFileNames.append("D:/Python/Workspace/" + repName) HTML(string=content).write_pdf(target=repName, stylesheets=[CSS(filename='/css/bootstrap.css')]) all files names, with paths, are saved in lstFileNames. 2. Create a zip file with pdf files generated by weasyprint for this I'm using zipfile zipPath = 'reportDir' + str(uuid.uuid4()) + '.zip' myzip = zipfile.ZipFile(zipPath, 'w') with myzip: for f in lstFileNames: myzip.write(f) 3. Send zip file to client for download resp = HttpResponse(myzip, content_type = "application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip' 4. Open file for downloading via Javascript var file = new Blob([response], {type: 'application/x-zip-compressed'}); var fileURL = URL.createObjectURL(file); window.open(fileURL); Problems 1. While the zip file is successfully received at front end, after I try to open it, it gives the following error: The archive is in either unknown format or damaged Am I sending the file wrong or is my Javascript code the problem? 2. Is there a way to store all pdf files in list of byte arrays and generate zip files with those byte array and send it to the client? … -
How can be shown manyTomany field values into a single text box in django template
I want to show manytomany field value into a single input textbox in django template. My output is ABC /n Abc /n BVC /n i want like ABC ,Abc,BVC my code sample is this <div class='col-sm-8'> {% for car in cars %}<br/> <input type='text' class='form-control' name='cars' placeholder='Select cars' value= {{car}}> {% endfor %} </div> I want to show the output in Textbox field -
How to use SearchVector with multiple fields from a list of strings
I don't have a lot of Python experience and can't figure out how to use a list of strings with the SearchVector functionality described here. I'm using Django 1.10 with PostgreSQL 9.6 and have verified that this works if I write the fields in manually. This function is from a class based view and its purpose is to receive a string from a form, then do a full text search against all CharFields in all Models within MyApp, then return the results (planning on using itertools to combine multiple QuerySets once I get this working). I don't want to hardcode the fields because we will be adding new objects and new fields regularly - its a sort of corporate middleware app where I am not able to master the data. def get_queryset(self): searchTargets = defaultdict(list) myModels = (obj for obj in apps.get_models() if obj._meta.label.startswith('myapp') and not obj._meta.label == 'myapp.ConfigItem') for thing in myModels: fieldNames = (x.name for x in thing._meta.fields) for thisField in fieldNames: if thing._meta.get_field(thisField).get_internal_type() == 'CharField': searchTargets[thing._meta.object_name].append(thisField) user_query=self.request.GET['user_query'] for key in searchTargets.iterkeys(): targetClass=class_for_name('myapp.models',key) results = targetClass.objects.annotate( search=SearchVector(searchTargets[key]), ).filter(search=user_query) #only a single QuerySet will be returned. return results I've tried ','.join(MyList) but of course that just makes one big … -
How to filter latest objects using nested query in Django
I have the following relation: class Product(foo): name = models.CharField() class Maintenance(foo): product = models.ForeignKey(Product, related_name="maintenances") start = models.DateField() end = models.DateField() I would like to filter all products with the latest (only the latest) maintenance object having start and end attributes in a given date range. Something like this: Product.objects.filter(maintenances__last__end__gte=today.now(), maintenances__last__end__lte=today.now()+datetime.timedelta(days=30)) -
uwsgi django1.3.5 error: "is outside repository"
my application suffered fatal errors, all of the search engines can not find some answer. Please somebody help me. Thank u. My application run with uwsgi, some fatal error appear in uwsgi log,whenever 'HARAKIRI' triggered or not, always have something like flow: Wed Sep 27 01:17:57 2016 - HARAKIRI !!! worker 25 status !!! Wed Sep 27 01:17:57 2016 - HARAKIRI [core 0] 149.202.48.192 - GET /problem/17800 since 1474391873 Wed Sep 27 01:17:57 2016 - HARAKIRI !!! end of worker 25 status !!! fatal: '/home/workspace/ENV/lib/python2.7/site-packages/django_mysqlpool/backends/mysqlpool/base.py' is outside repository fatal: '/home/workspace/ENV/lib/python2.7/site-packages/sqlalchemy/pool.py' is outside repository fatal: '/home/workspace/ENV/lib/python2.7/site-packages/sqlalchemy/pool.py' is outside repository fatal: '/home/workspace/ENV/lib/python2.7/site-packages/sqlalchemy/pool.py' is outside repository fatal: '/home/workspace/ENV/lib/python2.7/site-packages/django/core/handlers/base.py' is outside repository fatal: '/home/workspace/ENV/lib/python2.7/site-packages/django/contrib/auth/decorators.py' is outside repository fatal: '/home/workspace/ENV/lib/python2.7/site-packages/search/SearchService.py' is outside repository I don't know how and why something like this, but application is not affected. The flow is my uwsgi conf: <uwsgi> <socket>:3344</socket> <pidfile>/home/nb/staticfiles/pids/chunyu-uwsgi.pid</pidfile> <master/> <chdir>/home/nb/webapps/propellant</chdir> <pythonpath>/home/nb/webapps/propellant</pythonpath> <module>wsgi</module> <!-- 3s的timeout, 防止work执行某个任务耗费太多的时间 --> <harakiri>4</harakiri> <workers>4</workers> <listen>8192</listen> <enable-threads/> <logto>/home/nb/logs/xxoo/chunyu_uwsgi.log</logto> <daemonize>/home/nb/logs/xxoo/chunyu_uwsgi.log</daemonize> <memory-report/> <buffer-size>35535</buffer-size> <post-buffering>1</post-buffering> <reload-on-as>1200</reload-on-as> <reload-on-rss>750</reload-on-rss> </uwsgi> -
(Django) page showing \u200e code. (PROVIDING GOOD INFO I've been stuck for a VERY long time)
Hey guys I am beyond frustrated/exhausted trying to fix this unicode code \u200e showing in my web page. I tried everything I can think of. Here is what my page looks like, its data scraped articles from news.google.com and shown on my page with the time submission (the time submission is where the \u200e pops up everywhere) http://i.imgur.com/lrqmvWG.jpg I am going to provide my views.py, my articles.html (the page in the picture that is set up to display everything), and header.html (for whatever reason. But this is the parent template of articles.html for the CSS inheriting). Also, I researched and know that the \u200e is a left-to-right mark and when I inspect the source in news.google.com, it pops up in the time submission element as &lrm; like so: <span class="al-attribution-timestamp">&lrm;51 minutes ago&lrm;</span> I tried editing the views.py to encode it using .encode(encoding='ascii','ignore') or utf-8 or iso-8859-8 but it still displays \u200e everywhere. I put it in so many different parts of my views.py too even right after the for loop (and right before it gets stored as data in the variable "b" and its just not going away. What do I need to do? Views.py def articles(request): """ Grabs the …