Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Test how many method calls occured and what arguments was passed (test django mixin class)
I have a django mixin class with several methods coded like in following simple excample: class Mixin(object): def method1(self): A = self.A # this is dictionary B = self.B C = self.C D = self.D for i,j in self.A.iteritems(): self.method2(B, C, D, i, j) def method2(self, arg1, arg2, arg3, arg4, arg5): pass Mixin class declaration don't provide any of A,B,C,D arguments. These will be specified in view class. I want to test how many method2 calls occured and what arguments were passed in every call. I'll be grateful for any idea how could I handle this problem. Thanks in advance! -
Queryset inside et ouside a function
Assume, in the database, withdrawal=12. If, in a function, I define a queryset, e.g., OBJECT.objects.get(withdrawal=17), am I right to say that, if I don't save in the function, withdrawal=17, and once I am out of the function, withdrawal becomes again equal to 12? Thanks! -
How to protect a superuser?
In my Django Website I'd like to have multiple levels: lambda users moderators Super-moderators (or admin) Owner Super-moderators can change permissions, delete an account, modify a moderator etc... But I don't want them to change the superuser status of the Owner or to delete it. How can I do this? tl;dr : How do I give all permissions, except the one to change the superuser status? -
DJANGO - 'str' object has no attribute 'data'
I am doing a project using Django and DRF. I have a view which lists the details of an item (Conta). And all the fields are editable so the user can edit the object. The problem is a get the error: 'str' object has no attribute 'data' The code: class ContaDetailsHTML(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'conta_details.html' def get(self, request, pk): user = request.user conta = get_object_or_404(Conta, pk=pk,user=user) serializer = ContaDetailsSerializerHTML(conta) return Response({'serializer': serializer, 'conta': conta}) def post(self, request, pk): user = request.user conta = get_object_or_404(Conta, pk=pk, user=user) serializer = ContaDetailsSerializerPosts(conta, data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer, 'conta': conta}) serializer.save() return Response(status=status.HTTP_200_OK) And in the templates: {% load rest_framework %} <html><body> <h1>Conta - {{ conta.nome }}</h1> <form action="{% url 'conta_details' pk=2 %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> </body></html> the pk=2 is just for testing purposes. When i edit the fields and press Save, that error pops up. Any ideas? -
Online Payment System using Django
I'm trying to make an online payment system using Django. What are the strategies I need to follow to build this particular project? I searched in the internet and I found several ways but bit confusing. -
Django: Change the error message for validate_ipv46_address
I want to change the error message of the validator validate_ipv46_address. This is my code in my forms.py: class IPAddressForm(forms.ModelForm): ip_address = forms.CharField(validators=[validate_ipv46_address]) class Meta: # ... def __init__(self, *args, **kwargs): super(IPAddressForm, self).__init__(*args, **kwargs) def clean_ip_address(self): # i check other stuff and i want to change the messege of the validate_ipv46_address, but it hasn't a message argument like validate_ipv46_address(message=''). Or do I have to write my own validator? But this also doesn't work. class my_validate_ipv4_address(validate_ipv46_address): message = 'test' -
Postgres: add description of an ENUM value?
I've got an ENUM column in Postgres 9.6: CREATE TYPE my_type AS ENUM('foo', 'bar'); I'd like to add a human-readable description for each value in the enum, e.g. for foo, This is the foo value and it does stuff. Is there any way to do this in Postgres? I'd like something like Django's choices field. -
How to do data search in dataset with Python Django
I am new to Django and I'm working on dataset search. Given this class Student(models.Model): score_1 = models.IntegerField(default=0) score_2 = models.IntegerField(default=0) I know how get the students with the score_1 higher than 90, which is something like this: s = Student.objects.filter(score_1__gte=90) However, I'm having problem getting the students who have their score_1 10 points more than their score_2, aka score_1 - score_2 >= 10. Since there are lots of student data, I cannot just pull all the data out and then do the search, which will apparently take forever. So is there any other way to do this? Thanks so much! -
Interactive django website including a table
I want to create a django website with a table that lets users input numbers then the website uses code to add them up and other calculations. How would i go about doing this/are there any tutorials to help? I,ve created a code in python that works to do the calculations but i dont know how to transfer this to a working website! I'm a complete beginner and have never used django before. -
Using celery, send async_apply to specific vhost?
I have a use case where I'd like to be able to have many clients connect to RabbitMQ but they cannot see each other's messages. I believe using vhosts is the best way to keep privacy between the workers? I thought I'd be able to pass a virtual_host argument to apply_async but that's not going to work, I believe I have to make a custom connection like so: from kombu import Connection my_connection = Connection(virtual_host='new_virtual_host') task.apply_async(connection=my_connection) However, I bet there's a built in way to do that inside Celery using the settings I already have configured and going through the proper channels in case I switch backends. What is that internal "get connection" function? This is using Celery 3.1 -
apache2 crashes when trying to dynamically load python module
I have a Django application, which has the following code init: import importlib def get_class(m): module_name, class_name = m.rsplit('.', 1) module = importlib.import_module(module_name) return getattr(module, class_name) Whenever I make a request which requires a call of this function, in the error.log I see child pid 27228 exit signal Segmentation fault (11), possible coredump in /etc/apache, and request fails with error code 500. The strange thing is that if I call that function from command line, everything works well. Seems like mod_wsgi does not allow to dynamically load a python module. I tried to do the following with all combinations: Use virtual environment Downloaded sources of python 3.6, compiled and installed it, Recompiled the mod_wsgi for both default python 3.4.3 and new python 3.6. The error is always the same: OS: Ubuntu Server 14.04 Apache: 2.4.7 Python: 3.4.3, 3.6.0 On my Ubuntu Desktop 14.04 everything works fine. Apache is installed by sudo apt-get install apache2 -
Django Advanced Filter not working in django-material admin Theme
I am using django 1.9.5 and in admin panel i have imported django-advaced-filter and it works well but when i have changed my django admin theme to django-material then django-advanced-filter is not working i am only getting Title of django-material but the pop is not comming Please see the above screen shot -
ViewFlow and django-guardian
I want to make use of django-guardian's object permissions and grant specific rights for specific users to one or more Django users. I have tried to add some permissions to my Process class like this: class TestProcess(Process): title = models.CharField(max_length=64) something = models.ForeignKey(ForInheritage, null=True, on_delete=models.CASCADE) no_approval = models.BooleanField(default=False) approved = models.BooleanField(default=False) def something_is_approved(self): try: return self.something.approved except: return None class Meta: permissions = ( ('view_process', 'View Process'), ) Unfortunately this causes viewflow to immediately throw an error after starting runserver: File "/home/me/.virtualenvs/viewflow3/lib/python3.4/site-packages/viewflow/mixins.py", line 253, in ready self.flow_class.process_class._meta.permissions.append( AttributeError: 'tuple' object has no attribute 'append' My initial plan was to subclass Start and View flow classes to change how the Permission function, that is inherited from the PermissionMixin, works. But this seems to be more work than just this, too. django-guardian is already mentioned in one of the cookbook sections here but currently leads to a 404 page. What would be the recommended/cleanest way to use guardian permissions on Processes and Tasks? -
How to parse value with rivets.js?
I am using Dashing framework based on Django. HTML using the Rivets.js conventions to bind data to the script file. <div rv-status-color="value"> <h1>{ title }</h1> <h2>{ value }</h2> <p class="detail">{ detail }</p> <p class="more-info" rv-show="moreInfo">{ moreInfo }</p> <p class="updated-at" rv-show="updatedAt">{ updatedAt }</p> </div> <i rv-class="icon" rv-show="icon"></i> Following script gets value from HTML and set neccessary color to .css according condition. rivets.binders['status-color'] = function(el, value) { if (value == 0) { $(el).css('background-color', 'green'); } else if (value < 0) { $(el).css('background-color', 'orange'); } else { $(el).css('background-color', 'red'); } }; Could you tell me how to rewrite script to get {detail} value and comparing its with {value}? Something like that: rivets.binders['status-color'] = function(el, value) { if (value == detail) { $(el).css('background-color', 'green'); } else if (value < detail) { $(el).css('background-color', 'orange'); } else { $(el).css('background-color', 'red'); } }; Thank you in advance. -
python manage.py collecstatic isn't copying my .css file
I am trying to work with static files in django. I have watched many videos and I know I feel I am doing it correctly. Following is the settings.py snippet: STATIC_URL = '/static/' STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn') I have also added this to urls.py: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When I do a collectstatic it copies all those from admin folder. But it is not copying my .css file from static folder. Can someone tell me where am I doing it wrong. -
Django autocomplete light v2 access search term and results in Registry
in Django-autocomplete v2 my registry looks like this: def modifyresults(): usersearchstring='hello' return '<span data-value="%s">%s '+usersearchstring+'</span>' autocomplete_light.register(ResourceBase, search_fields=['title','abstract'], autocomplete_js_attributes={'placeholder': 'Resource name..', }, choice_html_format=modifyresults()) This works as expected, I can overwrite choice_html_format as the documentation mentions. But I do not need to modify choice_html_format but like to do further filtering on the results coming from my model. Question: How can I access the search term coming from the user input as GET var q (below defined as usersearchstring) and the results coming from the model (below defined as choices_coming_from_model). What I need could look like this in pseudo code: def find_user_string_in_database_matches(s, pat): pat = r'(\w*%s\w*)' % pat return re.findall(pat, s, re.IGNORECASE) def modifyresults(request): # get access to the user search usersearchstring=request.GET.get('q', '') # split results coming from model choicesparts=choices_coming_from_model.split('$$$') # filter result with regex new_find_results 0 find_user_string_in_database_matches(choicesparts[1], usersearchstring) return choicesparts[0]+': '+ " ".join([str(i) for i in new_find_results]) autocomplete_light.register(ResourceBase, search_fields=['title','abstract'], autocomplete_js_attributes={'placeholder': 'Resource name..', }, choice=modifyresults()) -
Wagtail 1.8.1 migration issue
Trying to upgrade Wagtail from 1.7 to 1.8.1 but we're getting the following error when running migrations. We're using Postgres db. Applying wagtailimages.0016_deprecate_rendition_filter_relation...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 204, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 495, in alter_field old_db_params, new_db_params, strict) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql/schema.py", line 117, in _alter_field new_db_params, strict, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 649, in _alter_field params, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 112, in execute cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: could not create … -
Altering the template html with javascript when the page loads with django
I have a calendar view that I have written in python with the django web framework. This presents holiday objects to the user, that contain a start_date, end_date and person_id. In the view, I want to change the html in all the day_cells between these dates, without making each day explicitly an object in itself. So for this I want to write some jquery that executes on page load and takes information from the view. Then I can use this information to append the html. I need to send the start_date, end_date and person_id with json. def holiday(request): # .... date_today = datetime.now() year = date_today.year month = date_today.month my_holidays = Holiday.objects.order_by('start_date').filter( Q(start_date__year=year, start_date__month=month) | Q(end_date__year=year, end_date__month=month) ) cal = HolidayCalendar(my_holidays, request.user).formatmonth(year, month) context = { "calendar": mark_safe(cal), } return render(request, "tande/calendar.html", context) And this is where the HTMLCalendar builds: class HolidayCalendar(HTMLCalendar): def __init__(self, holiday, user): super(HolidayCalendar, self).__init__() self.holiday = self.holiday_days(holiday) def formatday(self, day, weekday): #... return self.day_cell(cssclass, '%d %s' % (day, ''.join(body))) def formatmonth(self, year, month): self.year, self.month = year, month return super(HolidayCalendar, self).formatmonth(year, month) def holiday_days(self, holiday): #... return holiday def day_cell(self, cssclass, body): return '<td class="%s">%s</td>' % (cssclass, body) How do I do this, because my view … -
Optional(not random) argument in URL patterns
How can I pass optional argument in url patterns(not random)? /new/ /new/save-and-add-new/ url( regex=r'^~new/[save-and-add-new]/$', view=views.BudgetCreateView.as_view(), name='create' ), I need to use this in: def get_success_url(self): if save_and_add_new_argument_in_url: return HttpResponseRedirect(reverse('item:new')) return HttpResponseRedirect(reverse('item:list')) -
Django query objects with all related objects meeting a condition
Given these Django models: class Job(models.Model): pass class Task(models.Model): job = models.ForeignKey('Job', related_name='tasks') dependencies = models.ManyToManyField("self", related_name="dependents", symmetrical=False) I want to query all Tasks with status PENDING and ALL dependencies having status COMPLETED for a single Job. I wrote the following query, but it returns tasks that have at least one dependency with status completed, which is obviously not want I'm after. tasks_that_can_be_executed = Task.objects.filter( job__pk=job_id, status=TaskStatus.PENDING, dependencies__status=TaskStatus.COMPLETED ) Any suggestions? -
AdminModel object has no attribute 'obj'
I have model with manytomany field, and in admin panel in my AdminModel class I use this code: def get_object(self, request, object_id, to_field): # Hook obj for use in formfield_for_manytomany self.obj = super(GoalAdmin, self).get_object(request, object_id) return self.obj def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "reviewers": kwargs["queryset"] = Goal.objects.get(id=self.obj.id).reviewers.all() return super(GoalAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) It works fine, until I try add goal from admin panel. Than I get this error: 'GoalAdmin' object has no attribute 'obj' How can I fix it? -
Some simple API Requests are suddenly slow after moving from Heroku to DigitalOcean with Docker
I have a problem and I don't even begin to know what I should google. I have a Django + Nginx + Postgres + Angular 2 app, previously running on Heroku (without Nginx), but recently decided to move everything into its own Docker container, and deployed it on DigitalOcean. But now I seem to have a weird issue. I have one API endpoint that is used by my Angular app. The endpoint has received quite some traffic in the past few days and has been working well. The backend does some relatively heavy calculations when this endpoint is being called. I get a response in < 1 second. Now I have several other endpoints, including a login/auth system and another public endpoint for retrieving a big list. On Heroku I had no problems with these, but now they suddenly take over 60 seconds to respond, if they don't time out! Both the secured one and the publicly exposed one. I would post code or info, but since I have no clue what is going on here I don't know what to post. Help! :( -
m2m relations are not displayed or saved in django
class A(Model): to_b = ManyToManyField('B', blank=True, through='AtoB') class B(Model): to_a = ManyToManyField('A', blank=True, through='AtoB') class AtoB(Model): a = ForeignKey('A', on_delete=CASCADE) b = ForeignKey('B', on_delete=CASCADE) usr = ForeignKey(settings.USER, on_delete=CASCADE) # some other fields Im making a django application. This is roughly equivalent to what i have in my models.py I need m2m relation between A and B to go through another model because i need to store additional data there. Now there is a problem - when i try to save instance of model A in my custom view, relations with B instances are not saved no matter whether i pick them or not. And when i go to http://127.0.0.1:8000/admin and try to create instance of A from there, i dont even see proper field (should be <select multiple> i guess) for selecting relations with B. Can someone please explain me why relations are not saved, and not even displayed in /admin? -
How to get the related field value of item in the queryset inside for loop
Supposed that we have a model Patient and Diagnosis. class Patient(models.Model): name = models.CharField() class Diagnosis(models.Model): patient = models.ForeignKey( Patient, related_name='diagnoses', on_delete=models.CASCADE ) is_active = models.BooleanField() In my views.py i was able to filter Patient whose diagnosis is_active=True with this code. # returns queryset whose patient has active diagnosis. queryset = Patient.objects.filter( diagnoses__is_active = True ) But i cannot get the value using for loop with this. I added comment with the errors im getting. for qs in queryset: # 'RelatedManager' object has no attribute 'is_active' print qs.diagnoses.is_active # 'Patient' object has no attribute 'diagnoses__is_active' print qs.diagnoses__is_active # There is no error from this code but # i got the 'diagnoses.Diagnoses.None' in return print qs.diagnoses How can it possibly be when i was able to filter the queryset in the first place? -
How to clear cache on building Gitlab?
Gitlab can't clean my cache on building. How to fix this problem? Executor: shell Fetching changes... warning: failed to remove config/__pycache__/__init__.cpython-36.pyc warning: failed to remove config/settings/__pycache__/local.cpython-36.pyc warning: failed to remove config/settings/__pycache__/__init__.cpython-36.pyc warning: failed to remove config/settings/__pycache__/common.cpython-36.pyc warning: failed to remove config/settings/__pycache__/test.cpython-36.pyc warning: failed to remove docs/__pycache__/__init__.cpython-36.pyc