I am testing Django for the first time to create my own to do list.
All has been working fine so far until I synchronise to my sqlite3 database with
python manage.py syncdb
I have managed to debug all the errors so far. The error I cant seem to debug is
TypeError: CASCADE() missing 4 required positional arguments: 'collector', 'field', 'sub_objs', and 'using'
Here is the model code:
class Item(models.Model):
worktasks = models.CharField(max_length=250)
focus = models.CharField(max_length=250)
#...
todo_list = models.ForeignKey('Todo', on_delete=models.CASCADE())
def __str__(self):
return self.worktasks + '-' + self.lessons
I've tried removing the brackets "()" after CASCADE which resulted in the output
Unknown command: 'syncdb'
I am working on Pycharm - Python Version 3.7
Your fix with removing brackets is correct, but this is only half of the problem. The second half is that you're trying to use a command that doesn't exist. syncdb is no longer present in new Django (it was removed in Django 1.9). Instead of it, you should use the migrations system. Take look at this documentation page.
Related
I am working with AWS Personalize and the Python SDK (boto3). All goes well until I try to include the context param in the request. While everything works as expected within the Personalize > Campaigns UI for testing the results, when I try to use the following code:
response = personalizeRt.get_recommendations(
campaignArn = 'arn:aws:personalize:XXXXXXXXXX:campaign/interactions-meta',
userId = '43f0c7fd-4d89-4752-9c88-2fe5bf7ac830',
context={
'GENRES' : '42'
}
)
I get the following error:
Unknown parameter in input: "context", must be one of: campaignArn, itemId, userId, numResults
Has anyone else seen this error? And if so, how did you resolve it.
Thanks in advance.
Seems the issue is the version of boto3/botocore within Pycharm. If I run the same code on the command line, all works as expected.
In Pycharm go to Preferences > Project Interpreter. and you can update boto3 there.
I am using django-phonenumber-field battery for my django app (django 1.9, python 3.5).
I have form like follows:
class PhoneChangeForm(forms.Form):
phonenumber = PhoneNumberField(widget=PhoneNumberPrefixWidget(attrs={'placeholder': _('Phone number')}),
label=_("Enter phone"))
def clean_phonenumber(self):
users = User.objects.filter(profile__phone__iexact=self.cleaned_data['phonenumber'])
if users.count() == 0:
return self.cleaned_data['phonenumber']
else:
raise forms.ValidationError(_("This phone is already in use."))
In my development environment this form works normally. If there is user with given phone number then ValidationError is raised.
When I am moving the same code into Production I have following error:
Django Version: 1.9.6
Exception Type: ProgrammingError
Exception Value: can't adapt type 'PhoneNumber'
Creators don't respond to the last comments so I decided to ask here. Can you suggest the best way to debug it
For Production I am using Postresql, for development Sqlite.
Based on this [answer][2] there is some kind of bug in Django's filter depending on DB backend. If to use Sqlite then:
User.objects.filter(profile__phone__iexact=self.cleaned_data['phonenumber'])
is working like a charm.
If to use Postrgres it will throw "can't adapt type". Converting the value into string explicitly will solve the problem:
users = User.objects.filter(profile__phone__iexact=str(self.cleaned_data['phonenumber']))
I'm currently writing some tests for a Django app. I've got the following standalone function in my app's signals.py file:
def updateLeaveCounts():
# Setting some variables here
todaysPeriods = Period.objects.filter(end__lte=today_end, end__gte=today_start).filter(request__leavetype="AN")
for period in todaysPeriods:
print period
counter = LeaveCounter.objects.get(pk=period.request.submitter)
# some Logic here
period.batch_processed = True
period.save()
and in my TestCase, I'm calling it as follows:
def test_johnsPostLeaveCounters(self):
# Some setup here
p = Period.objects.create(request=request,start=datetime(today.year,today.month,today.day,9),end=datetime(today.year,today.month,today.day,16,30),length='whole')
updateLeaveCounts()
self.assertEqual(p.batch_processed,True)
updateLeaveCounts() is catching my newly created Period object in the for loop (I can see its details printed to the console by print period), but my assertEqual() test is failing - telling me that the batch_processed attribute is still False.
It's as if the period.save() transaction isn't being called.
I'm aware that in Django versions prior to 1.8, you'd have to use the TransactionTestCase class, but I'm running 1.8.3 for this project at the moment, so I don't believe that's the issue.
Is there something I need to do to have the TestCases correctly reflect the model.save() action I'm performing in this function and hence have this function covered by tests?
Try to use refresh_from_db:
# ...
updateLeaveCounts()
p.refresh_from_db()
self.assertEqual(p.batch_processed, True)
# ...
So I know there are already a ton of questions by people who changed a model and then failed to apply the migration to their database. However, in my case, I know for a fact that the migration was applied, as I can see the new table data.
Basically, I installed django-cms, and then I added a field to the djangocms_column plugin's models.py to allow me to add a Bootstrap class name to my columns (e.g. col-md-4, col-md-6, etc.).
if hasattr(settings, "COLUMN_CLASS_CHOICES"):
CLASS_CHOICES = settings.COLUMN_CLASS_CHOICES
else:
CLASS_CHOICES = (
('col-md-1', _("col-md-1")),
('col-md-2', _("col-md-2")),
('col-md-3', _('col-md-3')),
('col-md-4', _("col-md-4")),
('col-md-5', _('col-md-5')),
('col-md-6', _("col-md-6")),
('col-md-7', _('col-md-7')),
('col-md-8', _('col-md-8')),
('col-md-9', _('col-md-9')),
('col-md-10', _('col-md-10')),
('col-md-11', _('col-md-11')),
('col-md-12', _('col-md-12')),
('', _('none')),
)
...
#python_2_unicode_compatible
class Column(CMSPlugin):
"""
A Column for the MultiColumns Plugin
"""
width = models.CharField(_("width"), choices=WIDTH_CHOICES, default=WIDTH_CHOICES[0][0], max_length=50)
"""
This is the new field:
"""
bs_class = models.CharField(_("bs_class"), choices=CLASS_CHOICES, default=CLASS_CHOICES[0][0], max_length=50)
def __str__(self):
return u"%s" % self.get_width_display()
I then ran ./manage.py makemigrations and then ./manage.py migrate, and now the table looks like this:
sqlite> select * from djangocms_column_column;
cmsplugin_ptr_id bs_class width
---------------- ---------- ----------
3 col-md-1 33%
5 col-md-1 33%
7 col-md-1 33%
19 col-md-1 33%
21 col-md-1 33%
23 col-md-1 33%
Yet when I try to access the test server, I still get the following error:
OperationalError at /en/
no such column: djangocms_column_column.bs_class
Request Method: GET
Request URL: http://localhost:8000/en/
Django Version: 1.7.10
Exception Type: OperationalError
Exception Value:
no such column: djangocms_column_column.bs_class
And, yes, I've tried deleting the database and running ./manage.py migrate, but the site still displays the same error. Is there a special migration procedure one must use to modify plugins installed in the ./env/lib/python2.7/site-packages folder?
So I actually figured out what was causing this behavior. In designing my gulp tasks, I restructured the project folder, putting all of my django-created files inside of a src subdirectory.
I did this thinking it'd be easier to watch my app files for changes this way without unintentionally triggering my watch tasks when gulpfile.js or files in bower_components were modified. (Ultimately, it didn't matter, since my globs were more specific than just the django project root.)
This wouldn't have been a problem except that settings.DATABASES['default']['NAME'] was the relative path project.db. As a result, when I ran ./manage.py migrate from within the /src directory, it performed the migrations on /src/project.db. And when I ran src/manage.py migrate from the parent directory, the migrations were performed on /project.db. The djangocms app itself was using the latter, while I'd been performing all of my migrations on the former.
So the lessons here are:
Make sure your sqlite file is specified using an absolute path.
When you encounter seemingly inexplicable migration issues, check to make sure you don't have multiple .db files floating around in your workspace.
Have you tried deleting migrations in migration folder inside the app?
I have a process_view middleware that sets the module and view names into the request like this:
class ViewName( object ):
def process_view( self, request, view_func, view_args, view_kwargs ):
request.module_name = view_func.__module__
request.view_name = view_func.__name__
I use the names together as a key for session based pagination.
But as of yesterday, for reasons I am unable to discover,
view_func.__module__ now returns 'cp.models', which is a model file in
one of my apps.
I've gone back one commit at a time trying to find the cause. The issue is still there even after reverting code to more than a month ago.
I'm seeing only two python packages changed recently on the server, my app uses neither, and the updates were more than a month ago:
cat /var/log/dpkg.log*|grep "upgrade" |grep python
2013-01-25 03:41:05 upgrade python-problem-report 2.0.1-0ubuntu15.12.0.1-0ubuntu17.1
2013-01-25 03:41:06 upgrade python-apport 2.0.1-0ubuntu15.1 2.0.1-0ubuntu17.1
I also tried rearranging my middleware list, didn't help.
Any idea what else might be causing this issue?