Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add another column for edit/delete button in django datatable?
Hello I'm try to learn django and have decided to read more about django and datatables. Here is the link: https://github.com/shymonk/django-datatable How would I add an edit/delete button to this datatable? Appreciate any help Thank you. -
Does 'from module import function' statement cause implicit imports of other functions in given module
My question originally was raised by an error, highlighted here. The original issue is now solved, but this leaves a question about how importing works in Python. Here are the quick steps to reproduce the issue with Django: Launch a dummy project with django-admin Create an app with it: ./manage.py startapp dummy_app In the app models.py define a function and a class that extends Django model, as below: from django.db import models # auxiliary function in models def aux_function(value): print(value) class Report(models.Model): class Meta: managed = False In the new app module's __init__, import the mentioned aux_function as below: from dummy_app.models import aux_function Add application to INSTALLED_APPS and run dev server It will result in an exception: File "/home/aanikeev/PycharmProjects/dummy/dummy_app/__init__.py", line 1, in <module> from dummy_app.models import aux_function File "/home/aanikeev/PycharmProjects/dummy/dummy_app/models.py", line 8, in <module> class Report(models.Model): File "/home/aanikeev/.virtualenvs/dummy/lib/python3.5/site-packages/django/db/models/base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "/home/aanikeev/.virtualenvs/dummy/lib/python3.5/site-packages/django/apps/registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "/home/aanikeev/.virtualenvs/dummy/lib/python3.5/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") Which is OK, we know from documentation that we shouldn't import models or modules with them before Django initializes (see ref 1, ref 2). What is not clear to me is why importing a function from a module … -
Testing celery task
I have a multi tenant system set up. Celery with RabbitMQ is set up. I have a system which triggers an email at the pre save signal of a model. Here is the code: @receiver(pre_save, sender=Student) def invite_stu(sender, instance, **kwargs): user_email = instance.email subject = 'dummy' message = '' html_message = 'dummy' from_email = my email id to_list = [user_email] send_html_mail(subject, message, html_message, settings.DEFAULT_FROM_EMAIL, to_list) # super(Employee, self).save() return instance I am writing a test case for this: class BaseSetup(TenantTestCase): def setup_tenant(self, tenant): """ Add any additional setting to the tenant before it get saved. This is required if you have required fields. """ user = User.objects.create(email="dummy@dummy.com", is_active=True) user.set_password('dummy') tenant.owner = user user.save() def setUp(self): self.sync_shared() tenant_model = get_tenant_model() app.conf.update(CELERY_ALWAYS_EAGER=True) app.conf.update(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True) print app.conf.CELERY_ALWAYS_EAGER test_schema_name = self.get_test_schema_name() test_tenant_domain_name = self.get_test_tenant_domain() self.tenant = tenant_model.objects.filter(schema_name=test_schema_name).first() self.c = TenantClient(self.tenant) def test_core_employee_put_api(self): response = self.c.post('http://test.localhost:8000/login/',{'email':'admin@dummy.com','password':'dummy'}) response_add_student=self.c.post('http://test.localhost:8000/student_admin/',{'email':'xxx@dummy.com','stu_number':'100','role':'STUDENT'},**{'HTTP_AUTHORIZATION':'JWT '+response.data['token']}) self.assertEqual(response_put_employee.status_code, 201) The test is running fine and it is even taversing through the mail function. But celery isnt initiating and sending mail if I run it through tests, but will send email if I add a student through API. Any way to work with this? -
Django test: TransactionManagementError: You can't execute queries until the end of the 'atomic' block
Django newbie here. I'm trying to implement unit tests for a simple API I developed. Below you can find my test implementation which works fine: from django.test import TestCase from my_app.models import MyModel class TestMyViewSet(TestCase): """ Unit tests for endpoints in MyViewSet. """ fixtures = ['my_app/fixtures/data.yaml'] def setUp(self): # Making setup for the test case here. def test_post_my_resource(self): # Checking that fixture is loaded correctly. self.assertEqual(MyModel.objects.all().count(),1) request_body = { 'my_resource': "input_for_my_resource" } response = self.client.post('/my_resources/', data=request_body) self.assertEqual(response.status_code, 201) # self.assertEqual(MyModel.objects.all().count(),2) But when I removed the last line self.assertEqual(MyModel.objects.all().count(),2) from the comment to test that my_resource is created successfully on the corresponding model by checking the number of instances, I got an error stating the following: TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. What am I missing here? Thanks in advance! PS: I come across the following question: TransactionManagementError “You can't execute queries until the end of the 'atomic' block” while using signals, but only during Unit Testing but I'm not sure what's happening in my case is the same. -
Issues in using git forked package in Docker-compose
I have installed one package which is forked from original package so I have installed that using pip install -e git://github.com/**package**.git@7f323a3682ddede83a7bf53cdc8d24bcc24d096c#egg=**package** But when I list my packages using docker-compose exec myapp pip list this package is not listed here and I am unable to run my project. -
Django CMS SMTP Server -- [Errno 61] Connection refused
I'm using Django CMS with the Aldryn Jobs module installed, by default the Jobs module uses the emailit module, not the core mail module that comes with Django (Still not sure why). My problem is I cannot connect to the SMTP server, whenever the app needs to send an email I'm greated with a error page. Here is the traceback Link. As far as I know Django comes packaged with a SMTP server so this should work out the box. Any advice would be greatly appreciated. Thanks, Sam -
Set up a e-mailing module in python-django project, so that any e-mail throughout the project can use the module
How to set up a e-mailing module in python-django project, so that throughout the project emails can be triggered without blocking the request. -
Not able to render ImageField of a model in Django Templets
Models.py class Blog(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() content_photo = models.ImageField(upload_to='passive_income/',blank=True) posted = models.DateTimeField(db_index=True, auto_now_add=True) author = models.CharField(max_length=255, blank=True) status = models.BooleanField(default=True) category = models.ForeignKey('blog.Category') Views.py def view_post(request, slug): return render_to_response('blog/view_post.html', { 'post': get_object_or_404(Blog, slug=slug) }) view_post.html {% extends 'blog/base.html' %} {% block head_title %}{{ post.title }}{% endblock %} {% block title %}{{ post.title }}{% endblock %} {% block content %} <li>{{ post.body }}</li> <li><img src{{ Blog.content_photo }}/></li> {% endblock %} My query is that when the URL opens a browser it does not display the image. -
What happen if I try to evaluate non-existing property of entries?(Datastore, Python)
I am making a web app using GAE datastore and need to update model schema. Currently, I have model like this. class Group(db.Model): name = db.StringProperty() div = db.StringProperty() But I want to add mid property with default value. class Group(db.Model): name = db.StringProperty() div = db.StringProperty() mid = db.IntegerProperty(default=0) I understand this won't update existing entries reading through this article. https://cloud.google.com/appengine/articles/update_schema It is ok for me existing entries stay without mid property because I will not use this property for query. But I need to use this to assert the situation. If I retrieved all the entries from datastore and evaluate mid property, does this result in AttributeError or something? groups = [e for e in Group.all()] for group in groups: if group.mid == 3: dosomething... If attribute error will happen, is there any to avoid the error? I am a bit expecting this might not result in error since I set a default value.... -
Django: ajax response doesn't show anything
In Django, I am trying to get a json using ajax. Before doing that, I will try to output a generic string instead of json. However, no matter how I try, the data does not print properly. The character "Good" in result.html is output normally. I thought I used url incorrectly, so I tried it several ways and it did not work. I would appreciate it if you could look at the code and let me know in detail what went wrong. Here is my code: result.html <!DOCTYPE html> <html> <head> <title>Hello Bubble Chart</title> <meta charset="utf-8"> </head> <body> <h1> Good</h1> <hr> <script src="http://code.jquery.com/jquery-lastest.min.js"></script> <script type="text/javascript"> $.ajax({ type: "GET", //dataType: "json", url: "/help/", data: {}, success: function(response){ alert(data); $("body").append(data); } }); </script> </body> </html> views.py def json_data(request): if request.is_ajax(): message = "Yes, AJAX!" else: message = "Not AJAX" return HttpResponse(message) urls.py urlpatterns = [ url(r'^inputTest/$', views.input_V, name='input_V'), url(r'^inputTest/result/$', views.result, name='result'), url(r'^inputTest/process/$', views.process, name='process'), url(r'^inputTest/help/', views.json_data, name='json_data'), url(r'^admin/', admin.site.urls), ] -
Django count date from datetime field for a particular user
I have a table that looks like : +-------+---------+---------------------+-------------+-----------+-----------------+ | id | user_id | visit_time | action | user_type | erp_customer_id | +-------+---------+---------------------+-------------+-----------+-----------------+ | 17460 | 818 | 2017-05-15 15:02:13 | NULL | customer | 932 | | 17459 | 818 | 2017-05-15 15:02:11 | NULL | customer | 932 | | 17458 | 818 | 2017-05-15 15:01:56 | NULL | customer | 932 | | 17457 | 818 | 2017-05-15 15:01:55 | NULL | customer | 932 | | 17456 | 818 | 2017-05-15 15:01:47 | NULL | customer | 932 | | 17455 | 818 | 2017-05-15 15:01:15 | NULL | customer | 932 | | 17454 | 818 | 2017-05-15 15:00:44 | NULL | customer | 932 | | 17453 | 818 | 2017-05-15 14:59:58 | NULL | customer | 932 | | 17452 | 818 | 2017-05-15 14:59:55 | NULL | customer | 932 | | 17451 | 818 | 2017-05-15 14:59:55 | NULL | customer | 932 | | 17450 | 818 | 2017-05-15 14:59:52 | NULL | customer | 932 | | 17449 | 817 | 2017-05-15 14:55:46 | NULL | customer | 931 | | 17448 | 817 | 2017-05-15 14:55:45 | NULL … -
Django innerQuery
Hello I've 3 models in my project and would like to do an inner join query on them. class Experiment(models.Model): experiment_id = models.AutoField(primary_key=True) experiment_name = models.CharField(max_length=500) class DataFile(models.Model): file_id = models.AutoField(primary_key=True) file_name = models.CharField(max_length=500) experiment_id = models.IntegerField(blank=True, null=True) date = models.DateTimeField(blank=True) created_on = models.DateTimeField(auto_now_add=True) class Analysis(models.Model): sample_name = models.CharField(max_length=500) file_id = models.IntegerField(blank=True, null=True) I'm using postgre and the query which I'm trying is select experiment_name,ma.rt FROM main_experiment me INNER JOIN main_datafile md ON me.experiment_id = md.experiment_id INNER JOIN main_analysis ma ON ma.file_id = md.file_id I want to extract all the sample name name using the experiment id I tried Experiment.objects.filter(experiment_id__sample_name=18) and many other combinations but I always get the below error. Unsupported lookup ' ' for AutoField or join on the field not permitted. -
Django and jquery datatable
I'm new in python/django and i'm making a project where i have this datatable: https://www.datatables.net/examples/api/multi_filter_select.html and i'm wondering if theres a way to select multiple objects, because now you are able to select only one -
return multiple objects with same name
MultipleObjectsReturned at /user/(name of object)/ Exception Type: MultipleObjectsReturned Request Method: GET Exception Value: get() returned more than one Canvas -- it returned 2! Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py in get, line 389 Multiple objects with the same name, but a user can only have one unique object name. Whenever I create another object with the same name I get this error (MultipleObjectsReturned). I want to allow every user to create one unique object name. For example: user1 can have a unique object name of (test) and user2 can also have a unique object name of (test). class Object(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) object_name = models.CharField( max_length=100, validators=[ # validate_canvas_title, RegexValidator( regex=CANVAS_REGEX, message='Canvas must only contain Alpahnumeric characters', code='invalid_canvas_title' )], ) slug = models.SlugField(max_length=100, blank=True) class Meta: unique_together = ['user', 'object_name'] view def canvasView(request, username=None, slug=None): user = User.objects.get(username__iexact=username) object = get_object_or_404(Object, slug__iexact=slug) template = "pages/object.html" context = { 'user' : user, 'object': object, } return render(request, template, context) -
Django template - checkbox did not react when is select
I have app in django and I updated my model: is_promoted_post = models.BooleanField(default=False) promoted_from = models.DateTimeField(blank=True, null=True) promoted_to = models.DateTimeField(blank=True, null=True) promoted_budget = models.CharField(max_length=70, blank=True, null=True) My goals are the appearance of the remaining fields when the is_promoted_post field is selected. In template I have: <h2>Promoted post</h2> <label>Promoted post?</label> {{ form.is_promoted_post }} <br><br> <label>Promoted date from</label> {{ form.promoted_from }} <label>Promoted date to</label> {{ form.promoted_to }} <label>Promoted budget</label> {{ form.promoted_budget }} When I use Firebug to get more details about is_promoted_post I get: <input checked="checked" id="id_is_promoted_post" name="is_promoted_post" type="checkbox"> I tried do start my js code but code did not respond when I selected checkbox without save model. My js code: $(document).ready(function(){ if ($('input#id_is_promoted_post').prop('checked')) { alert('Test test'); } }); Thanks for any help. -
How create custom widget in django?
In my form I have function field which is ModelMultipleChoiceField where I want to add selected by user functions. As queryset function field take all objects of Group. Can someone help me to create custom widget as the picture below for that field? Also here below you can see html of my widget (tree_widget.html). tree_widget.html: {% for group in groups %} <p>{{ group }}</p> {% for task in group_task.task_set.all %} <p>{{ task }}</p> {% for function in task.function_set.all %} <p> <input type="checkbox" name="option" value="{{ function }}">{{ function }} </p> {% endfor %} {% endfor %} {% endfor %} forms.py: class RequirementForm(forms.ModelForm): function = forms.ModelMultipleChoiceField(required=True, widget=CustomTreeWidget, queryset=Group.objects.none()) class Meta: model = Requirement fields = ('function',) def __init__(self, all_groups, all_user_characteristics, *args, **kwargs): super(RequirementForm, self).__init__(*args, **kwargs) self.fields['function'].queryset = all_groups # I take all Group objects from view widgets.py: class CustomTreeWidget(CheckboxSelectMultiple): template_name = 'tree_widget.html' ??? -
django model name in save() method
I want to get the name of the model inside the save() method . I want to correct this line self.slug = create_slug(self.model_name, self.slug) here I need to get the model name self.model_name. here model course inherited basemodel but I need to get the model name as course. How can I do that? Somebody please help me. class BaseModel(models.Model): slug = models.SlugField(unique=True, max_length=500) def save(self, *args, **kwargs): if self._state.adding == True: if not self.slug: self.slug = create_slug(self.model_name, self.slug) return super(BaseModel, self).save(*args, **kwargs) class Meta: abstract = True class Course(BaseModel): title = models.CharField(max_length=128) class Meta: db_table = "course" -
Django rest framework custom filter - order search by children count
I use DRF with django-rest-framework-filters . Models are: Order that has many OrderItems. Task is to create filter, that enable to search orders by order items count or sort by count. in my view.py : class OrderFilter(filters.FilterSet): order_items_count = filters.NumberFilter(name="order_items__count") customer = filters.RelatedFilter( CustomerFilter, name='customer', queryset=Customer.objects.all(), ) class Meta: model = Order fields = { 'internal_code': ['icontains'], 'notes': ['icontains'], 'status': ['exact'], 'complete': ['exact'], 'order_items_count': ['exact'] } class OrderViewSet(BaseViewSet, viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer filter_class = OrderFilter filter_backends = ( OrderingFilter, DjangoFilterBackend, ) ordering_fields = ( 'internal_code', 'notes', 'status', 'complete', 'customer__title', 'order_items__count', ) On request /orders?order_items_count=2 I got error: Related Field got invalid lookup: count How can I create custom filter for count of model's children? Thank you. P.S. It's my first question on stackowerflow, sorry for style errors. -
djano-registration not authenticating users on login
I'm using a (compatible) Custom User model. The registering part of django-registration is working perfectly. However, when I take the user to the log-in page from a navbar, The user is never really authenticated. If I put in a wrong password it will correctly through and error, but when username and password are correct, the user is simply redirected to the correct page, just without getting authenticated. My register/urls.py: urlpatterns = [ # a custom RegistrationForm that works perfectly url(r'^register/$', RegistrationView.as_view(form_class=GeneralUserForm), name='registration_register'), url(r'^', include('registration.backends.hmac.urls')), ] My register/templates/registration/login.html: . {% extends "base.html" %} {% load i18n %} {% block content %} <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans 'Log in' %}" /> <input type="hidden" name="next" value="{{ next }}" /> </form> <p>{% trans "Forgot password" %}? <a href="{% url 'auth_password_reset' %}">{% trans "Reset it" %}</a>!</p> <p>{% trans "Not member" %}? <a href="{% url 'registration_register' %}">{% trans "Register" %}</a>!</p> {% endblock %} -
Split Django application into two Python packages
I have a pretty large Django web application. The application is installed on a server and is working. It is divided into several Django apps, each with its own models and views. The users of this application are also programmers, and sometimes they want to write scripts that manipulate the database. I want them to use the existing Django models. However, I don't want them touching the big web application, they shouldn't be able to modify the views or write management commands that are installed on the server. Just scripts to run at their own convenience on their own private copy of the database. Ideally, they should be able to just pip install our-django-models. What's the best way of splitting the application into two parts? One will have to be a very slimmed-down Django application with just the models (which, again, are split into different Django apps). The other will need to be based on the first one, and provide everything else - views, their business logic, settings, etc... -
how to iterate python-django loop for N times in template?
I have an Object in python-django which i want to iterate in Django template for 5 times only, but the object has more than 100 values in it. What i am doing is : {% for x in abc %} <h4>{{x.name}}</h4> {% endfor %} nut this will run run till all elements. want to run it 5 times only. -
ImportError Unhandled by user code
[I've just begun working with Visual Studio, trying to develop Python web app using Django web framework, now every time I try to run the program in Google Chrome, the following error shows up. Pretty new stuff to me, sort of lost in the middle of nowhere.] https://i.stack.imgur.com/cvw41.png -
Django application deployed in AWS Elastic BeanStalk but cannot access the website
I have deployed a django based web application successfully in AWS Elastic Beanstalk. Health is showing OK. And logs are also fine. I have allowed SSH, HTTP and HTTPS traffic in inbound rules of Security group. But still I am not able to access my website using mysite.elasticbeanstalk.com url. I did ssh and saw that python process is up and running - [ec2-user@ip-xxx-xx-x-x ~]$ ps -aef | grep python root 2707 1 0 May13 ? 00:05:00 /usr/bin/python2.7 /opt/aws/bin/cfn-hup root 2816 1 0 May13 ? 00:00:15 /usr/bin/python2.7 /usr/local/bin/supervisord --nodaemon -c /opt/python/etc/supervisord.conf netstat -tulpn command is showing some process is listening on port 80 but I don't see any listening entry for port 443. Here is my .ebextensions/django.config file - container_commands: 00_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" 02_fixture: command: "source /opt/python/run/venv/bin/activate && python manage.py loaddata site.yaml" 03_oscar_countries: command: "source /opt/python/run/venv/bin/activate && python manage.py oscar_populate_countries" test: test ! -f /var/log/my-logs/.semaphore03 99_oscar_countries_populated: command: "touch /var/log/my-logs/.semaphore03"` option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "myapp.settings" "aws:elasticbeanstalk:container:python": WSGIPath: myapp/wsgi.py "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/"` How should I proceed and debug? I am stuck here. -
how to raise forms validation error, unique together
I don't know how to raise a forms validation error, am i suppose to override the validate_unique() method? IntegrityError at "..." UNIQUE constraint failed: model1, model2 -
What is the django managment directory for other than holding the commands directory?
In our django project we've created quite a bit of custom management commands over time. All of these are nested under root/<app_name>/management/commands/<command_name>.py The management directory contains just an __init__.py and the commands directory. ( as specified in the docs). This seems like unnecessary nesting to me. Are there any uses for the management directory that i'm not aware of?