Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return data from a table in a Django template
I am trying to display data from a website in HTML. I have created a class called Video in models.py as follows: class Video(models.Model): filename = models.CharField("File Name", max_length=100) title = models.CharField("Video Title", max_length=250) The database is migrated and I am able to insert data into it using a Django form. I have checked and there is data in the database. I have the following code in my HTML template file, but the page is empty when it is displayed, and is showing no data. {% for video in Video %} <div class="row"> <div class="col-md-3"> <a href="{{ video.filename }}">{{ video.title }}</a> </div> </div> {% endfor %} Why isn't this displaying any data in the rendered HTML page? Edit: This is the relevant code from the view: def listvideos(request): """Renders the listvideos page.""" assert isinstance(request, HttpRequest) return render( request, 'app/listvideos.html', ) -
Understanding django's logging
I am a bit confused on how django is handling the logging. I have this setting for loggers in my settings: Logging settings LOGGING = { ... 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_BASE_DIRECTORY + '/django.log', 'maxBytes': LOGFILE_SIZE, 'backupCount': LOGFILE_COUNT, 'formatter': 'verbose' }, 'mail_admins': { 'level': 'ERROR', #'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['file','mail_admins'], 'level': 'INFO', 'propagate': True, }, 'app1': { 'handlers': ['file','mail_admins'], 'level': 'DEBUG', 'propagate': True, }, ... }, } As one can see, I have 2 handlers defined for django and app logs, file and mail_admins. The log level for file is debug. Hence I assume all logs which are debug and above shall use this handler. The level for mail_admins is error. The problem that I am seeing though is that in case of 500 errors while email handler runs and sends the mail there is no logging on the file. -
How to access MEDIA_ROOT files within the view
How do i get MEDIA_ROOT files in the view function, am i suppose to use request.FILES[path]? if so then how do i get the file i want by using settings.MEDIA_ROOT request.FILES[settings.MEDIA_ROOT/file] -
MySql copy data from production to development DB keeping FK references
I am trying to figure out a way to copy data from the production DB(I'll call it prod DB from now on) into the development(I'll call it dev DB from now on). My system is: MySQL Python - Django(if it is any help) The sittuation is like that: assume I have all the tables, and even the rows needed for me from the prod DB the tables have FK refs between them. the PK on every table is self inc. I need to keep data in the dev DB, meaning my mission is to "merge" the data from prod to dev. I've read about mysql dump and not sure it will work since the pk and the fk connection will be all wrong(correct me if I am wrong), So I've been thinking about implementing it on my own, but just not sure about how to preserve the fk connection since after the export of data from prod it will be with the PK of the prod and they will all change when inserted to dev. so far my best idea is to use python and save a mapping of old key to new key but that is a messy way … -
Does not display an image! Django
Does not display an image! image is exists, dut django didn't display any images on page, how to fix this? this is my models.py class All_Images_Of_The_Series(models.Model): to_series = models.ForeignKey(Series, on_delete=models.CASCADE, blank=True, default=None) image_of_all = models.ImageField(upload_to="previews/previews_for_series/", default=None,width_field="width_field", height_field="height_field") is_poster = models.BooleanField(default=False) is_active = models.BooleanField(default=True) width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return "Active: |%s| and Poster: |%s| " % (self.is_active, self.is_poster) class Meta: ordering = ["-timestamp"] verbose_name = 'All_Images_of_the_Series' verbose_name_plural = 'All_Images_of_the_Series' this is my views.py def homeview(request, *args, **kwargs): full_path = All_Images_Of_The_Series.objects.all() context = {"full_path":full_path,} return render(request, 'home.html', context) this is my template <div class="col-sm-3 right-side"> <div class="new-movies-block"> <a class="header" href="#/new/"> <div class="title">Новинки</div> </a> {% for one_to_one_path in full_path %} <div class="movie-spacer" ></div> <a class="new-movie" href="{{ one_to_one_path.to_series.get_absolute_url }}" title="{{ one_to_one_path.to_series.eng_name }}"> <div class="title-info"> {{ one_to_one_path.to_series.season_of_this_series.number_of_season }} сезон {{ one_to_one_path.to_series.number_of_series }} серия </div> <div class="date">{{ one_to_one_path.to_series.timestamp_rus }}</div> <img src="{{ one_to_one_path.image_of_all.url }}" class="img-responsive"> </a> {% endfor %} </div> </div> -
Complex aggregation in Django
Using Django rest framework 3.x and Django 1.1.10. I have a model that represents users. When I list all the users by accessing /users/ endpoint in DRF the list has to include some more data that is related to users via another model, called Owner. Each Item has an Owner and Owners have Users. I made an extra property on the User model and it just returns a JSON array of the data. This is something that I can't change, because it is a requirement on the front-end. I have to return a total number of items that are related to each user and there are three different counts to perform to get the data. I need to get multiple count()'s of items on the same model but with different conditions. Doing these separately is easy, two are trivial and the last one is more complicated: Item.objects.filter(owner__user=self).count() Item.objects.filter(owner__user=self, published=True).count() Item.objects.filter(Q(history__action__name='argle') | Q(history__action__name='bargle'), history__since__lte=now, history__until__gte=now, owner__user=self).count() The problem is because this is run for every user and there are many of them. In the end this generates more than 300 DB queries and I would like to bring these to a minimum. So far I've came up with this: Item.objects.filter(owner__user=self)\ .aggregate(published=Count('published'), … -
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 …