Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when refreshing I got 404 not found (nginx)
My website URL is www.pm0603.com and everything works fine. But when I got into a detailed page or like http://www.pm0603.com/detail/113448 and hit refresh button(Or try to access that resources directly), then I got 404 not found error message. The front-end part is not done by me and I don't know exactly what the problem is. I am using Django for the back-end. And the refresh works without any problem in local env. I just guess it would be related to my nginx configuration. Or is it a cache problem? Below is my nginx configuration. server { listen 4567; server_name localhost api.pm0603.com pm0603-dev.ap-northeast-2.elasticbeanstalk.com; charset utf-8; client_max_body_size 128M; location /media/ { alias /srv/app/django_app/media/; } location /static/ { alias /srv/app/static_root/; } location / { uwsgi_pass unix:///tmp/app.sock; include uwsgi_params; }} server { listen 4567; server_name front.localhost pm0603.com www.pm0603.com; charset utf-8; client_max_body_size 128M; location / { alias /srv/please/; } gzip on; gzip_comp_level 2; gzip_proxied any; gzip_min_length 1000; gzip_disable "MSIE [1-6]\." gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;} As you can see, I have two servers, one is for the api and the other for serving static files. If you have any idea, please help me! -
ImportError: cannot import name 'NAMESPACE'
I have searched all over for a solution but I cannot find one for the error I am getting. I am trying to migrate to heroku and every time I run the command I get an error. Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/base.py", line 353, in execute self.check() File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/app/.heroku/python/lib/python3.5/site-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.5/site-packages/django/urls/resolvers.py", line 310, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/python/lib/python3.5/site-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.5/site-packages/django/urls/resolvers.py", line 303, in urlconf_module return import_module(self.urlconf_name) File "/app/.heroku/python/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, … -
Django Rest Framework: How to enable swagger docs for function based views
I went through Django REST Swagger 2.1.2 documentation. When I tried with class based views, it was working fine. But i did not find any reference on how to enable swagger for function based views as shown below: @api_view(['GET', 'POST']) def app_info(request): ... return response Most of my views.py is filled with function based views, just like above. Any help on how to enable the same will greatly appreciated. Thanks! I am using Django: 1.8; Django REST Swagger: 2.1.2; DRF: 3.6.2 -
django-reversion didnt work with MultipleChoiceField?
I have form with MultipleChoiceField. It shows me data from tuple CHOICES. Users select checkboxes and then I use that selected data to create new objects (in my case requirements) inside view. When I try to use django-reversion in my view it raise Error. Do you have any ideas why reversion.set_user(request.user) and reversion.set_comment('CREATE') dont work? models.py: @reversion.register() class Requirement(models.Model): code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) forms.py: CHOICES = ( ('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ) class RequirementAddForm(forms.ModelForm): symbol = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=CHOICES,) class Meta: model = Requirement fields = ('symbol',) view.py: @reversion.create_revision() def _requirement_add(request): if request.method == 'POST': form = RequirementAddForm(request.POST) if form.is_valid(): group_requirement_list = dict(CHOICES) # {'C': 'Name C', 'A': 'Name A', 'B': 'Name B'} symbols = form.cleaned_data.get('symbol') # Selected values: ['A', 'B', 'C'] group_requirement = list_group_requirement_form.save(commit=False) for symbol in symbols: group_requirement.project = project group_requirement.symbol = symbol group_requirement.name = group_requirement_list[symbol] group_requirement.pk = None group_requirement.save() reversion.set_user(request.user) # ??? reversion.set_comment('CREATE') # ??? ERROR: Traceback (most recent call last): File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
.env 'PAYPAL_API_USERNAME' is not defined
I am trying to set my sensitive data into my .env file. I did some researched and created this file successfully. https://ultimatedjango.com/learn-django/lessons/handling-sensitive-keys/ https://django-environ.readthedocs.io/en/latest/ I am able to set my secret key and database settings and access it through my settings.py, everything works fine. Like for example - env.db()SECRET_KEY = os.environ["SECRET_KEY"] DATABASES = { 'default': env.db(), # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ } And database details prints in my python shell. And django-oscar runs with no problem. Now, I am trying to set my Paypal details within the same .env file, but seems to be having problems. in my .env file I have the setting as - #PAYPAL SETTINGS export PAYPAL_MODE=sandbox # sandbox or live export PAYPAL_CLIENT_ID=my_paypal_client_id export PAYPAL_CLIENT_SECRET=my_payal_secret #PAYPAL SETTINGS export PAYPAL_API_USERNAME=mypaypalusername.com export PAYPAL_API_PASSWORD=my_password export PAYPAL_API_SIGNATURE=my_signature In my settings.py I am trying to make a reference to it so my application can access it - #PAYPAL SETTINGS PAYPAL_API_USERNAME = os.environ["PAYPAL_API_USERNAME"] PAYPAL_API_PASSWORD = os.environ[PAYPAL_API_PASSWORD] PAYPAL_API_SIGNATURE = os.environ[PAYPAL_API_SIGNATURE] import paypalrestsdk PAYPAL_MODE=os.environ['PAYPAL_MODE'] PAYPAL_CLIENT_ID=os.environ['PAYPAL_CLIENT_ID'] PAYPAL_CLIENT_SECRET=os.environ['PAYPAL_CLIENT_SECRET'] I get errors when running server - PAYPAL_API_USERNAME=os.environ[PAYPAL_API_USERNAME] NameError: name 'PAYPAL_API_USERNAME' is not defined I have done some research but not got an answer specifically for this problem. Please, can somebody kindly point me to the … -
Architecture inquiry for chatbot embedded python web application
I am new to programming and would like to ask for help structuring my project. I apologize ahead of time if I use a word incorrectly. I would like to build a python based web application. In place of the banner, I want to embed a chatbot written in python. I downloaded django and set up the provided application on my localhost http://127.0.0.1:8000/ I have a python script I wrote from scratch that I would like to use. I am not sure of my next steps having no prior experience. My goal would be to create a webpage with HTMl/CSS (web responsive) and my guess would be to have a DIV tag linked to the python script. Question: What term should I google so I can learn more about linking/embed/? python scripts to web apps? -
KeyError: u'editable' when performing ./manage.py migrate for the first time
I recently upgraded from Django 1.3 to 1.8 and have been experiencing issues trying to get setup on migrations. Previously used South and have uninstalled it through settings.py and deleted their folders in each app. When trying to setup migrations I get this error: root@ip:/home/# python manage.py migrate Operations to perform: Synchronize unmigrated apps: web_forms, staticfiles, tinymce, messages, miscellaneous, generalpagess, gallery, template, import, navigation, frontpage, association Apply all migrations: admin, contenttypes, sites, auth, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/usr/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 222, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 100, in migrate state.apps # Render all real_apps -- performance critical File "/usr/lib/python2.7/dist-packages/django/utils/functional.py", line 59, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/lib/python2.7/dist-packages/django/db/migrations/state.py", line 166, in apps return StateApps(self.real_apps, self.models) File "/usr/lib/python2.7/dist-packages/django/db/migrations/state.py", line 226, in __init__ self.real_models.append(ModelState.from_model(model, exclude_rels=True)) File "/usr/lib/python2.7/dist-packages/django/db/migrations/state.py", line 345, in from_model name, path, args, kwargs = field.deconstruct() File "/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", … -
django group by queryset in form ModelChoiceField
I have a model having image and reference field (reference is a string value). I need to filter the images list by reference, and a reference can have multiple images. Now I'm wishing a dropdown menu having reference field values. How can I do that. -
Shopify App Development that supports multiple platforms For eg. Shopify, Bigcommerce etc
If we are to build an app that supports multiple e-comm platforms like Shopify, Bigcommerce, Magento, Generic 3rd party API etc. , what should be our approach ? Should we build separate apps ( codebases ) for each of them or a common codebase with extensions ? P.S : I have built an app on Shopify using Python, Django stack -
How to initialize Django ModelForms on an entire queryset?
I am building an ad manager software, and I want to use django's ModelForm system to load an entire queryset of Ad objects so that users can alter fields in an already running/existing ad. I want to do this preferably in an alternative way to the modelformset_factory method. For example, if a user has a single Ad model you could simply call that instance and load the instance into a modelForm instance called AdForm so that they can edit the ad's properties: ad_instance = Ad.objects.get(pk=1) ad_form = AdForm(instance=ad_instance) So what about if the user has 20 active ads running? How can a queryset of 20 ad instances be loaded into their respective AdForms? Thanks -
In django-rest-auth, the password reset confirm URL doesn't work--is it missing arguments?
If you look at urlpatterns in django.contrib.auth.urls, the password_reset_confirm URL takes uidb64 and token params, which makes sense--when clicked on, this will identify the user resetting the password. However, django-rest-auth's rest_password_reset_confirm URL doesn't take any arguments: it just goes to password/reset/confirm/. How can it work? I get the following 500 error when submitting my email to reset my password, and I'm not surprised--the error makes sense: NoReverseMatch: Reverse for 'password_reset_confirm' with arguments '()' and keyword arguments '{u'uidb64': 'NA', u'token': u'4lj-65cd7b4219c9206126b4'}' not found. What I don't understand is it seems like such a basic thing that I must be doing something wrong--otherwise it seems like everyone using django-rest-auth would get this error because the arguments are clearly missing in the URL definition. Has anyone else experienced it and if so, did you update the URL to fix it? -
Django ProgrammingError column does not exist
I've recently migrated to postgresql, I was not sure about the cause of the problem but column does not exist error is showing up. ProgrammingError at /admin/mtsauth/authorms/ column mtsauth_authorms.nihgrants does not exist LINE 1: ..."secfirstname", "mtsauth_authorms"."seclastname", "mtsauth_a... this is migrations file migrations.CreateModel( name='AuthorMS', fields=[ ('firstname', models.CharField(max_length=120)), ('lastname', models.CharField(max_length=120)), ('ArticleId', models.AutoField(primary_key=True, `enter code here`serialize=False)), ('secfirstname', models.CharField(blank=True, default='None', max_length=120)), ('seclastname', models.CharField(blank=True, default='None', max_length=120)), ('nihgrants', models.BooleanField(default=False)), ('country', models.CharField(choices=[('INDIA', 'INDIA'), ('US', 'USA'), ('UK', 'UK'), ('RUSSIA', 'RUSSIA')], max_length=50)), ('seccountry', models.CharField(blank=True, choices=[('INDIA', 'INDIA'), ('US', 'USA'), ('UK', 'UK'), ('RUSSIA', 'RUSSIA')], default='None', max_length=50)), ('affliation', models.CharField(default='None', max_length=100)), ('secAffliation', models.CharField(blank=True, default='None', max_length=100)), ('code', models.IntegerField(default=101, max_length=10000)), ], ), -
JWT, how to write about the user's Permission in Django without session?
It had a permission below when my server was cookie-based authentication. class IsAuthenticatedAndStudentOwner(BasePermission): message = 'You must be a student.' def has_permission(self, request, view): return request.user.is_authenticated() and smart_str(request.user.identity) == 'student' def has_object_permission(self, request, view, obj): return obj.student.user == request.user Then, when i use JWT, that request.user returns AnonymousUser. # login(request, user_obj) payload = jwt_payload_handler(user_obj) token = jwt_encode_handler(payload) data['token'] = token return data So, how can i write this permission without session? -
django login test with selenium
In my application I have a login page. I am currently using User model from django.contrib.auth.model. This is my test with Selenium, based on PhantomJS (because I am in a container): class TestLogin(TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.driver.set_window_size(1120, 550) self.user = User.objects.create_user(username='this_is_a_test', password="dockercompose") def test_good_login(self): expected_url = "http://localhost:8080" self.driver.get("http://localhost:8080/login") self.driver.find_element_by_id('id_username').send_keys("this_is_a_test") self.driver.find_element_by_id('id_password').send_keys("dockercompose") self.driver.find_element_by_id('login_form').submit() print(self.driver.page_source) assert self.driver.current_url == expected_url My test failed, and this is the print(self.driver.page_source) : <body><h2>Login</h2> <form method="post" id="login_form"> <input type="hidden" name="csrfmiddlewaretoken" value="zRNkCIYxymsGLFKcZlpLTjbfBcvZxAVFTrAQyvy2wTyiKeISZCRIkraVV7OfS6DG"> <ul class="errorlist nonfield"><li>Please enter a correct username and password. Note that both fields may be case-sensitive.</li></ul> <p><label for="id_username">Username:</label> <input type="text" name="username" value="this_is_a_test" autofocus="" maxlength="254" required="" id="id_username"></p> <p><label for="id_password">Password:</label> <input type="password" name="password" required="" id="id_password"></p> <button name="submit_button" type="submit">Login</button> </form> </body></html> I did a User.objects.all() into the test and user this_is_a_test has been created. If you can help, it could be nice :) -
Pubnub always times out in Django app
I'm building a Django app to listen to a Pubnub feed and store the messages in a database. I create a pubnub listener in my app's apps.py's AppConfig's ready() method. Upon launching my app on Heroku, I get the really unhelpful error 2017-04-26T02:17:50.038060+00:00 heroku[web.1]: Error R12 (Exit timeout) -> At least one process failed to exit within 30 seconds of SIGTERM 2017-04-26T02:17:50.038060+00:00 heroku[web.1]: Stopping remaining processes with SIGKILL 2017-04-26T02:17:50.134619+00:00 heroku[web.1]: Process exited with status 137 I suspect django wants to clean up the AppConfig process and is getting upset that there is a pubnub object hanging around in there. Is that the problem? How do I fix it? I also see that (at least implicitly by example) Heroku recommends using the twisted interface. Is it bad that I'm not? Here's the relevant code: I created a mypubnub.py based on Pubnub's hello world example: from pubnub.pubnub import PubNub from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback class MySubscribeCallback(SubscribeCallback): def presence(self, pubnub, presence): pass def status(self, pubnub, status): pass def message(self, pubnub, message): pass # I'll actually do the storage here later def create_pubnub(): pnconf = PNConfiguration() pnconf.subscribe_key = 'sub-c-blargyblargblarg' pnconf.publish_key = 'pub-c-blargyblargblarg' pubnub = PubNub(pnconf) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('achannel').execute() return pubnub I instantiate … -
Django how to see the cookies being set and unset?
I'm using response.set_cookie() to set cookies and response_delete_cookie() to delete it. I'd like to see if things are working as intended, but I don't know where to look for the cookies being set. -
Accessing a SerializerMethodField in create()
I want to create a password on server side and send it back to the user. Below is the code I have written: class ASCreateSerializer(serializers.Serializer): name = serializers.CharField(write_only = True) password = serializers.SerializerMethodField() def get_password(self, obj): from django.utils.crypto import get_random_string password = get_random_string(length=16) return password def create(self, validated_data): name = validated_data['name'] as = AS.objects.get_or_create(name = name, password = validated_data['password'] ) I am getting a key error for 'password'. How can I access the value of a SerializerMethodField in create()? -
Django CMS unable to add a child to a nested plugin
For some reason I can't seem to add a child plugin: I want to achieve the following hierarchy: Faq row Faq column Faq However when I press the plus sign of the column nothing happens and I am not able to drag the Faq plugin within the Faq column. Any idea? My plugins definitions: from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext_lazy as _ from .models import FaqPluginModel class FaqRowPlugin(CMSPluginBase): name = u'Faq Row' module = _("Fundbox") render_template = "faq_row.html" cache = False allow_children = True class FaqColumnPlugin(CMSPluginBase): name = u'Faq Column' module = _("Fundbox") render_template = "faq_column.html" cache = False allow_children = True require_parent = True class FaqPlugin(CMSPluginBase): name = u'Faq' module = _("Fundbox") model = FaqPluginModel render_template = "faq.html" cache = False plugin_pool.register_plugin(FaqRowPlugin) # register the plugin plugin_pool.register_plugin(FaqColumnPlugin) # register the plugin plugin_pool.register_plugin(FaqPlugin) # register the plugin -
Passing POST data from form into GET method to generate graph
I'm trying get user input from a HTML form and use that value to populate a ChartJS graph in my Django app called DisplayData which has a template called Display.html. I have an API set up to pass data into ChartJS called display/api/chart/data/ which I use to get two lists to populate the Chart with. In order make the Chart, I am getting data from my models and graphing the data value (integer) against the timestamp of when the value of recorded. This is one of the queries that gets the data: all_entries = models.Entries.objects.all().filter(parent=2) Right now, I have it hardcoded to one time of data value (as seen above, to the integer 2), but I would like the user to have a form where they can input a number and submit it, generating the chart by using that integer as a filter. The user input integer would be placed inside the parent= portion of the code above. I have the following urls set up. urls.py urlpatterns=[ url(r'^$',views.DisplayView, name='DisplayView'), url(r'^api/data/$', views.get_data, name='api-data'), url(r'^display/api/chart/data/$', views.ChartData.as_view()), url(r'^logs/', views.LogDisplay, name='Display-Logs'), ] In order to achieve this, I have added a form in my Display.html file above the code for ChartJs as follows. Display.html … -
Certbot: Invalid response http://www.example.org/.well-known/acme-challenge
I'm working through https://serversforhackers.com/video/letsencrypt-for-free-easy-ssl-certificates and https://certbot.eff.org/docs/intro.html , trying to add an ssl certificate to my site (django 1.8 on nginx on ubuntu 16.04). I have been able to do this before a few months ago using the standalone option (Certbot cannot reach nginx webroot running django), but this time I want to get the certbot-auto script working so I can run it on a chron job. I tried: deploy@server:/opt/certbot$ sudo ./certbot-auto certonly --webroot -w /var/www/html -d example.org -d www.example.org Saving debug log to /var/log/letsencrypt/letsencrypt.log Cert is due for renewal, auto-renewing... Renewing an existing certificate Performing the following challenges: http-01 challenge for example.org http-01 challenge for www.example.org Using the webroot path /var/www/html for all unmatched domains. Waiting for verification... Cleaning up challenges Failed authorization procedure. www.example.org (http-01): urn:acme:erruthorized :: The client lacks sufficient authorization :: Invalid response http://www.example.org/.well-known/acme-challenge/6j3QzM4LGMRWaLYZXYTR98: " If I paste http://www.example.org/.well-known/acme-challenge/6j3QzM4LGMRWaLYZXYTR98: " into the browser I get a 404 like in the screenshot. Is it possible to set django to allow the challenge to 'pass through ' the routing without generating a django error? -
Django optional choices
Currently, I have the following field in my model event_duration = models.PositiveIntegerField(blank=False, null=False, choices=EVENT_DURATION_OPTIONAL_CHOICES, validators=[ MaxValueValidator(270), MinValueValidator(1) ], ) and in my forms.py I have def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.helper['event_duration'].wrap(DropDownTextInput) and my DropDownTextInput: class DropDownTextInput(Field): """ Layout object for rendering dropdowntextinput:: DropDownTextInput('field_name') """ template = "widgets/dropDownTextFieldRendered.html" def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): return super(DropDownTextInput, self).render( form, form_style, context, template_pack=template_pack, extra_context={'inline_class': 'inline'} ) I want it to allow people to select from the the choices I provide, but if I they really wanted to enter their own integer, they could also do so. It currently renders exactly like I wanted (which is the same as in here), but if the user enters a value which is not in the choices list, the form becomes invalid and returns a message Select a valid choice. 99 is not one of the available choices. -
Django CMS get all models defined in the admin
I am building a FAQ plugin that will display a list of questions and answers on my Django CMS site. I have the following model: class Faq(models.Model): question = models.CharField( 'question', blank=False, default="", help_text=u'Please type in the question', max_length=256, ) answer = HTMLField(configuration='CKEDITOR_SETTINGS_BASIC', null=True, help_text=u'Please provide an answer. if you paste HTML make sure to cmd+shift+v for plain paste') def __unicode__(self): # Python 3: def __str__(self): return self.question Which I defined in the admin: class FaqAdmin(admin.ModelAdmin): model = Faq extra = 3 admin.site.register(Faq, FaqAdmin) And added a few instances as content. For now in the plugin defines 10 questions: class FaqPluginModel(CMSPlugin): faq1 = models.ForeignKey(Faq, related_name='faq1+') faq2 = models.ForeignKey(Faq, related_name='faq2+') faq3 = models.ForeignKey(Faq, related_name='faq3+') faq4 = models.ForeignKey(Faq, related_name='faq4+') faq5 = models.ForeignKey(Faq, related_name='faq5+') faq6 = models.ForeignKey(Faq, related_name='faq6+') faq7 = models.ForeignKey(Faq, related_name='faq7+') faq8 = models.ForeignKey(Faq, related_name='faq8+') faq9 = models.ForeignKey(Faq, related_name='faq9+') faq10 = models.ForeignKey(Faq, related_name='faq10+') def __unicode__(self): return self.faq1.question However this approach is not scalable. I am looking for a way to fetch all the models from the admin and render them in the template's html. Something along the lines of: <div class="col-xs-12 col-sm-6"> <div class="box"> --->> {% for every faq model render this: %} <<-- <div class="question"> <div class="question-title"> What are your supported … -
Creating Process Dictionary
My Goal: I need to create a function that retrieves the PID and Name of each process and returns them in a dictionary. I will be uploading this to Django and really need two different dictionaries. 1 with every running process name and PID and another with all installed names and PIDs. So far I can get it to print the dictionary well but not return correctly. Maybe I am calling it wrong. I am newer to this. import psutil def pid_name(): for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name']) except psutil.NoSuchProcess: pass else: return pinfo If you were to sub "return" for print the dict will print fine. How to I call that dict from here? Is it even returning correctly?? -
OneToOneField in Django admin not editable
I've stripped my code all the way down and am left with these simple models: models.py class Member(models.Model): property = models.OneToOneField(Property, on_delete=models.CASCADE, blank=True, null=True) class Property(models.Model): .... And this very basic admin for Members: admin.py class MemberAdmin(admin.ModelAdmin): pass admin.site.register(Member, MemberAdmin) While logged into the admin as a superuser, as expected on the Member admin page I see a dropdown to choose a Property model. When there is already a Property model selected, the usual pencil icon to edit the selected Property model is faded out, so I cannot click on it. How can I activate this icon so that I can get the usual pop-up to edit the related Property from this Member page? I can't figure out what I am missing. Thank you! -
Django makemigrations and migrate unbearably slow / freeze
I am using Django 1.8.6 for a small project. It has about 5 small models. When I run makemigrations and migrate locally on my Mac, it takes about 3-4 seconds to finish and apply migrations to the SQLite DB. However, when I try doing the same thing on the production server, each of the commands freezes. Here is the point at which it freezes: Operations to perform: Synchronize unmigrated apps: staticfiles, sekizai, sortedm2m, mptt, absolute, aldryn_reversion, aldryn_common, messages, treebeard, emailit, aldryn_apphooks_config, aldryn_translation_tools, parler, aldryn_boilerplates, djangocms_admin_style Apply all migrations: djangocms_video, page_extensions, aldryn_forms, filer, email_notifications, aldryn_newsblog, djangocms_picture, aldryn_people, menus, djangocms_text_ckeditor, djangocms_link, sessions, djangocms_column, djangocms_googlemap, auth, djangocms_snippet, captcha, aldryn_bootstrap3, easy_thumbnails, admin, djangocms_file, cms, taggit, reversion, contenttypes, sites, social_icon, aldryn_categories, djangocms_style Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... Why is this happening? How can I fix it? If it helps, I am using an EC2 AWS instance with CentOS as the production server.