Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django backend connect to frontend react native
i have problem in my App with react native my backend use Django to make it and I'm create app with react native but when i use to fetch() to connect the backend its won't work its my fetch function fetch('http://pezeshkam.com/api/v1/doctors/') .then((response )=> response.json()) .then((json)=>{ console.log(json); }) .catch(error =>console.log(error)) how to setup in my code for connect to react native? its response my console : TypeError: Network request failed at XMLHttpRequest.xhr.onerror (fetch.js:441) at XMLHttpRequest.dispatchEvent (event-target.js:172) at XMLHttpRequest.setReadyState (XMLHttpRequest.js:548) at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:381) at XMLHttpRequest.js:487 at RCTDeviceEventEmitter.emit (EventEmitter.js:181) at MessageQueue.__callFunction (MessageQueue.js:306) at MessageQueue.js:108 at MessageQueue.__guard (MessageQueue.js:269) at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:107) -
Why I get "Relation fields do not support nested lookups"?
I am trying to display all Expenses I am getting for certain building. However, expences can be or for a particular unit in the building or for particular extra property in the building. So for this in my view I am filtering my data like this: expense_list = Expense.objects.filter(Q(payment_date__range=[start_date, end_date],noteunit__unit__building = building) | Q(payment_date__range=[start_date, end_date],noteextra__unit__building = building) ) But getting error:Relation fields do not support nested lookups How to resolve it? And What I am doing wrong? -
How to test a new user activation in Django?
I am trying to test django.contrib.auth-based user signup view with django-nose, where an activation link is being sent to a new user: def signup(request): if request.method == 'POST': user_form = SignUpForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.is_active = False user.save() user.profile.user_type = profile_form['user_type'].data user.save() current_site = get_current_site(request) subject = 'activation email' message = render_to_string('registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: user_form = SignUpForm() profile_form = ProfileForm() return render(request, 'registration/signup.html', { 'user_form': user_form, 'profile_form': profile_form }) Currently I use Django built-in email back-end, so that activation email is being sent to the server terminal. I want to test the activation view which requires uid and token. Is there any way to access the email sent to the user? Is there any other way to test that? Regenerating token in the test does not work, because hash value is generated using timestamp. -
Django get_or_create returns False
I'm creating a population script, from an MysqlDatabase to Django Models. Im looping through my receiving data from the Mysql and thats going good. Now I have to write it to the Django Database... mdl, succeeded = models.User.objects.get_or_create( name=name, password=password, email=email ) I'm printing succeeded so I can see what the feedback is, but all it gives me is False My Django Model User is edited so all fields can be blank and allows NULL or have a default My Model User: username = models.CharField(max_length=20, blank=True, null=True) slug = models.SlugField(null=True, blank=True) email = models.EmailField(unique=True, null=True) name = models.CharField("First and last name", max_length=100) uses_metric = models.BooleanField(default=True) position = models.CharField("Position", max_length=70, blank=True, null=True,) utility = models.ForeignKey(Utility, default=1, blank=True, null=True) supplier = models.ForeignKey(Supplier, default=1, blank=True, null=True) currency = models.ForeignKey(Currency, default=1) phone = models.CharField("Direct phone number", max_length=40, blank=True, default='+') gets_notifications_on_reply = models.BooleanField("Receive notifications", default=False) memberlist = models.BooleanField("Show member in memberslist", default=True) registration_date = models.IntegerField(default=floor(time.time()), blank=True, null=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Deselect this instead of deleting accounts.' ), ) USERNAME_FIELD = 'email' -
Store Data from different websites in Django Database
I would like to create a Django project to save tags or pixels fires from different websites in a my database: For this reason, create the following Django model. This one, include all variables that I want to save class Purchase (models.Model): account = models.CharField(max_length=250, blank=True) user_cookie = models.CharField(max_length=250, blank=True) session_id = models.CharField(max_length=250, blank=True) …. For collect data from other websites I saw this method. I don’t know if it’s the base way to collect this data. <script> var e= document.createElement("script"); e.async = true; e.src =e.src ="https://mydomain.js;m=001;cache="+Math.random()+ "?account=0001"+ "&user_cookie=" + String(utag_data.uidCookie) + "&session_id =" + utag_data.Session_ID); var s =document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(e,s); </script> Finally, I would like to collect this javascript request in my Django database. Which url I need to use? How can store this data in my dataset? Thank you for your help -
How to start and stop django server from java servlet?
I have two separate applications one written in django python and other one in java. These applications are communicating with each other through API's now I want to stop django server from java servlet and also want to restart it again from java servlet. Is it possible to do this ? -
authentication Django on LDAP server
I would like my web application authenticate users on an ldap server (only for username and password), but that the permissions reside on django. Not all ldap users must have access to the web application. In particular, I would like to allow users to see only a few records (for example, suppose there is a model with a city field: some users should only be able to see records whose city field is london, others whose city is milano, etc.). How can i define django permissions if users are defined on ldap? How can I define the user's application admin if users are defined on ldap? Do I need to implement a double authentication? Do I have to define ldap users who can access the web application even on django? What is the best way to proceed? Do you have any suggestions? Examples? Thanks pacopyc -
Django dynamic HTML table refresh with AJAX
First of all, I am new with Django, and pretty much completely unfamiliar with AJAX and jQuery. So I'm trying to achieve a HTML table, that is dynamically refreshed every X amount of seconds with help from AJAX, but I can't seem to get my code to work. I've already used the example provided in this question: https://stackoverflow.com/a/34775420/6724882 (If I had enough rep, I would have either replied to that question, or asked help from chat, but I don't have that luxury yet) I've been trying to get this to work for 10+ hours, and I start to feel helpless. I've been searching the web like crazy, but I'm overwhelmed by all the different ways of doing this, and every question and answer seems to be either too many years old, or just not relevant to my app. So, I got couple questions. Should I include the script in its own separate file, and not in the HTML file (in my case, displaykala.html). If so, should that file be in the static/js folder, or somewhere else? Do I need to include AJAX/JS somewhere separately, in order for the script to work? Am I clearly doing something wrong, or is the … -
Django settings for Microsoft exchange
How to configure setting for send_mail that using Microsoft Exchange. Can we still use the settings below. EMAIL_PORT = 443 EMAIL_USE_TLS = True EMAIL_HOST = 'host' EMAIL_HOST_USER = 'username' EMAIL_HOST_PASSWORD = 'password' When i try to send email i got an error Connection timed out -
Django query optimization for merging two tables . update_or_create
I am retrieving some info from another table and want to update or create a new row in my local table . I am following this logic , its working fine but taking a huge time approx 150sec , to complete 10000 loops . Is there anything i can do to make it work fast and optimize . And i am already using celery background process for this thing PS : I HAVE NEARLY 8 FIELDS TO CREATE OR UPDATE ACCORDING TO ID . for row in results: id = row['id'] id = row['id'] check = Agents.objects.update_or_create(id=id, defaults={ 'abc': abc, },) -
Broken django-debug-toolbar panels with sub domains configuration
I'm working on djangoproject.com website with Django Debug Toolbar configured in this dev settings. I founded an issue with django-debug-toolbar that I reported in the issue #796 of djanoproject.com but after some test I think it's only a configuration problem and we need help to solve it. All the below sentence are related with the code on branch master used locally. Django Debug Toolbar works well for www , for example, if I open http://www.djangoproject.dev:8000/ I can show the toolbar and open the SQL panel. If I try to open for example http://docs.djangoproject.dev:8000/en/1.11/ I can see the toolbar but I got 0: error if I try to open SQL panel This is the message I saw on browser console: Failed to load http://www.djangoproject.dev:8000/debug/render_panel/?store_id=212b2bb5adc54a3a81b97b6da5547d4c&panel_id=SQLPanel: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://docs.djangoproject.dev:8000' is therefore not allowed access. I can see all the data if I open directly the url: http://www.djangoproject.dev:8000/debug/render_panel/?store_id=212b2bb5adc54a3a81b97b6da5547d4c&panel_id=SQLPanel I think the problem is that the toolbar is trying to open a www. for the panel instead of a docs. url but I don't know how to update the settings to fix this. Can you suggest to us how to change the dev settings to use django-debug-toolbar … -
Django UpdateView is giving empty forms without object data
I'm using UpdateView to edit data using forms. After I click to edit the popup using modal is showing a few forms with blank data! It doesn't retrieve the previous data that was in the Database. Anyone know what should I add? I am stuck with this edit for about a week :( If anyone has a clue I will be grateful! Thank you! views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() forms = {} if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() for post in posts: forms[post.id] = HomeForm(instance=post) args = {'form' : form, 'forms': forms, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks if validation of the forms passed post = form.save(commit=False) post.save() form … -
Forbidden (403) CSRF verification failed. Request aborted when login to admin mezzanine
i deploy project web into server but when i login addmin page it has an error "Forbidden (403) CSRF verification failed. Request aborted." . It's normal when i test in local. my project used mezzanine cms and i use default login of mezzanine I need some help -
django ajax call from template
I have a model: class ok(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, default='') rfc = models.CharField(max_length=255) I have model form. class okForm(ModelForm): class Meta: model = ok fields='__all__' I am getting first 3 fields: name, project, story user manual entry. Now I want to populate the last two fields with respect to third field using AJAX call from views function that will query to mysql database. I have a fucntion in views.py def get(self, request): name = request.GET.get('name') project = request.GET.get('project') story = request.GET.get('story') if name and project and story: try: obj = ok.objects.get(name=name, project=project, story=story) return JsonResponse(data={ 'depends_on': ok_obj.depends_on, 'rfc': ok_obj.rfc}, status=200) except ok.DoesNotExist: pass return JsonResponse(data={'error': 'bad request'}, status=400) How i will make the ajax call with the third value the user just filled, as he has not submitted the form yet . Kindly help. -
How to serializer the openstack.compute.v2.server.ServerDetail?
How to serializer the openstack.compute.v2.server.ServerDetail ? I use the openstacksdk for develop my own openstack app. But when I get the generator of my connection: user_conn = UserOpenstackConn() openstack_servers_gen = user_conn.conn.compute.servers() I can use the list() to convert the openstack_servers_gen to list: : [openstack.compute.v2.server.ServerDetail(OS-EXT-AZ:availability_zone=, key_name=None, hostId=, os-extended-volumes:volumes_attached=[], OS-SRV-USG:launched_at=None, OS-EXT-STS:vm_state=error, flavor={'id': '5c5dca53-9f96-4851-afd4-60de75faf896', 'links': [{'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/flavors/5c5dca53-9f96-4851-afd4-60de75faf896', 'rel': 'bookmark'}]}, updated=2017-11-27T10:29:50Z, accessIPv4=, image={'id': '60f4005e-5daf-4aef-a018-4c6b2ff06b40', 'links': [{'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/images/60f4005e-5daf-4aef-a018-4c6b2ff06b40', 'rel': 'bookmark'}]}, created=2017-11-27T10:29:49Z, metadata={}, links=[{'href': 'http://controller:8774/v2.1/233cf23186bf4c52afc464ee008cdf7f/servers/3db46b7b-a641-49ce-97ef-f17c9a11f58a', 'rel': 'self'}, {'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/servers/3db46b7b-a641-49ce-97ef-f17c9a11f58a', 'rel': 'bookmark'}], OS-DCF:diskConfig=MANUAL, id=3db46b7b-a641-49ce-97ef-f17c9a11f58a, user_id=41bb48ee30e449d5868f7af9e6251156, OS-SRV-USG:terminated_at=None, name=123456, config_drive=, accessIPv6=, OS-EXT-STS:power_state=0, addresses={}, OS-EXT-STS:task_state=None, status=ERROR, tenant_id=233cf23186bf4c52afc464ee008cdf7f), openstack.compute.v2.server.ServerDetail(OS-EXT-AZ:availability_zone=, key_name=None, hostId=, os-extended-volumes:volumes_attached=[], OS-SRV-USG:launched_at=None, OS-EXT-STS:vm_state=error, flavor={'id': '5c5dca53-9f96-4851-afd4-60de75faf896', 'links': [{'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/flavors/5c5dca53-9f96-4851-afd4-60de75faf896', 'rel': 'bookmark'}]}, updated=2017-11-27T10:27:42Z, accessIPv4=, image={'id': '60f4005e-5daf-4aef-a018-4c6b2ff06b40', 'links': [{'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/images/60f4005e-5daf-4aef-a018-4c6b2ff06b40', 'rel': 'bookmark'}]}, created=2017-11-27T10:27:41Z, metadata={}, links=[{'href': 'http://controller:8774/v2.1/233cf23186bf4c52afc464ee008cdf7f/servers/721467ac-440f-4784-b825-f6155c65abee', 'rel': 'self'}, {'href': 'http://controller:8774/233cf23186bf4c52afc464ee008 ....... But how can I make it to be serializable in my project? -
Create password protected zip file Python
I'm using following code to create password protected zip file, from a file uploaded by user, in my Python34 application using zipFile. But when I open the zip file from windows, it doesn't ask for the password. I will be using the same password to read zip files from python later on. What am I doing wrong? Here's my code: pwdZipFilePath = uploadFilePath + "encryptedZipFiles/" filePath = uploadFilePath if not os.path.exists(pwdZipFilePath): os.makedirs(pwdZipFilePath) #save csv file to a path fd, filePath = tempfile.mkstemp(suffix=source.name, dir=filePath) with open(filePath, 'wb') as dest: shutil.copyfileobj(source, dest) #convert that csv to zip fd, pwdZipFilePath = tempfile.mkstemp(suffix=source.name + ".zip", dir=pwdZipFilePath) with zipfile.ZipFile(pwdZipFilePath, 'w') as myzip: myzip.write(filePath) myzip.setpassword(b"tipi") -
Python suddenly stopped when matplot image was drawn
Python suddenly stopped when matplot image was drawn. I wanna show matplot image's table in index.html.Now I wrote in views.py def past_result(request): return render(request, 'index.html', {'chart': _view_plot(request)}) def _view_plot(request): dates = [20150805,20160902,20170823] heights = [5,6,3] df = pd.DataFrame() df['DATE'] = dates df['SCORE'] = heights col_width = 3.0 row_height = 0.625 font_size = 14 header_color = '#40466e' row_colors = ['#f1f1f2', 'w'] edge_color = 'w' bbox = [0, 0, 1, 1] header_columns = 0 ax = None if ax is None: size = (np.array(df.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height]) fig, ax = plt.subplots(figsize=size) ax.axis('off') mpl_table = ax.table(cellText=df.values, bbox=bbox, colLabels=df.columns) mpl_table.auto_set_font_size(False) mpl_table.set_fontsize(font_size) for k, cell in six.iteritems(mpl_table._cells): cell.set_edgecolor(edge_color) if k[0] == 0 or k[1] < header_columns: cell.set_text_props(weight='bold', color='w') cell.set_facecolor(header_color) else: cell.set_facecolor(row_colors[k[0] % len(row_colors)]) plt.show() return ax in index.html <img src="data:image/png;base64,{{ chart }}" width="700px" height="500px" alt="RESULT"/> When I read past_result method,Python suddenly stopped .I do not know why.Why does such a error happen? I read this url as reference How to save the Pandas dataframe/series data as a figure? .How should I fix this? -
YAML Exception . Invalid Yaml
I am trying to upload my Django rest framework application in AWS elasticbeanstalk. I followed the steps from here http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I did exactly what is mentioned there and ended up in an error on creating environment. WARNING: You have uncommitted changes. Creating application version archive "app-989c-171129_120334". Uploading TestApi/app-989c-171129_120334.zip to S3. This may take a while. Upload Complete. ERROR: InvalidParameterValueError - The configuration file .ebextensions/packag s.config in application version app-989c-171129_120334 contains invalid YAML or JSON. YAML exception: Invalid Yaml: while scanning for the next token found character '\t' that cannot start any token in "<reader>", line 6, column 1: ^ , JSON exception: Invalid JSON: Unexpected character (p) at position 0.. Update the configuration file. My files contains exactly same info as mentioned in the docs. .ebextensions\django.config :- option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py Where am I going wrong ? -
How can I get values checkbox django
How to get values from database in checkbox and then insert selected values in database MySQL . How can create my views form template ? Any help is greatly appreciated -
get_thumbnailer renders different image than source image
I'm using get_thumbnailer from the sorl-thumbnail package and the cached image that is rendered in the key value store (used in conjunction with S3 storage pointing to a bucket) is different image than the source (ie: image = ImageField(upload_to='images')) My use case is that I have images being uploaded from camera on mobile via a HTML5 <input type="file" accept="image/*" capture="camera">. For each image, a thumbnail is being produced via the get_thumbnailer method. From desktop and android uploads I have no issues, but apparently on iOS the image upload and generation via the get_thumbnailer is not consistent, for some mysterious reason which I have yet to determine. The url attribute that get_thumbnailer renders from one of the uploads from an iOS is a different image than the source image. I don't expect answers, but if you can give me some idea then that's good enough. Just say something and I will give you an up-vote. -
How to fix error on python django_auth_ldap
I have a problem! When I try to install django_auth_ldap on Windows x64, python 2.7 64. I get this error: C:\Program Files (x86)\Microsoft Visual C++ Build Tools>pip install D:\django_auth_ldap-1.3.0b3-py2.py3-none-any.whl Processing d:\django_auth_ldap-1.3.0b3-py2.py3-none-any.whl Collecting python-ldap>=2.0; python_version < "3.0" (from django-auth-ldap==1.3.0b3) Using cached python-ldap-2.5.2.tar.gz Requirement already satisfied: django>=1.8 in c:\python27\lib\site-packages (from django-auth-ldap==1.3.0b3) Requirement already satisfied: setuptools in c:\python27\lib\site-packages (from python-ldap>=2.0; python_version < "3.0"->django-auth-ldap==1.3.0b3) Installing collected packages: python-ldap, django-auth-ldap Running setup.py install for python-ldap ... error Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;file='c:\users\dmisss\appdata\local\temp\pip-build-rle0oc\python-ldap\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record c:\users\dmisss\appdata\local\temp\pip-wl8mnc-record\install-record.txt --single-version-externally-managed --compile: running install running build running build_py file Lib\ldap.py (for module ldap) not found file Lib\ldap\controls.py (for module ldap.controls) not found file Lib\ldap\extop.py (for module ldap.extop) not found file Lib\ldap\ldapobject.py (for module ldap.ldapobject) not found file Lib\ldap\schema.py (for module ldap.schema) not found creating build\lib.win-amd64-2.7 copying Lib\ldapurl.py -> build\lib.win-amd64-2.7 copying Lib\ldif.py -> build\lib.win-amd64-2.7 copying Lib\slapdtest.py -> build\lib.win-amd64-2.7 creating build\lib.win-amd64-2.7\ldap copying Lib\ldap__init__.py -> build\lib.win-amd64-2.7\ldap copying Lib\ldap\async.py -> build\lib.win-amd64-2.7\ldap creating build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls__init__.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\deref.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\libldap.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\openldap.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\ppolicy.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\psearch.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\pwdpolicy.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\readentry.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\sessiontrack.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\simple.py -> build\lib.win-amd64-2.7\ldap\controls copying … -
How to combine django-modeltranslation and django-reversion apps?
Question: how to combine django-modeltranslation and django-reversion apps? I have next problem: in models.py file I registered Slide model which has head field. This field has several other fields for translation like head_ru, head_kz, head_en. I set these fields in translation.py and settings.py files. In Slide table in DB has all this fields. Also I show all this fields I show in form where user can edit data. When user submit the form django-reversion create version only for head field and ignore other fields. How to fix this problem? models.py: from django.db import models import reversion @reversion.register() class Slide(models.Model): head = models.CharField(verbose_name='Title', max_length=200, blank=False,) translation.py: from modeltranslation.translator import TranslationOptions from modeltranslation.translator import translator from .models import Slide class SlideTranslationOptions(TranslationOptions): fields = ('head',) translator.register(Slide, SlideTranslationOptions) settings.py: LANGUAGES = ( ('ru', 'Russian'), ('en', 'English'), ('kz', 'Kazakh'), ) -
Getting ValueError While Trying to Create Category in Django
I am a beginner in Django. I am trying to add an option for adding category in my Django blog. However, I am getting this error: ValueError: invalid literal for int() with base 10: 'category' Here the codes that I have used in models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse #from tinymce import HTMLField #from froala_editor.fields import FroalaField from redactor.fields import RedactorField class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Category(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) title = models.CharField(max_length=250, verbose_name="Title") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts') content = RedactorField(verbose_name=u'Text') publish = models.DateTimeField(default=timezone.now) category = models.ForeignKey(Category, verbose_name="Category", default='category') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # The Dahl-specific manager. class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = … -
Facebook Messenger Bot - Invalid URL button fields for List Template
I have been working to send a list to user containing some data. I am following facebook's doc to setup my request payload. However, I am getting the following error: {'error': { 'message': '(#100) Invalid URL button fields provided. Please check documentation for details.', 'type': 'OAuthException', 'code': 100, 'error_subcode': 2018125, 'fbtrace_id': 'GZFFcM+j5e/'}} Here is my JSON Payload: {'recipient': {'id': 'MY_MESSENGER_ID'}, 'message': {'attachment': {'type': 'template', 'payload': {'template_type': 'list', 'top_element_style': 'compact', 'elements': [{'title': 'Hello 1', 'subtitle': 'Subtitle 1', 'buttons': [{'title': 'View', 'type': 'web_url', 'url': 'https://www.medium.com/', 'messenger_extensions': 'false', 'webview_height_ratio': 'full', 'fallback_url': 'https://www.medium.com/'}], 'default_action': {'title': 'View', 'type': 'web_url', 'url': 'https://www.medium.com/', 'messenger_extensions': 'false', 'webview_height_ratio': 'full', 'fallback_url': 'https://www.medium.com/'}}, {'title': 'Hello 2', 'subtitle': 'Subtitle 2', 'image_url': 'https://cdn-images-1.medium.com/1*Vkf6A8Mb0wBoL3Fw1u0paA.jpeg', 'buttons': [{'title': 'View', 'type': 'web_url', 'url': 'https://www.medium.com/', 'messenger_extensions': 'false', 'webview_height_ratio': 'full', 'fallback_url': 'https://www.medium.com/'}], 'default_action': {'title': 'View', 'type': 'web_url', 'url': 'https://www.medium.com/', 'messenger_extensions': 'false', 'webview_height_ratio': 'full', 'fallback_url': 'https://www.medium.com/'}}]}}}} I have checked, re-checked it multiple times. PLUS, I have sent the facebook's example json from the doc but I have got the same reply. Please take a look and let me know where I am stuck! This is my end url: "https://graph.facebook.com/v2.6/me/messages?access_token=" Thanks in advance! -
Add field to model dynamically and still work with migrations Django >= 1.10
Using Django v1.10 I found this comprehensive answer regarding having dynamic model and fields in Django https://stackoverflow.com/a/7934577/80353 As the answer is starting to show its age, I am hoping to garner some more updated answers. At the same time, my scope is slightly different from the original poster of the question which that answer belonged to. I will state my scope as below: Right now, I have models and fields defined by me the developer. But the user wants to be able to add new fields when they need to. I have been using django-migrations as a way to propagate changes. I prefer to continue to use postgres and continue to still have migrations for these user-defined fields. So that it's easy for me to troubleshoot in case the user did something wrong. Not all models will allow users to dynamically add fields. Only a select few models which I deem okay will allow dynamic fields. By default, when the user defines the field, there are only 4 kinds: integer, decimal, text, varchar. All are default nullable and blankable. The length will also be set default. Essentially, the user cannot define the length or the nullable, blankableness. The user also …