Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pyswip python/django segmentation fault
I get a segmentation fault while trying to use pyswip with Django. My config : Linux 4.9.87-linuxkit-aufs #1 x86_64 GNU/Linux Python 3.6.4 # latest Python's docker image Django 2.0.2 SWI-Prolog 6.6.6 pyswip 0.2.7 Test in the shell works like a charm : $python manage.py shell >>>from pyswip import Prolog >>>prolog = Prolog() >>>prolog.assertz('person(john)') >>>print(list(prolog.query('person(X)'))) [{'X': 'john'}] Whereas in a django view, I get a segmentation fault as soon as the ... prolog.assertz('person(john)') ... is processed. Can't find a solution to this problem so far (best trail up to now : pyswip - issue #1). Is there a configuration in the settings.py for example to add ? What's missing for django's ecosystem to process that instruction right? -
Django: StackedInline displays extra element even though extra=0 in admin.py. Why?
I have a model to track and individual's behaviors over time. This model is used as an inline for a what I'm calling a "shell model." My admin model for the inilne looks like this: class IndicatorInline(admin.StackedInline): formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'20'})}, } model = Indicator insert_after = 'person' can_delete = False template = "admin/trajectory/indicator/edit_inline/stacked.html" readonly_fields = ["name",] fieldsets = ( ("Name", {"fields": ("name",)}), ("Primary", {"fields": (("primary_date", "primary_date_cue"), "primary_date_confidence")}), ("Secondary", {"fields": (("secondary_date", "secondary_date_cue"), "secondary_date_confidence")}), ("Tertiary", {"fields": (("tertiary_date", "tertiary_date_cue"), "tertiary_date_confidence")}), ) extra = 0 max_num = 26 def has_add_permission(self, request): return False So here extra = 0 and max_num=26, because there are only 26 defined behaviors, and the app doesn't care if some are missing, so all 26 are added at the same time. They are all part of the same table however, because it will make more common queries more intuitive. That aside when I add one of these "shell" models, the 26 behaviors are added on calling shell.save() but the Django admin is still rendering an extra inline, which I definitely don't want. For reference I will include the custom templates that I use for the inline (had to write custom templates so that the inline would render … -
Make Password NumericValidator Optional
For this application I'm working on, the password field should be able to accept only numeric password because some special users will only have to use 4 digits number to login to their dashboard. I commented out the NumericPassowrdValidator, but I got KEYERROR - 'NAME'. I checked the contrib.auth.password_validator code to see if I can add options and set either true or false to the NumericValidator similar to MinimumLengthValidator, but I can't find anything like that. How do I avoid the Numeric validator? What am I missing? AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { #'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] -
how to create mptt models together with forms
I have a model like this: # model: class MyMPTTModel(models.Model): name = models.CharField(max_length=256, unique=True) # this is set parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') #form class MyMPTTModelForm(forms.ModelForm): parent = mptt_forms.TreeNodeChoiceField(queryset=MyMPTTModel.objects.all()) class Meta: model = MyMPTTModel fields = ['name', 'parent'] I want to atomically get_or_create a set of nodes with the form(set?). Something like: paths = ['each-part/of-the-path/is-the-name', 'each-part/of-the-path/could-have-mutliple-children'] for path in paths: parent = None nodes = [] for p in path.split('/'): nodes.append({'name': p, 'parent': parent }) parent = p for node in nodes: name, parent = node.values() if parent: parent = MyMPTTModel.objects.get_or_create(name=parent)[0] MyMPTTModel.objects.get_or_create(name=name) I'm struggling with the get_or_create part of the form as the parent may not exist and therefore is not a valid choice. I could create them down before I create the next node, but then when it fails, it would create a bunch of orphan nodes since the children failed. -
Could not resolve URL for hyperlinked relationship using view name "source-detail" Django
We are running into this issue on tables that have foreign key constraints. For the table creating this issue, we copied the table data exactly with no constraints, just the data to a new table and everything worked fine. However, we want to use the table with the relationships and real constraints. Our models.py class NewsSerialiser(serializers.HyperlinkedModelSerializer): class Meta: model = News fields = ('news_id', 'news_source', 'news_title', 'news_description', 'news_publication_date', 'news_link') class NewsViewSet(viewsets.ModelViewSet): queryset = News.objects.all() serializer_class = NewsSerialiser The issue we get: Could not resolve URL for hyperlinked relationship using view name "source-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. -
node webpack build completing but files return 404 on heroku deploy
we're converting the frontend of a django (backend) app to react and using node and webpack to build the dependencies. all the frontend code is in a /frontend folder in the app. because heroku's node buildpack only looks at app root, I've added a root package.json to guide it to the right build path: { "description": "help heroku find path for frontend node app", "scripts": { "postinstall": "cd frontend && npm install && npm run build:production" }, "engines":{ "node":"10.0.0", "npm":"6.0.01" } } then inside /frontend is the build:production directive and deps: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack --config webpack.config.babel.js", "build:watch": "webpack --config webpack.config.babel.js --watch", "build:production": "npm run build" }, "author": "", "license": "ISC", "dependencies": { "babel": "^6.23.0", "babel-loader": "^7.1.4", "babel-polyfill": "^6.26.0", "dotenv": "^5.0.1", "lodash": "^4.17.10", "prop-types": "^15.6.1", "react": "^16.3.2", "react-dom": "^16.3.2", "semantic-ui-css": "^2.3.1", "semantic-ui-less": "^2.3.1", "semantic-ui-react": "^0.81.1", "style-loader": "^0.21.0", "styled-components": "^3.2.6", "webpack": "^4.8.3", "webpack-bundle-tracker": "^0.3.0", "babel-cli": "^6.26.0", "babel-core": "^6.26.3", "babel-plugin-transform-regenerator": "^6.26.0", "babel-preset-env": "^1.7.0", "babel-preset-react": "^6.24.1", "babel-register": "^6.26.0", "css-loader": "^0.28.11", "dotenv-webpack": "^1.5.5", "eslint": "^4.19.1", "eslint-plugin-import": "^2.12.0", "eslint-plugin-jsx-a11y": "^6.0.3", "eslint-plugin-react": "^7.8.2", "extract-text-webpack-plugin": "^4.0.0-beta.0", "file-loader": "^1.1.11", "less": "2.7.3", "less-loader": "^4.1.0", "mini-css-extract-plugin": "^0.4.0", "svg-inline-loader": "^0.8.0", "uglifyjs-webpack-plugin": "^1.2.5", "url-loader": … -
Django - admin related model editing
I'm trying to resolve something and i'm hope for your help there is 2 models: def BigBox(models.Model): title = textfield date = datetimefield author = foreignkey(user) # other fields etc. def SmallBox(models.Model): title = textfield contained_in = foreignkey(BigBox) # little box that can be only in big box I need to make (all that is written below apply to the admin.Model): When you edit/creating BigBox, need to be able to create new related SmallBoxes inside. That means that every BigBox always contains at least one SmallBox and every SmallBox always in anyof BigBox. Need to specify way of creating SmallBoxes just inside BigBox. -
Error while installing Django on Mac
Perhaps your account does not have write access to this directory? If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account. If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferably one that is listed in your PYTHONPATH environment variable. Even though my privileges are set to read and write. I don't know what to do. -
Can not use celery delay for saved form
I'd like to triger a delayed celery function after a form is saved in views def new_topic(request, forum_id): form = TopicForm() uid = request.user.id if request.method == 'POST': tform = TopicForm(request.POST) if tform.is_valid(): topic = tform.save(commit=False) topic.title = clean_title(tform.cleaned_data['title']) topic.description = clean_desc(tform.cleaned_data['description']) topic.save() notify_new_topic.delay( uid, topic) #<--problem here #rest of the views But I get EncodeError at /add/topic/ <Topic: Topic object> is not JSON serializable I don't get any error if I remove delay from the celery task. The task is: @shared_task def notify_new_topic(flwd_id, topic): title = topic.title link = topic.slug flwd= cached_user(flwd_id) #User.objects.get(id = flwd_id) print 'flwd is', flwd.username flwr_ids = FollowUser.objects.filter(followed=flwd).values('follower_id') flwrs = User.objects.filter(id__in= flwr_ids).values('id', 'username','email') for f in flwrs: print 'flwr username:', f['username'] if notify_flwdp_applies(int(f['id'])): print 'notify flwdp applies' make_alerts_new_topic(flwd_id, f['id'], topic) print 'back from make_alerts_new_topic' I'm wondering how can I debug/fix this? -
changes to settings.py not updating
I am trying to get a django app to work on ubuntu with apache. I am getting the error message "You may need to add 'x.x.x.x' to ALLOWED_HOSTS." I have made the changes to settings.py, but still get the error message. I can see in the debug output that it looks like the changes I made to settings.py are not taking effect. I have tried restarting apache ( /etc/init.d/apache2 restart) but still no help. Any input would be greatly appreciated. thanks! Bob -
TemplateDoesNotExist error please help me
Hi^^ I'm studying django I'm creating a blog site and now I'm working on linking a template to a view but It's had a problem.... this is traceback /home/choco/.local/lib/python3.6/site-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /home/choco/.local/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /home/choco/.local/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /home/choco/python3/django/blog/blog/views.py in post_list return render(request, 'blog/post_list.html', {}) ... ▶ Local vars /home/choco/.local/lib/python3.6/site-packages/django/shortcuts.py in render content = loader.render_to_string(template_name, context, request, using=using) ... ▶ Local vars /home/choco/.local/lib/python3.6/site-packages/django/template/loader.py in render_to_string template = get_template(template_name, using=using) ... ▶ Local vars /home/choco/.local/lib/python3.6/site-packages/django/template/loader.py in get_template raise TemplateDoesNotExist(template_name, chain=chain) ... ▶ Local vars blog/blog/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name = 'post_list'), ] blog/mysite/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] blog/blog/views.py from django.shortcuts import render def post_list(request): return render(request, 'blog/post_list.html', {}) blog/blog/blog/templates/blog/post_list.html -
Task is not applying on Celery
Please help me about how to register task on celery. Error log is: [2018-06-21 23:23:20,288: ERROR/MainProcess] Received unregistered task of type 'projects.tasks.hoge'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[[2, true], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (84b) Traceback (most recent call last): File "/home/ec2-user/.pyenv/versions/3.6.2/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 561, in on_task_received strategy = strategies[type_] KeyError: 'project.tasks.hoge' It worked fine on different environment and same source code. Does anyone know why this occured? -
Django variant model field?
I have a situation where I want to be store values in a database which may be textual or numeric (the reason is incidental but basically, want to create label/value pairs for a scorecard where the questions may either have numeric or text answers). I thought of addressing this by creating a variant model field type. However after a fairly extesive google and stackoverflow search I failed to encounter any off-the-shelf solutions. Now, I can go ahead and develop my own probably by deriving CharField. However, the lack of existing solutions makes me think that I'm looking at the problem in the wrong way. I would very much appreciate your thoughts as I bet others have come accross this kind of problem Many thanks -
Specifying a certain group in Django
I know this is probably a basic question for anyone who codes python regularly but I am new to python and have a pretty basic question. Basically I have users within my site, and each user is specified a certain role.... On my home page I want a message that lists who the admins are... I know how to create the message itself but I do not know how to pull only the admins out from a group of people with mixed roles.. class UserInfo(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) SERVER_ROLE = ( ('creator', 'CREATOR'), ('admin', 'ADMIN'), ('moderator', 'MODERATOR'), ('normie', 'NORMIE'), ) role = models.CharField(max_length=10, choices=SERVER_ROLE, default='normie') That is basically the code that I have for my basis. I have tried to look at other peoples answers but i genuinely dont understand what they are saying... Thank you! -
Render message status to templates while view is still in progress using Django
I want to render messages status in html while view is still not finish its progress. For example in html will show a modal then changing it text from the view messages: class IndexView(TemplateView): def post(self, request): messages.info(request, 'Initializing') # do something messages.info(request, 'Getting results') # other codes here Then html modal will display this message like 'Initializing' after a few seconds it will change to 'Getting results'. -
Django Model Form validation doesn't show
I needed some validation on a Django ModelForm field. So I changed 2 lines in my models.py (just below). The validation is blocking as necessary, but I can't find the proper way to display the ValidationError. Maybe there is a cleaner way to do this in the model form ? models.py class Lexicon(models.Model): [...] alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', _('Only alphanumeric characters are allowed')) filename = models.CharField(_("Filename"), max_length=40, validators=[alphanumeric]) LexiconForm is simply populated with the Lexicon model field. views.py @login_required def new_pls_view(request): if request.method == 'POST': form = LexiconForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() return redirect('pls_edit') else: form = LexiconForm() return render(request, 'main/new_pls.html', { 'form': form, }) template.html <form class="form-horizontal" method="post" action="{% url 'new_pls' %}"> {% csrf_token %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} [...] {% if form.is_bound %} {% if form.filename.errors %} {% for error in form.filename.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% endif %} {% if form.filename.help_text %} <small class="form-text text-muted">{{ form.filename.help_text }}</small> {% endif %} {% endif %} {% render_field form.filename type="text" class+="form-control" id="plsFilename" placeholder=form.filename.label %} -
How does Django creates tables(sqlite)?
I am looking at this example django-multiple-users When I go to sqlite shell sqlite> .tables auth_group classroom_subject auth_group_permissions classroom_takenquiz auth_permission classroom_user classroom_answer classroom_user_groups classroom_question classroom_user_user_permissions classroom_quiz django_content_type classroom_student django_migrations classroom_student_interests django_session classroom_studentanswer There are 8 classess in models.py class User(AbstractUser): class Subject(models.Model): class Quiz(models.Model): class Question(models.Model): class Answer(models.Model): class Student(models.Model): class TakenQuiz(models.Model): class StudentAnswer(models.Model): Forms.py(shown in github link above) has couple of forms. Do forms also create tables? Where do classroom_user_user_permissions come from? -
Zulip on Vagrant cannot find jquery.js
I'm following Zulip's docs to set it up on Vagrant. Installation seemed to go well. But, when I ran it with ./tools/run-dev.py: Error: Cannot find module '../static/node_modules/jquery/dist/jquery.js' at Function.Module._resolveFilename (module.js:547:15) at Function.resolve (internal/module.js:18:19) at exports.default (/srv/zulip/tools/webpack.config.ts:45:35) at handleFunction (/srv/zulip-npm-cache/6fcddf4358d67c4ab177350efd1322d0f3ed02cc/node_modules/webpack-cli/bin/prepareOptions.js:23:13) at prepareOptions (/srv/zulip-npm-cache/6fcddf4358d67c4ab177350efd1322d0f3ed02cc/node_modules/webpack-cli/bin/prepareOptions.js:9:5) at requireConfig (/srv/zulip-npm-cache/6fcddf4358d67c4ab177350efd1322d0f3ed02cc/node_modules/webpack-cli/bin/convert-argv.js:136:14) at /srv/zulip-npm-cache/6fcddf4358d67c4ab177350efd1322d0f3ed02cc/node_modules/webpack-cli/bin/convert-argv.js:142:17 at Array.forEach (<anonymous>) at module.exports (/srv/zulip-npm-cache/6fcddf4358d67c4ab177350efd1322d0f3ed02cc/node_modules/webpack-cli/bin/convert-argv.js:140:15) at Object.<anonymous> (/srv/zulip-npm-cache/6fcddf4358d67c4ab177350efd1322d0f3ed02cc/node_modules/webpack-dev-server/bin/webpack-dev-server.js:234:54) static/node_modules contains just this: ../node_modules/. Here's the file on GitHub. It's a node_modules symlink, right? I'm running Git BASH on Windows 10 as administrator and: $ git config core.symlinks true When I went to http://localhost:9991/: Error reading /srv/zulip/zproject/../var/webpack-stats-dev.json. Are you sure webpack has generated the file and the path is correct? I read the common errors section of the docs and googled it as well but haven't found anything. I'm not familiar with Vagrant and Virtualbox so I'm not great at navigating them yet. What should I try? -
serializer for add to cart in django rest framework
I am struggling on creating the serializer for add to cart. When adding cart, there should be product and the quantity. With the model I have, I am confused on which model to choose for adding the items to the cart. Here is the model models.py class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) items = models.ManyToManyField(Cycle, through='CartItem') updated = models.DateTimeField(auto_now_add=False, auto_now=True) subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) tax_percentage = models.DecimalField(max_digits=10, decimal_places=5, default=0.085) tax_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) active = models.BooleanField(default=True) objects = CartManager() def __str__(self): return str(self.id) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) item = models.ForeignKey(Cycle, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) line_item_total = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.cart.id I feel like I have to use Cart for the Add, Remove, Update CartSerializer and CartItem for the checkout. However, I am still confused because using model Cart in CartSerializer, i do not get the product to select. Can anyone help me to create a serializer for adding to the cart, please? -
List apps of a django project
I'm completely new for django and I'd want to list the apps of a django project, for example: FeinCMS I know that startapp creates the directory structure for an app. I wonder if there is either a function or a file to get the app list. -
How do I add additional fields in the Django Admin?
I am learning python and I have to add some additional fields in admin/auth/user/add/ -
Django: cannot import name 'url_patterns'
I have a weird edge-case where I need to use the data stored in urls.py within a view, but since the urls.py file imports the view, I am getting a circular import error when I try to import the url data into the view. cannot import name 'url_patterns' Does Django have any way of grabbing all the url patterns within a view that could circumvent this error? The fact that the reverse() function exists indicates that it might. -
Did you install mysqlclient?
I have read every single post and googled for the last 4 hours to try to find a solution to this error. I am not running virtual environment, this server is just for django. Server: Ubuntu 16.04 python: 3.5.2 I am getting this error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? trying to install mysqlclient sudo -H pip3 install mysqlclient equirement already satisfied: mysqlclient in /usr/local/lib/python3.5/dist-packages (1.3.12) useing ubtunu sudo apt-get install -y python3-mysqldb Reading package lists... Done Building dependency tree Reading state information... Done python3-mysqldb is already the newest version (1.3.7-1build2). 0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded. any help is greatly appreciated -
Outer loop value does not matches with inner loop value: Django template
I have written a nested loop and doing value comparison between data coming from outer loop with inner loop. Below is my template code :- <tbody> {% for col in filter2.qs %} <tr> {% for mso in filter1.qs %} {{ col.box_id }}&nbsp;vs&nbsp;{{ mso.box_id }} <br> {% if mso.box_id == forloop.parentloop.col.box_id %} <td>{{ mso.mso_id }}</td> <td>{{ col.box_id }}</td> <td>{{ col.channel_id }}</td> {% endif %} {% endfor %} </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} </tbody> Problems are : When i do print {{ col.box_id }}&nbsp;vs&nbsp;{{ mso.box_id }} i can see values When i do print {{ col.box_id|length }}&nbsp;vs&nbsp;{{ mso.box_id|length }} i see length of outer loop value as 0. If condition below the prints never runs hence no data is inserted in the table. I am getting data for both the loops from views.py def search(request): user_list1 = VCB_Execution_Details.objects.all() user_filter1 = ReportFilter_VCB_Execution_Details(request.GET, queryset=user_list1) user_list2 = VCB_Details.objects.all() user_filter2 = ReportFilter_VCB_Details(request.GET, queryset=user_list2) print(user_filter2.qs) print(type(user_filter1)) return render(request, 'user_list.html', {'filter1':user_filter2,'filter2': user_filter1}) filters.py class ReportFilter_VCB_Execution_Details(django_filters.FilterSet): class Meta: model = VCB_Execution_Details fields = ['box_id','channel_id'] class ReportFilter_VCB_Details(django_filters.FilterSet): class Meta: model = VCB_Details fields = ['box_id','mso_id'] -
How to store two Integers in one Django model instance?
Inside my Django model which is called Setup, I have an instance dedicated to the timing that the user can set in case of fast operation. In real life, the timing is expressed by two numbers, example: timing: 5-10 secondswhere 5 is the "pause" and 10 the "motor on" time. Now, I know that probably the best way to have this set up is to separate the two and have one instance for each, but for usability reason I'd need to keep the "real" format, so number + hyphen + number. Is there any way in Django to store two different numbers in the same model instance? There will be a form for this model and ideally it should have input + hyphen + input. fast_op_timing = models.IntegerField...?? Thank you very much in advance. I appreciate your help!