Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"no module named _base" on __init__.py soaplib django 1.10 and python 3.4.3
["no module named _base" on init.py][1] when i run this project with terminal python3 manage.py runserver i have this WARNING: Performing system checks... System check identified some issues: WARNINGS: ?: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. System check identified 1 issue (0 silenced). March 09, 2017 - 09:57:28 Django version 1.7.9, using settings 'intento.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. And i have this probleme when i enter "ImportError at /books No module named '_base' Request Method: GET Request URL: http://127.0.0.1:8000/books Django Version: 1.7.9 Exception Type: ImportError Exception Value: No module named '_base' Exception Location: /usr/local/lib/python3.4/dist-packages/soaplib-2.0.0b2.post0-py3.4.egg/soaplib/core/init.py in , line 3 Python Executable: /usr/bin/python3 Python Version: 3.4.3 Python Path: ['/home/khaled/Bureau/soaplib-django-master', '/usr/local/lib/python3.4/dist-packages/soaplib-2.0.0b2.post0-py3.4.egg', '/usr/lib/python3/dist-packages', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-i386-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages']" can i help me -
django checks csrf only in production?
I am working on an SPA django (DRF)/angular 2. django checks for csrf token only in production server (gunicorn). how to simulate the same check using manage runserver ? -
How to use Python proxy server when getting [Errno 111] Connection refuse
I try to test Odoo Web Service API from Python and everything works fine from localhost using a basic Django app and xmlrpclib. But when I host it at pythonanywhere I get a [Errno 111] Connection refused error. On their help page they describe that ports are closed on free accounts and that their HTTP proxy at proxy.server:3128 has to be used. How to do that? Here is the Django code of my view (yes I know that's bad practice to put html in the view, just for testing): from django.http import HttpResponse import xmlrpclib url = "https://demo3.odoo.com" db = "demo_100_1489044950" username = "admin" password = "admin" #odoo service connection common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url)) uid = common.authenticate(db, username, password, {}) models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url)) products = models.execute_kw(db, uid, password, 'product.template', 'search_read', [[]], {'fields': ['name', 'list_price'], 'limit': 10}) for product in products: print product['id'], product['name'], product['list_price'] def index(request): html = "<html><body><h1>Odoo Products</h1>" for product in products: name = product['name'].encode("utf-8", "strict") html += "<div>"+name+": "+str(product['list_price'])+"</div>" html += "</body></html>" return HttpResponse(html) ps: Source code of Django app is in this github repository -
Django "trans" template tag using wrong language
I have a site using Django 1.10 with German and English as available languages, where German is the source language. Dynamic content is translated with django-modeltranslation and for static strings I am using Django's built-in trans template tag. I want Django to return the page in the visitor's preferred language. I have read how Django discovers language preference carefully several times, and I think I have everything right. As I change my language settings in my browser, the value of the LANGUAGE_CODE variable when displayed in a template always changes accordingly, and also the dynamic content is always returned in the expected language by django-modeltranslation. Also the admin interface and extensions like rosetta and django-debug-toolbar switch their interface language nicely as expected. It's only the trans template tag that is not picking my browser's language preference. Instead, it seems to directly resort to the initial value of the LANGUAGE_CODE variable as it is originally set in the settings file, without going through the algorithm described in the aforementioned link. The locale middleware is of course in place, and so are the *.po and *.mo files as well. The browser request headers also look fine. Because everything except the trans tag … -
Django builtin test client can't find static files provided by jdango-bower?
Django succeeded to find static files provided by django-bower when using python manage runserver, but inside a TestCase, django failed to find those staticfiles: from django.test import TestCase from django.urls import reverse class ExampleTestCase(TestCase): def test_client(self): self.client.post(reverse('test')) The above code will generate exception like this: ValueError: The file 'bootstrap/dist/css/bootstrap.css' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x7fe30824fb10>. Do i need to do some extra configurations for django-bower to work inside django unittest? -
Django - add text beetween modelform fields
How can I add some html text beetween form fields? This is my forms.py: class SiteAddFormFull(forms.ModelForm): url = forms.URLField(widget=forms.TextInput(attrs={'readonly': 'readonly'})) class Meta: model = Site fields = ('url', 'name', 'description', 'keywords', 'group', 'category', 'subcategory', 'category1', 'subcategory1', 'email') def clean(self): cleaned_data = super().clean() subcategory = cleaned_data['subcategory'] subcategory1 = cleaned_data['subcategory1'] if subcategory1 and (subcategory == subcategory1): raise forms.ValidationError("Subcategories can't be the same.") Part of my html file: <form method="post" action="" class="form-horizontal"> {% csrf_token %} {% bootstrap_form form_extended layout='horizontal'%} {% bootstrap_button "Zatwierdź" size='large' button_type="submit" button_class="btn-primary" %} </form> I would like to add description after 'group' field. Something like: You can add site to 2 categories You can add site to 2 subcategories Just normal html text. How can I achieve that? -
Table doesn't exist with Django Chartit raw query
I'm getting a problem with Django Chartit from my views.py file because he doesn't find my table. However this table exists in my MySQL Database. I'm using this module in order to display some graphics in my Django website and it's the first time I'm using it. I have a table which is named Person in my Identity application like this : class Person(models.Model): title = models.CharField(max_length=12,choices=TITLE_CHOICES, verbose_name='Civilité') young_girl_lastname = models.CharField(max_length=30, verbose_name='Nom de jeune fille', blank=True) lastname = models.CharField(max_length=30, verbose_name='Nom de famille') firstname = models.CharField(max_length=30, verbose_name='Prénom(s)') sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe') birthday = models.DateField(verbose_name='Date de naissance') birthcity = models.CharField(max_length=30, verbose_name='Ville de naissance') birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') ..... In my MySQL Database, I have this : mysql> show tables ; +-------------------------------------+ | Tables_in_DatasystemsEC | +-------------------------------------+ | BirthCertificate_birthcertificate | | Configurations_theme | | Identity_monthlyweatherbycity | | Identity_person | | Mairie_mairie | | Recensement_attestation_recensement | | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | django_admin_log | | django_content_type | | django_migrations | | django_session | | log_userprofile | +-------------------------------------+ You have Identity_person as table. In my view, I defined a new function in order to display some statistics graphics … -
Translating text in external js file in Django
The project tree is as follows : In the url.py inside master folder I have next: from django.views.i18n import javascript_catalog ...... js_info_dict = { 'domain': 'djangojs', 'packages': ('traxio.traxio',), } url(r'^jsi18n/$', javascript_catalog, js_info_dict, name='javascript-catalog'), In my base.html file (master/templates/master/base.html) I added : <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> <script src="/static/master/js/custom.js"></script> If I click on page source when page loads I see : <script type="text/javascript" src="/master/jsi18n/"></script> <script src="/static/master/js/custom.js"></script> The custom.js is the file where I need those translations. I did : django-admin makemessages -d djangojs -l nl django-admin makemessages -d djangojs -l fr django-admin compilemessages The files are created in the locale folder. My custom.js is as follows: function contactUs(fullname, telephone, email) { bootbox.dialog({ title: gettext("Limit reached"), message: '<p>gettext(You have reached the limit.)</p>', buttons: { ....... } } }); } But nothing happends. What did I wrong? -
Change form widget in a formset
How can I change a form widget in a model formset from this <tr><th><label for="id_form-2-image">image:</label></th><td><input id="id_form-2-image" name="form-2-image" type="file" /></td></tr> <tr><th><label for="id_form-2-DELETE">Delete:</label></th><td><input id="id_form-2-DELETE" name="form-2-DELETE" type="checkbox" /><input id="id_form-2-id" name="form-2-id" type="hidden" /></td></tr> To something more beutifull? I need only 2 buttons to manage a form: <input type="file"> for uploading; <input type="button"> for deleting form. And not a checknox for deleting. -
Trigger signal when add relation to model
Given the following model, with four instances already created (A, B, C, D) I want to trigger a hook when I add a Company to the instance D. class Foo(models.Model): name = models.CharField() description = models.TextField() company = models.ManyToManyField(Company) I've thought about using a post_save signal but I'm not sure if it's a good approach. -
Access data passed from an url in a view Django Rest Api
I am working with a DRF. I am building a custom function that counts the number of posts of a user hence I not using a class based view. I am not able to access the userid I pass into the url in the view. I have tried the following Urls.py url(r'^count/(?P<userid>[0-9]+)/$', views.Count), Views.py @api_view(['GET', 'POST', ]) def Count(self): userid = self.kwargs['userid'] I get the following error: Count() got an unexpected keyword argument 'userid' This approach works fine for class based views... What am I doing wrong here? -
Django Forms Not adding objects to DB
My View function to handle the form looks like this ==> def login(request): form=Login() if request.method=="POST": form=Login(request.POST)#populate if form.is_valid(): Username=forms.cleaned_data['Username'] Password=request.cleaned_data['Password'] TPerson=Person.objects.create(Username=Username,Password=Password) TPerson.save() else: form=Login() context={ "Login":form, } return render(request,"photos/login.html",context) and My HTML <!DOCTYPE> <html> <body> <form action="/photos/memes.html" method="POST"> {% csrf_token %} <div style="padding-bottom: 10px;" > <span>{{Login}}</span></div> <br/> <input type="submit" value="Submit" /> </form> </body> whenever I click submit the object is not being uploaded to the database -
Correct Way for Celery Process Architecture and demonizing
I have a Python/Django Project running on uwsgi/nginx. For asynchronous task we are using rabbitmq/celeryd and supervisord to manage all the daemons Versions: python: 2.7 django: 1.9.7 celery: 3.1.23 django-celery: 3.1.17 Celery has 10 queue of type Direct (say queue1, queue2, ...) Each queue is handled by a separate celeryd process which is manage via supervisord. each supervisord process looks as following [program:app_queue_worker] command=/var/www/myproj/venv/bin/celery worker -A myproj -c 2 --queue=queue1 --loglevel=INFO directory=/var/www/myproj/ user=ubuntu numprocs=1 autostart=true autorestart=true startsecs=10 exitcodes=1 stopwaitsecs = 600 killasgroup=true priority=1000 Hence Supervisord is running 10 Mainprocess and 20 Worker process Other Thing I have noticed is uwsgi also spawns some celery workers(Dont understand how and why, YET ) with concurrency=2. So if I have 4 uwsgi process running i will have an addition 10 celery workers running All these workers are each taking 200-300M memory? Something is wrong here I feel it but I am not able to put my finger on it. Celery shouldn't be running such memory heavy process? Note: Debug=False, there is no memory leakage due to debug Can someone please comment on the architecture if it is correct or wrong? Would it be better to run 2-3 celery MainProcesses which listen all queues … -
How to implement gmail api access in Django
I am struggling to find a good document/tutorial explaining how to connect to user gmail account using Django. I saw google docs but most of the samples are old an not up to date so not all imports are still valid. My main requirement is that the user will access the page and grant my application permission to look for specific emails. I would appriciate some directions and pointers. -
Django upload form, additional field causing error
There is an issue I'm facing. I need to upload an excel of students containing their related data. I also need to have, as an user-input, the batch of the student. Following are my codes: Views.py def import_student(request): this_tenant=request.user.tenant if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) def choice_func(row): data=student_validate(row, this_tenant, batch_selected) return data if form.is_valid(): data = form.cleaned_data batch_data= data['batch'] batch_selected=Batch.objects.for_tenant(this_tenant).get(id=batch_data) with transaction.atomic(): try: request.FILES['file'].save_to_database( model=Student, initializer=choice_func, mapdict=['first_name', 'last_name', 'dob','gender','blood_group', 'contact', 'email_id', \ 'local_id','address_line_1','address_line_2','state','pincode','batch','key','tenant','user']) return redirect('student:student_list') except: transaction.rollback() return HttpResponse("Error") else: print (form.errors) return HttpResponseBadRequest() else: form = UploadFileForm(tenant=this_tenant) return render(request,'upload_form.html',{'form': form,}) Forms.py class UploadFileForm(forms.Form): file = forms.FileField() batch = forms.ModelChoiceField(Batch.objects.all()) def __init__(self,*args,**kwargs): self.tenant=kwargs.pop('tenant',None) super (UploadFileForm,self ).__init__(*args,**kwargs) # populates the post self.fields['batch'].queryset = Batch.objects.for_tenant(self.tenant).all() self.helper = FormHelper(self) self.helper.add_input(Submit('submit', 'Submit', css_class="btn-xs")) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-2' self.helper.field_class = 'col-sm-4' However, the error, (I'm printing the error) being shown on submitting the form is: <ul class="errorlist"><li>batch<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul> If I remove the batch field, the form is working great. Can anyone help me with this? -
Reactjs and Django Independent Functionality
I am new to django and reactjs and I want to ask if it is possible to make an application that have the following requirements: "Reactjs only care of front-end". No need to import the scripts of reactjs to the templates of Django. Most of the tutorial I read are importing the bundles of Reactjs into the Django templates. "Django handles everything on backend". Django only wait for any request and return response. If you know any blog, tutorials please include it on your answers. Thank you very much! -
NoReverseMatch error Django 1.10
I am new to Django and cant seem to find a solution to my problem I get the following error Reverse for 'todo_list' with arguments '()' and keyword arguments '{'cid': 1}' not found. 1 pattern(s) tried: ['todo/(?P<cid>)/'] 1 {% extends "base.html" %} 2 {% block nav_title %} Company Batches {% endblock nav_title %} 3 {% block content %} 4 <div class="jumbotron"> 5 6 {% for obj in object_list %} 7 <a href={% url 'todo_list' cid=obj.company.id%} class="href-nostyle"> 8 <div class="container"> 9 <div class="jumbotron" style="background:white"> 10 <div class="text-center"> 11 <h1>{{ obj.company }}<br> 12 <small>{{ obj.job }}</small> 13 </h1> 14 </div> 15 </div> 16 </div> 17 </a> This template is located in an app named company_batches and I am attempting to navigate a user to the todo app using an href my url tag is {% url 'todo_list' cid=obj.company.id%} my main urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', home, name='home'), url(r'^batches/', include('company_batches.urls')), url(r'^todo/', include('todo.urls'), name='todo') ] todo/urls.py urlpatterns = [ url(r'^$', ToDoCreateView.as_view(), name='todo_create'), url(r'^(?P<cid>)/', ToDoListView.as_view(), name='todo_list'), ] the relevant views.py class ToDoListView(ListView,): template_name = 'todo/todo_list.html' def get_context_data(self, *args, **kwargs): context = super(ToDoListView, self).get_context_data(*args, **kwargs) return context def get_queryset(self, cid): return ToDoList.objects.filter(company=self.cid) I cant figure out what I'm doing wrong, some guidance would be … -
django allauth's get_package method where property package is
i saw django-allauth source code. class Provider in allauth/socialaccount/base.py has get_package method @classmethod def get_package(cls): pkg = getattr(cls, 'package', None) if not pkg: pkg = cls.__module__.rpartition('.')[0] return pkg i have question where property package is -
Adding item to index: QuerySet no attribute save
I am trying to get a field to be added to my index when it is changed. The code below is updating the index correctly, but actual model does not get updated. Also, I get a traceback error (provided via link at bottom). I get the error: 'QuerySet' object has no attribute 'save'. I have provided the traceback via a link below. # models.py class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) taglevel = models.IntegerField("Tag level", null=True, blank=True) def to_search(self): tags = self.id if tags: queryset = Item.objects.filter(tag=tags) for object in queryset: object.save() return queryset def update_search(instance, **kwargs): instance.to_search().save() class Item(models.Model): title = models.CharField("Title", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) def get_grouped_tags(self): tag = self.tag.order_by('taglevel') grouped_tags = { tag_level: [ { 'name': tag_of_level.name, 'taglevel': tag_of_level.taglevel, } for tag_of_level in tags_of_level ] for tag_level, tags_of_level in groupby(tag, lambda tag: tag.taglevel) } return grouped_tags def to_search(self): d = { "tags": self.get_grouped_tags(), "title": self.title } return ItemIndex(meta={'id': self.id}, **d) def indexing(self): obj = ItemIndex( meta={'id': self.id}, title=self.title, tag=self.get_grouped_tags(), ) obj.save() return obj.to_dict(include_meta=True) def update_search(instance, **kwargs): instance.to_search().save() def remove_from_search(instance, **kwargs): instance.to_search().delete() post_save.connect(update_search, sender=Item) post_save.connect(update_search, sender=Tag) pre_delete.connect(remove_from_search, sender=Item) pre_delete.connect(remove_from_search, sender=Tag) m2m_changed.connect(update_search, sender=Item.tag.through) # search.py class ItemIndex(DocType): title = String() class Meta: index = 'Item-index' def bulk_indexing(): … -
Django and wordpress simultanous logout
I have this project in which user simultaneously login into Django as well as Wordpress accounts. To achieve Simultanous logout, I used Javascript to delete the authentication cookie of Wordpress and thus automatically logging out the user. This works fine as long as user clicks on "logout" button. On clicking logout a Javascript function is called and wordpress cookie is deleted and thus making user logged out of Wordpress and user is logged out of Django by using normal Django functionality. Now the problem occurs when user directly type the logout url "localhost:8000/logout" in address bar, this directly send request to Django server and without involving any JavaScript to delete the Wordpress cookie. How to achieve Wordpress logout in this situation when user directly types the logout url of Django? Note:- Wordpress and Django server are running on same host with different port. -
django model parent model accessing child model field
from django.contrib.auth.models import User User = settings.AUTH_USER_MODEL class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') class Tutor(UserProfile): # tutor_fields here From User object how can I access Tutor? user.profile.?? user.profile.select_related('tutor') does not seem to work -
Can this be achieved through Aggregation?
I have achieved what I want but I'm not convinced it is the best approach. This is my model: class foo(models.Model): user = models.ForeignKey(User) rate = models.PositiveSmallIntegerField(default = 3) rate1 = models.PositiveSmallIntegerField(default = 3) rate2 = models.PositiveSmallIntegerField(default = 3) This is my view: sum = {} bad_rating = None rate = foo.objects.values('user').distinct().annotate(r=Avg("rate"), r1 = Avg("rate1"), r2= Avg("rate2")) for r in rate: sum[r['user']]=r['r']+r['r1']+r['r2'] bad_rating = sorted(sum.items(), key=operator.itemgetter(1)) Basically, I'm getting average of rate, rate1 and rate2 grouped by distinct users. Once I have gained the average of these three fields associated with distinct users, I want to add them all together, and keep the user association. In my case, I have a queryset at the beginning, then I store it in a dictionary, then I store it in a tupple list (because it allows me to order it and gain the lowest rating, or highest rating). Is it possible to achieve the same results through Django Queryset and aggregation? In example: My Queryset result: <QuerySet [{'r': 1.0, 'r2': 3.0, 'user': 16, 'r3': 5.0}, {'r': 4.333333333333333, 'r2': 2.1666666666666665, 'user': 17, 'r3': 5.0}, {'r': 2.0, 'r1': 2.0, 'user': 18, 'r2': 2.0}]> Instead I would like a queryset that would produce the following results: … -
Django get results from multiple rows into a list?
For example, I have the following model: class Author(models.Model): firstname = models.CharField(max_length=30) book = models.CharField(max_length=30) I want to my template to do something that results in the html below. So, for every author with the same first name, it iterate and populate the list with all the books that has the author with that first name. <h3>Author First Name</h3> <ul> <li>Book1</li> <li>Book2</li> <li>Book3</li> </ul> <h3>Author First Name2</h3> <ul> <li>Book4</li> <li>Book9</li> </ul I'm not sure how to build a Django Queryset that would allow me to do this. -
Django imagekit, 'ImageCacheFile' object is not subscriptable when using AWS S3
I have a model which have ImageField, it generates thumbnails by using django imagekit: class Tour(models.Model): image = models.ImageField(blank=True, null=True, upload_to=UploadToPathAndRename("tours")) image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFit(320, 200)], format='JPEG', options={'quality': 60}) The UploadPathAndRename will create new names for uploaded images: @deconstructible class UploadToPathAndRename(object): def __init__(self, path): self.sub_path = path def __call__(self, instance, filename): ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}_{}.{}'.format(instance.pk, datetime.datetime.now().strftime("%Y%m%d%H%M"), ext) else: # set filename as random string filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return os.path.join(self.sub_path, filename) I use Boto3 lib to upload this image to my AWS S3 bucket. I have page where form of image uploading is located. When user uploads it's image corresponding view will redirect to page where this model's image will be shown like this: <a target="_blank" href="{{ tour.image.url }}"> <img src="{{ tour.image_thumbnail.url }}"/> </a> My view where this image is handled looks like this: if request.FILES: tour.image = request.FILES['image'] tour.save() When I choose image and then make POST request from my form to my view, it handles it right and then redirects me to page where image must be shown and it shows me that kind of error: Internal Server Error: /tour/11/ Traceback (most recent … -
Is it possible for an attribute to receive two different type values in a Django model?
I need to create an evaluation model for a candidate for a job. The form should be a page that displays the criteria (which are another template, so here I would use the ForeignKey) and next to a field to give a note to this criterion, assign a note to this criterion ... so I thought if you have As an attribute receive two value, a ForeignKey and an integer, or some way to connect two different attributes of the same model into another variable, the foreignKey criterion and the note that was received ... I thought of a variable that receives two different values From the point of view of forms (for when I pass it to the template), I'm a beginner in Django and I do not know how I can solve this. Qaulquer hint and help are welcome! Grateful